render a partial from inside a model

Have you ever wanted to render a partial to a string from inside a model?

This solution was inspired by this snippet showing how to use view helpers in a controller. It’s clean and simple, no need to mess with ERB or metaprogramming!


class Model

  class Helper < ActionView::Base
    include Singleton
  end
  def help
    Helper.instance
  end

  ...

  def summarize
    ## Note that we have to use the FULL path here!  
    help.render( :partial => "#{RAILS_ROOT}/app/views/notifications/text_order_summary", :object => self )
  end
  alias_method :to_s, :summarize

end

actionmailer ActionView ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factory pattern filemerge find and replace finder fink fixtures fun gem google maps helper helpers imagemagick Intertrust javascript logo math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism prototype.js rails rake rmagick RSA encryption ruby script shoulda subversion SyncTV TDD testing textmate tricks unique hashes unix shell validation view yaml zebra stripes