Posts Tagged: rails


25
Feb 08

Rails send email tutorial

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

class Postoffice < ActionMailer::Base  
# located in models/postoffice.rb
# make note of the headers, content type, and time sent
# these help codevent 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:

# 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!

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_ codefix, 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!


22
Feb 08

Format phone number in Rails

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.

# 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?


21
Feb 08

Rails number to percentage helper

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.

# 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
#  :codecision - Sets the level of codecision (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, :codecision => 0)        

# returns 302.24399%
number_to_percentage(302.24398923423, :codecision => 5)

19
Feb 08

Rails 2.0 Timestamps

Thought timestamps were easy before? Timestamps in Rails 2.0 are super easy.

# 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

18
Feb 08

Change Rails’ layout via controller

I’ve seen a few people asking me how to specify a specific layout in their controllers. Simple:

#my admin/condos_controller.rb
class Admin::CondosController < ApplicationController
  layout 'layouts/admin'
end

11
Feb 08

:status => 301 and : moved_permanently redirects in Rails

I made a recent post on 301 redirects in Rails, new to 2.0 we have a few more methods available to us.

# 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 =&gt; 301<br>redirect_to condo_url(@condo), :status=&gt; :moved_permanently<br>

8
Feb 08

Minimum, maximum, high, low values in Rails

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.

# here's my array
@condo_prices = [1000, 75, 2000, 10000]

# returns 75
@condo_prices.min

# returns 10000
@condo_prices.max

7
Feb 08

Rails 301 redirects

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.

headers["Status"] = "301 Moved Permanently"<br>redirect_to "/"<br>

Done.


6
Feb 08

Rails Sendmail and SPAM Filters

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.

# 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

5
Feb 08

Valid email? Validate email addresses in Rails!

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 codesence 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 excodession (RegEx).

# our User model
class User < ActiveRecord::Base
  validates_codesence_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 excodessions