Veerasundaravel's Ruby on Rails Weblog

August 9, 2011

Rails ActionMailer – Use multipart/alternative as content_type of email


Rails uses plain/text as the default content_type for sending email, you can change it to text/html that email clients can display html formatted email.

But not all the email clients support html format well, we should make our sent emails support both plain text and html format for different email clients.

text/plain:

By default Rails sending an email with plain/text content_type, for example

# app/models/notifier.rb
def send_email(email)
  subject       email.subject
  from          email.from
  recipients    email.recipients
  sent_on       Time.now
  body          :email => email
end

# app/views/notifier/send_email.html.erb
Welcome to here: <%= link_to @email.url, @email.url %>

The sent email is a plain text email

Date: Tue, 9 Aug 2011 16:38:07 +0800
From: VeeraaWP <veeraa@wordpress.com>
To: some-user@gmail.com
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8

Welcome: <a href="https://veerasundaravel.wordpress.com">http://veerasundaravel.wordpress.com</a>

The link url is just displayed as a plain text because of the email content_type.

text/html:

If we want the email clients to display link url as html format, we should change the content_type to text/html.

# app/models/notifier.rb
def send_email(email)
  subject       email.subject
  from          email.from
  recipients    email.recipients
  sent_on       Time.now
  content_type     "text/html"
  body          :email => email
end

# app/views/notifier/send_email.html.erb
Welcome to here: <%= link_to @email.url, @email.url %>

Now the sent email is a html formatted email

Date: Tue, 9 Aug 2011 16:38:07 +0800
From: VeeraaWP <veeraa@wordpress.com>
To: some-user@gmail.com
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8

Welcome: <a href="https://veerasundaravel.wordpress.com">http://veerasundaravel.wordpress.com</a>

Now the email client can display the link url correctly with html format.

multipart/alternative:

But we can’t promise that all the email clients support the html format and some users will set the email client to display plain text email instead of html formatted email. How should we do?

We should use multipart/alternative as email content_type to support both text/plain and text/html emails.

# app/models/notifier.rb
def send_email(email)
  subject          email.subject
  from             email.from
  recipients       email.recipients
  sent_on          Time.now
  content_type     "multipart/alternative"

  part :content_type => "text/html",
    :body => render_message("send_email_html", :email => email)

  part "text/plain" do |p|
    p.body = render_message("send_email_plain", :email => email)
    p.transfer_encoding = "base64"
  end
end

# app/views/notifier/send_email_html.erb
# app/views/notifier/send_email_plain.erb

As you see, we can set the email content_type to multipart/alternative, then define content_type text/html render the file app/views/notifier/send_email_html.erb and content_type text/plain render the file app/views/notifier/send_email_plain.erb. So the sent email is as follows

Date: Tue, 9 Aug 2011 16:17:35 +0800
From: VeeraaWP <veeraa@wordpress.com>
To: some-user@gmail.com
Mime-Version: 1.0
Content-Type: multipart/alternative; boundary=mimepart_4c5a739f40ca1_967c1a0d6123

--mimepart_4c5a739f40ca1_967c1a0d6123
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: Quoted-printable
Content-Disposition: inline

Welcome: <a href="https://veerasundaravel.wordpress.com">http://veerasundaravel.wordpress.com</a>

--mimepart_4c5a739f40ca1_967c1a0d6123
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: Quoted-printable
Content-Disposition: inline

Welcome: <a href="https://veerasundaravel.wordpress.com">http://veerasundaravel.wordpress.com</a>

--mimepart_4c5a739f40ca1_967c1a0d6123--

As you see, the content_type of email is multipart/alternative now, and the body of email is divided into two parts, one is for text/plain, the other is for text/html. So email clients can decide which format of email to display.

Convention:

It’s cool, but can the codes be simpler? Of course, there is a convention to simplifier the multipart/alternative content_type

def send_email(email)
  subject          email.subject
  from             email.from
  recipients       email.recipients
  sent_on          Time.now
  body             :email => email
end

# app/views/notifier/send_email.text.plain.erb
# app/views/notifier/send_email.text.html.erb

Please note the file extensions for notifier send_email method, one is .text.plain.erb, the other is .text.html.erb, they are the email views for text/plain and text/html according to their names. ActionMailer will detect the file extension, if .text.plain and .text.html exist, the content_type of email will be set to multipart/alternative automatically.

In rails3: the mail view file names should be send_email.html.erb and send_email.text.erb


Related articles:

Rails, email and multipart/alternative (olddognewtricks.co.uk)
Rails Best Practices (rails-bestpractices.com)

October 7, 2010

Useful Rails Commands – Cheatsheet

Filed under: Ruby On Rails — Tags: , , , , , , , — Veerasundaravel @ 3:08 pm

These are the commands,  we ROR folks use often in development. Please refer and let me know if there is any missing.

rails ApplicationName – Create a new application
ruby script/generate model ModelName – Creates a model with the specified model_name
ruby script/generate controller ControllerName – Creates a controller with the specified controller_name
ruby script/generate migration MigrationName – Creates a migration with the specified migration_name
ruby script/generate scaffold ModelName ControllerName – A shortcut for creating your controller, model and view files etc.
ruby script/destroy controller ControllerName – Destroys the created controller and its related file. Same way you can destroy your model, migration files etc.
ruby script/server – start ruby server at http://localhost:3000
ruby script/plugin install PluginName – Installs the specified plugin.
ruby script/console – Opens the rails console for the current RAILS_ENV
ruby script/dbconsole – Opens the DB console for the current RAILS_ENV
ruby script/performance – For benchmarkering and profiling your application.

rake –tasks – Lists all available rake tasks
rake db:create – Create the database defined in config/database.yml for the current RAILS_ENV
rake db:drop – Drops the database for the current RAILS_ENV
rake db:migrate – Migrate the database through scripts in db/migrate folder.
rake db:reset – Drops and recreates the database from db/schema.rb for the current environment.
rake db:schema:dump – Create a db/schema.rb file that can be portably used against any DB supported by AR
rake doc:app – Build the RDOC HTML Files
rake db:sessions:create – Creates a sessions migration for use with CGI::Session::ActiveRecordStore
rake gems – List the gems that this rails application depends on
rake gems:install – Installs all required gems for this application.
rake log:clear – Truncates all *.log files in log/ to zero bytes
rake rails:freeze:gems – Lock this application to the current gems (by unpacking them into vendor/rails)
rake routes – Print out all defined routes in match order, with names.
rake test – Run all unit, functional and integration tests
rake test:functionals – Run tests for functionalsdb:test:prepare / Run the functional tests in test/functional
rake test:integration – Run tests for integrationdb:test:prepare / Run the integration tests in test/integration
rake test:units – Run tests for unitsdb:test:prepare / Run the unit tests in test/unit
rake tmp:clear – Clear session, cache, and socket files from tmp/

gem list – Lists all the installed gems.
gem install GemName – Installs the specified gem in to your machine.
gem uninstall GemName – Uninstalls the specified gem from your machine.
gem server – present a web page at http://localhost:8808/ with info about installed gems.

Alos refer:

Useful Rails3 Commands & Cheatsheet
Useful SVN and Git commands – Cheatsheet

February 23, 2010

Check list for Rails application

Filed under: Ruby On Rails — Tags: , , , , , , , , — Veerasundaravel @ 11:34 am

I just surfed through google for good optimized and general check list for a rails application, here I listed some useful tips which will help you lot.

Code formatting:

1. Indentation – The blank space between a margin and the beginning of an indented line. Use 2 space indent, no tabs.

2. Add required comments and reference links where ever possible.

3. Remove unwanted spaces and new lines. That will reduce the size of file and give better readability.

* Use spaces around operators, after commas, colons and semicolons,
around { and before }.

* No spaces after (, [ and before ], ).

* Use two spaces before statement modifiers (postfix
if/unless/while/until/rescue).

* Use an empty line before the return value of a method (unless it
only has one line), and an empty line between defs.

* Use empty lines to break up a long method into logical paragraphs.

* Keep lines fewer than 80 characters.

* Avoid trailing whitespace.

http://pub.cozmixng.org/~the-rwiki/rw-cgi.rb?cmd=view;name=RubyCodingConvention

General App:

1. Try to use maximum of scaffold to generate resources(model, controllers, views)

2. Never put log files or database.yml file into version control systems(git/svn).

3. Never put temporary files and cache files like files under /tmp folder etc into version control systems(git/svn).

4. Unpack all required gems and freeze rails gems.

5. Session data should be stored in the database.

6. Application must have Unit and Functional tests.

7. Use Rspec for testing. Rspec is available as plugin

8. Controller Methods should be no longer than 5-8 lines of code.

9. Try to limit each controller’s actions to: index, new, create, edit, update, destroy. This is not always possible. However, if you notice that a given controller has more than 10 methods, it probably time to refactor.

http://www.rorexperts.com/rails-application-development-standards-t1302.html

10. Use custom configuration files

11. Use constants for repeated strings like APP_DOMAIN = ‘mydomain.com’

12. Keep time in UTC format.

13. Keep your controllers and view files Skinny.

Database and Model:

1. Use indexing for applicable table columns.

2. Store big size of data like images contents and bigger text in separate table.

3. Always don’t select all the columns from your table, when it is not required.

4. Design your table with minimum number of columns.

5. Avoid eager loading of active records.

6. Always use model associations to create associated records etc.

7. Use generic names for model association, for example users in our application is going to use email optoins.

Models: User-UserMessage-Message

so the associations will look below is not a good name
user has_many :messages
message belongs_to :user

instead of above try the association names like below:
user has_many :sent_messages
user has_many :received_messages
message belongs_to :sender
message has_many :receivers

8. Try to include associated table in your find query, if you want to use them.

General – Extended

1. Readme file should be application specific and mentions the functionality and usage information
2. Automated deployment with capistrano wherever possible
3. log all exceptions
4. expose API for all models with admin credentials, this would make it easy to populate the data
5. send a release notes for each deployment

%d bloggers like this: