February 25, 2008

Want to send an email using Rails? I struggled with this for a while and I’m sure many of you do too. This post will cover the basic implementation of a mailer, it is tested to work in Rails 2.0.2.
Rails Mailer Overview
1) script/generate mailer postoffice
2) Create a method for your mailer (models/postoffice.rb)
3) Create your email template using welcome.text.html.erb and welcome.text.plain.erb (views/postoffice)
4) Deliver your message
5) If you’re testing locally, make sure postfix is running
Begin by opening your terminal:
add3-imac: jon$ rails mailer_example
-- output truncated --
add3-imac: jon$ cd mailer_example/
add3-imac:mailer_example jon$ script/generate mailer postoffice
exists app/models/
create app/views/postoffice
exists test/unit/
create test/fixtures/postoffice
create app/models/postoffice.rb
create test/unit/postoffice_test.rb
Next, we are going to create a method for our mailer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| class Postoffice < ActionMailer::Base
# located in models/postoffice.rb
# make note of the headers, content type, and time sent
# these help prevent your email from being flagged as spam
def welcome(name, email)
@recipients = "user@host.com"
@from = params[:contact][:email]
headers "Reply-to" => "#{email}"
@subject = "Welcome to Add Three"
@sent_on = Time.now
@content_type = "text/html"
body[:name] = name
body[:email] = email
end
end |
Now that our method is created, let’s modify the email templates:
1
2
3
4
5
6
7
8
9
10
11
12
13
| # located in views/postoffice
# we can access the variables we declared in models/postoffice.rb
# body[:name] = name is accessed by @name
# body[:email] = email is accessedby @email
# welcome.text.html.erb
# note the HTML
<p>Welcome to AddThree <i><%= @name %></i>. </p>
<p>The address we have on file for you is <b><%= @email %></b>, please let us know if this is incorrect.</p>
# welcome.text.plain.erb
Welcome to AddThree <%= @name %>. The address we have on file for you is <%= @email %>, please let us know if this is incorrect. |
Now that our mailer and templates arein place, let’s deliver the email!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| class Registration < ApplicationController
# controllers/registration_controller.rb
# assume the Registration controller already existed
# assume @user.name and @user.email have been declared
def send_welcome_email
# triggered via:
# http://localhost:3000/registration/send_welcome_email
# note the deliver_ prefix, this is IMPORTANT
Postoffice.deliver_welcome(@user.name, @user.email)
# optional, but I like to keep people informed
flash[:notice] = "You've successfuly registered. Please check your email for a confirmation!"
# render the default action
render :action => 'index'
end
end |
If you’re testing locally, make sure postfix is running
add3-imac:mailer_example jon$ sudo postfix start
Password:
postfix/postfix-script: starting the Postfix mail system
Everything should be working! Was this helpful? Link to me and leave a comment!
February 22, 2008

Recently, I have needed to take a number string and format it to a phone number. This was a PITA in PHP, fortunately, Rails includes some methods that will make the formatting of phone numbers much easier.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
| # number_to_phone(number, options = {})
# Formats a number into a US phone number (e.g., (555) 123-9876).
# You can customize the format in the options hash.
#
# Options
#
# :area_code - Adds parentheses around the area code.
# :delimiter - Specifies the delimiter to use (defaults to "-").
# :extension - Specifies an extension to add to the end of the generated number.
# :country_code - Sets the country code for the phone number.
# returns => 123-555-1234
number_to_phone(1235551234)
# returns => (123) 555-1234
number_to_phone(1235551234, :area_code => true)
# returns => 123 555 1234
number_to_phone(1235551234, :delimiter => " ")
# returns => (123) 555-1234 x 555
number_to_phone(1235551234, :area_code => true, :extension => 555)
# returns => +1-123-555-1234
number_to_phone(1235551234, :country_code => 1)
# returns => +1.123.555.1234 x 1343
number_to_phone(1235551234, :country_code => 1, :extension => 1343, :delimiter => ".") |
Want to see it in action?
February 21, 2008

In the next few days I’m going to quickly touch on a few of Rail’s number helper methods. Lately I’ve been doing a lot of mathematical calculations that require percentages, the number_to_percentage method is quite handy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # number_to_percentage(number, options = {})
# Formats a number as a percentage string (e.g., 65%). You can customize the format in the options hash.
# Options
# :precision - Sets the level of precision (defaults to 3).
# :separator - Sets the separator between the units (defaults to ".").
# Examples
# returns 100.000%
number_to_percentage(100)
# returns 100%
number_to_percentage(100, :precision => 0)
# returns 302.24399%
number_to_percentage(302.24398923423, :precision => 5) |
February 19, 2008

Thought timestamps were easy before? Timestamps in Rails 2.0 are super easy.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| # before
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.column :name, :string
t.column :subscribed, :boolean, :default => true
t.column :created_on, :timestamp
t.column :updated_on, :timestamp
end
end
def self.down
drop_table :users
end
end
# after
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.boolean :subscribed, :default => true
t.timestamps
end
end
def self.down
drop_table :users
end
end |
February 18, 2008

I’ve seen a few people asking me how to specify a specific layout in their controllers. Simple:
1
2
3
4
| #my admin/condos_controller.rb
class Admin::CondosController < ApplicationController
layout 'layouts/admin'
end |
February 11, 2008

I made a recent post on 301 redirects in Rails, new to 2.0 we have a few more methods available to us.
1
| # prior method<br>headers["Status"] = "301 Moved Permanently"<br>redirect_to "/"<br><br># condo has been defined as a resource in my route.rb<br>redirect_to condo_url(@condo), :status => 301<br>redirect_to condo_url(@condo), :status=> :moved_permanently<br> |
February 8, 2008

Have an array that needs sorting? Perhaps you have a range of condominiums and you want to know the highest and lowest priced properties? Check it.
1
2
3
4
5
6
7
8
| # here's my array
@condo_prices = [1000, 75, 2000, 10000]
# returns 75
@condo_prices.min
# returns 10000
@condo_prices.max |
February 7, 2008

301 redirects are one of the best ways to inform search engines that your URLs have changed. They’re simple to implement, so you should have no reason not to use them.
1
| headers["Status"] = "301 Moved Permanently"<br>redirect_to "/"<br> |
Done.
February 6, 2008

One of the sites we’re working on sends an email upon the completion of a registration form. We were having problems with different SPAM filters catching and misflagging our emails. After doing a little research, it looks like we were omitting some important fields. Take a look at the before and after implementation.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| # before
# note the lack of headers, sent on, and content type declarations
class Postoffice < ActionMailer::Base
def welcome(email)
@recipients = email
@from = "Meeta Support <happy2help@meeta.com>"
@subject = "Welcome to Meeta.com"
body[:email] = email
end
def contact(params)
end
end
# after
class Postoffice < ActionMailer::Base
protected
def welcome(email)
@recipients = email
@from = "Meeta Support <happy2help@meeta.com>"
headers "Reply-to" => "happy2help@meeta.com"
@subject = "Welcome to Meeta.com"
@sent_on = Time.now
@content_type = "text/html"
body[:email] = email
end
end |
February 5, 2008

Let’s face it, most of us creating apps collect at a very minimum a name and email address. By a simple validation method to our model, we can easily check the length, format, and presence of our fields. Checking the format of an email address is also simple, but requires a little more work. Using validates_format_of we are able to validate an email address against a regular expression (RegEx).
1
2
3
4
5
| # our User model
class User < ActiveRecord::Base
validates_presence_of :email
validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
end |
Read up on validations at the Rails API
Read up on regular expressions