Archive for November, 2008

Merb simple_format helper

Merb does not have a simple_format helper like in Rails so you can do the following.

Add this to your Application Helper

1
2
3
4
5
6
7
8
9
10
11
      def simple_format(text, html_options={})
        text = text.to_s.dup
        text.gsub!(/\r\n?/, "\n")
        text = text.split(/\n\n+/)
        formatted_text = ""
        text.each do |line|
          line.gsub!(/([^\n]\n)(?=[^\n])/, '\1<br />')
          formatted_text << tag(:p, line, html_options) + "\n\n"
        end
        formatted_text
      end

Use in your view
<%= simple_format(@page.body) %>
<%= simple_format(@page.body, :class => ‘hello’) %>

Thanks goes to matteti for enlighting me on the fact that I could start with the rails simple_format helper and configure as necessary.

Remove quoted text from reply emails in rails

the code

and with rough context:

Thanks malkomalko

Setup Paperclip plugin with Amazon S3 to upload videos in rails

This is taken from Clayton Lengel-Zigich. Thanks.

Create a video model.rb

Configure the config/s3.yml file

Configure and install right_aws gem

Then run: sudo rake gems:install & sudo rake gems:unpack

Create a videos controller with the prospective views for the uploading

Configure flash player to display video

1. Download JW FLV MEDIA PLAYER (mediaplayer.zip download link)
2. Copy and paste the player.swf file at public/flash/player.swf
3. Copy and paste the swfobject.js at public/javascript/swfobject.js
4. Configure your application.html.erb file to call swfobject.js in the head

That’s it, you should now be able to upload flv video files and view them in a flash player by going to http://localhost:3000/videos. For instructions on converting quicktimes videos to flash videos on file upload take a look at Jim Neath’s tutorial on converting videos with rails.

Development vs Production mode

It’s a good idea to create a bucket for development and a bucket for production. If you decide to, you can do the following.
Note:this assumes you started your app with bort, and already have a settings.yml that gets loaded by the load_config.rb file using APP_CONFIG = YAML.load_file(”#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].symbolize_keys)

In config/settings.yml

In video.rb

Merb: Seeing your routes

Here’s how to see your routes in merb using rake and irb.

It’s similar to rake:routes in rails.

1
rake audit:routes

Or in irb

merb -i
merb.show_routes

How to run rake in production mode on your server

This is a really brittle way to do this, but sometimes I find myself needing a quick rake task than I can just run from my server’s command line - rather than incorporating it into my deploy tasks.

Using Gmail with IMAP to Receive Email in Rails (cron job version)

This pretty much comes about because of RailsTips and Peepcode. Thank you guys.

Goal

You want your user to be able to send an email and have that email get posted as a comment to the rails app.

Requirements

1. Your rails app should already have the ability to send out emails
2. Your Rails app must already be capified via Capistrano or similar with some type of deployment recipe
3. You need an additional gmail or google apps account with imap enabled
4. You need the ability to run cron jobs on your server

Configuration

First, setup the cron task and make it easy to run with cap deploy:start and cap deploy:stop

Create file lib/tasks/chores.rake

Create file config/cron.erb

Add the following near the end of your deploy.rb file

Second, setup the login information for the gmail mail account we will use to receive emails through.

Create file config/mail.yml and configure for imap

Install lockfile and tmail cause your gonna need them:
sudo gem install lockfile
sudo gem install tmail

Edit environment.rb

Retrieve the email and save to the database

Edit lib/tasks/chores.rake and put the following code inside the each_minute task. (credit for this goes to John of RailsTips.org though I added a quick fix to handle multipart emails)

Deployment

Deploy your app as usual with cap deploy

Next, run cap cron:start to start up the cron task. This will run every minute.

Send an email to the account you specified in mail.rb and after one minute you should see the email saved as a comment on the app.

Creating a contact form mailer in merb using sendmail and merb-mailer

I posted all this in the wiki here, but in case it changes and simply as documentation for myself, I am reposting it here. Much of it is pieced together from various places.

===== Installation =====
The gem merb-mailer is already installed as part of the standard merb installation via sudo gem install merb. See http://github.com/wycats/merb/tree/master

But if you are missing it, do:

sudo gem install merb-mailer

It will install “mailfactory”:http://mailfactory.rubyforge.org/ gem and “mime-types”:http://mime-types.rubyforge.org/ that mailfactory depends on.

===== Configuration =====
Assuming you created an app using ‘merb-gen app’, merb-mailer will already be listed in config/dependencies.rb. If you started your app using ‘merb-gen core’ then you will need to include merb-mailer as a dependency like the following:

In init.rb, put this at the top

1
require 'config/dependencies.rb'

In config/dependencies.rb

1
2
3
4
5
6
# dependencies are generated using a strict version, don't forget to edit the dependency versions when upgrading.
merb_gems_version = "1.0"
dm_gems_version   = "0.9.6"
 
# For more information about each component, please read http://wiki.merbivore.com/faqs/merb_components
dependency "merb-mailer", merb_gems_version

In init.rb configure for sendmail (see below for other config options like smtp). Alternatively, you can put this in development.rb if your production.rb email setup might use smtp instead or vice versa. Development.rb and production.rb will override the init.rb file.

1
2
3
4
5
Merb::BootLoader.after_app_loads do
  # This will get executed after your app's classes have been loaded.
  Merb::Mailer.config = {:sendmail_path => '/usr/sbin/sendmail'}
  Merb::Mailer.delivery_method = :sendmail
end

(Type “which sendmail” to verify where sendmail is located on your machine.)

See http://merbivore.com/documentation/current/doc/rdoc/merb-mailer-1.0/index.html for documented config options.

===== Using Merb mailers =====
Merb separates out its mailers into its only little MVC so things work a little differently than you might be used to with Rails. But it’s for the better.

==== First, setup the mailer. ====

merb-gen mailer contact

This will generate a mailer controller and a mailer view under app/mailers

Open up app/mailers/contact_mailer.rb and make it look like the following:

1
2
3
4
5
6
7
8
class ContactMailer < Merb::MailController
 
  def notify
    @user = params[:user]
    render_mail
  end
 
end

Edit app/mailers/views/contact_mailer/notify.text.erb

1
Tall tube socks with red stripes. The right sock has a large whole near the big toe.

==== Now put the mailer to use inside a controller ====
**Generate a static controller**

merb-gen controller static

**Create an index action and contact action for the static controller**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Static < Application
 
  # ...and remember, everything returned from an action
  # goes to the client...
  def index
    render
  end
 
  def contact
    send_mail(ContactMailer, :notify, {
      :from => 'yourself@email.com',
      :to => "someoneelse@gmail.com",
      :subject => "Free gym socks. Used!"
    })
 
    render
  end
end

**Make sure your routes are setup properly in router.rb**

1
2
3
4
5
Merb::Router.prepare do
  match('/index').to(:controller => "static", :action => "index").name(:index)
  match('/contact').to(:controller => 'static', :action =>'contact').name(:contact)
  match('/').to(:controller => 'static', :action =>'index')
end

**Make sure your views (static/index.html.erb and static/contact.html.erb) are setup to some degree**

1
2
3
4
5
# index.html
<h2>Home page</h2>
 
# contact.html
<h2>Contacto!</h2>

**Navigate to http://localhost:4000/contact and it should work!**

See http://github.com/wycats/merb/tree/master/merb-mailer for additional details.

It you have problems make sure postfix is running with sudo postfix stop and then sudo postfix start). You should also see the email get sent in your merb development server output. It should look something like the following:

merb : worker (port 4000) ~ notify sent to someoneelse@gmail.com about =?utf-8?Q?Free_gym_socks._Used!?=

===== Creating a contact form =====
This assumes you’ve followed the above instructions so far. This also assumes usage with datamapper.

Create a contact model

merb-gen model contact

Edit models/contact.rb to look like the following:

1
2
3
4
5
6
7
8
9
10
11
class Contact
  include DataMapper::Resource
 
  property :id, Serial
  property :name, String, :nullable => false
  property :email, String, :nullable => false
  property :message, String, :nullable => false
 
  validates_format :email, :as => :email_address
 
end

Edit the static controller’s contact action. This renders the contact page unless the form is submitted using request.post? Then the contact information is saved with datamapper (but not to the database) and our ContactMailer notify action is used to send the mailer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# static.rb controller
  def contact
    if request.post?
      @contact = Contact.new(params[:contact])
      if @contact.valid?
        send_mail(ContactMailer, :notify, {
          :from => @contact.email,
          :to => 'scott@scottmotte.com',
          :subject => "New message from contact form"
        }, { :contact => @contact})
        render "Thank you. Your message has been sent."
      else
        render :contact
      end
    else
      @contact = Contact.new
      render
    end
  end

Edit the contact action’s view at views/static/contact.html.erb

1
2
3
4
5
6
7
8
<h2>Contact</h2>
<%= error_messages_for @contact %>
<%= form_for @contact, :action => url('contact') do %>
     <p><%= text_field :name, :label => 'Name' %></p>
     <p><%= text_field :email,  :label => 'Email' %></p>
     <p><%= text_area :message, :label => 'Message' %></p>
     <%= submit 'Send' %>
<% end =%>

Your contact form should now send emails and do validations if items aren’t filled in. We still have to pass the values to the emailed message though so let’s take a look at our mailers/contact_mailer.rb and its prospective view to do this.

Edit contact_mailer.rb

1
2
3
4
5
6
7
8
9
class ContactMailer < Merb::MailController
 
  def notify
    # use params[] passed to this controller to get data
    @contact = params[:contact]
    render_mail
  end
 
end

Edit notify.text.erb

1
2
3
4
5
6
7
Name: <%= @contact.name %>
 
Email: <%= @contact.email %>
 
Message:
 
<%= @contact.message %>

**That’s it. You’re done.** You could also customize things a bit here, by creating a global from email in devlopment.rb and production.rb by putting something like ‘SITE_EMAIL = “you@domain.com”‘ at the end of those files.

Beginner’s guide to installing merb

Merb is very cool, but one thing that bothers me is that it is still tough to simply get installed - even at 1.0. The guys working on merb are seriously awesome and amazing. Their progress might even be told in programming history books one day, but installing all the parts of merb has always been a bit painful.

Here’s what I did.

First your gonna need datamapper or the install from merb edge will send a hissy fit.

sudo gem install dm-core dm-more

(hopefully, this will soon just be datamapper - would make more sense)

Then merb:

sudo gem install merb --source http://edge.merbivore.com

Then merb-plugins

cd ~/sources
git clone git://github.com/wycats/merb-plugins.git 
cd merb-plugins
sudo rake install

(hopefully this will become a gem soon too)

You’re also gonna need webrat - even if you don’t end up using it.

sudo gem install webrat

You’re also going to have to create a test database once you setup an app. To do that first edit your database.yml file, then do the following to actually generate that database.

rake db:create MERB_ENV=test

Then run the migrations with:

rake db:automigrate MERB_ENV=test

(there used to be a db:test:clone rake task for this, but it seems to be no more as of this posting so you instead specify the MERB_ENV as the ‘test’ environment)

Now you’ll be able to run autotest

How to install ffmpeg on ubuntu hardy on slicehost

sudo apt-get install ffmpeg

It seems ffmpeg is now distributed through apt-get making things much easier. The above should work just fine.

Originally, I followed these instructions, but to no avail. I then scoured the web trying multiple different steps but still no luck.

On a side not, here’s how to install ffmpeg on mac os x leopard for testing of your app on localhost with ffmpeg.

Explaining the names behind the ubuntu source lists - multiverse, universe, main, restricted

Thanks goes to Ryan52 for his explanation of this on the #slicehost irc.

multiverse is non free not officially supported.
restricted is non free officially supported.
main is free officiaully supported.
universe is non free officially supported.

This information was particularly helpful. I was missing multiverse at the end of my sources list at /etc/apt/sources.list

It looked like this:

deb http://archive.ubuntu.com/ubuntu/ hardy main restricted universe
deb-src http://archive.ubuntu.com/ubuntu/ hardy main restricted universe
 
deb http://archive.ubuntu.com/ubuntu/ hardy-updates main restricted universe
deb-src http://archive.ubuntu.com/ubuntu/ hardy-updates main restricted universe
 
deb http://security.ubuntu.com/ubuntu hardy-security main restricted universe
deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted universe

and now it looks like this thanks to Ryan52s knowledge

deb http://archive.ubuntu.com/ubuntu/ hardy main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ hardy main restricted universe multiverse
 
deb http://archive.ubuntu.com/ubuntu/ hardy-updates main restricted universe multiverse
deb-src http://archive.ubuntu.com/ubuntu/ hardy-updates main restricted universe multiverse
 
deb http://security.ubuntu.com/ubuntu hardy-security main restricted universe multiverse
deb-src http://security.ubuntu.com/ubuntu hardy-security main restricted universe multiverse

Then I just ran sudo aptitude update to update my sources list.

I recently had to do this to get download some lib files using apt-get. In particular: http://packages.ubuntu.com/hardy/libdevel/libx264-dev when trying to follow Jim Neath’s tutorial on installing FFMPEG