Wednesday, April 13, 2011

Rendering from a Model in Rails 3

Call me 'rebel', but it happened to me that I had to render text from a ruby class.
I was composing text withing a regular class to send personalized SMS's and I wanted to use 'erb' templates and some other view utilities. Even it is not the Rails way, I wanted to do so.

Here are the tricks I used to build the logic. Key points are:
- how to get access to the view context
- how to get access to the path and the erb templates
- hot to get access to the url helpers in case you need form an url

class MyModel < ActiveRecord::Base
   # Use the my_models/_my_model.txt.erb view to render this object as a string
  def to_s
    url = helpers.new_user_url :host => default_host
    view =
    text = view.render(
      :partial => 'my_models/my_model', :format => :txt,
      :locals => { :my_model => self, :url => url}
  def views_path
    @views_path ||=

  def self.helpers
    @helpers ||= Rails.application.routes.url_helpers

  def default_host
    #you need to configure it in your /config/environments/*.rb files
    # for example:   config.action_mailer.default_url_options = { :host => 'localhost:3000' }
    @default_host ||= Rails.configuration.action_mailer.default_url_options[:host]

No comments:

Post a Comment