Skip to content

Instantly share code, notes, and snippets.

@wdiechmann
Created February 23, 2012 12:03
Show Gist options
  • Save wdiechmann/1892556 to your computer and use it in GitHub Desktop.
Save wdiechmann/1892556 to your computer and use it in GitHub Desktop.
Rendering a string of Erb/HAML back to a string (render :partial from everything else but filesystem)
# My intention is to be able to do this:
#
# from within some view, render a partial
# with the added flavour that the partial is not a file
# but rather a table model instance - like say a Customer,
# a PurchaseOrder, or in this case - a Template
# the partial rendering "should" adhere to all the standard Rails
# magic, ie nested rendering of partials, builders with Erb/HAML,
# I18n translation support to label the most important.
# Regrettably I'm not a very good BDD/TDD'er so my tests stinks - hence
# this elaborate example <:(
# First I write the code I'd wish I had:
#
# views/users/mailer/confirmation_instructions.haml
= build_from_template( { template: 'mail confirmation' })
# which requires me to include some Helpers
#
# mailers/users/mailer.rb
class Users::Mailer < Devise::Mailer
default :from => '[email protected]'
add_template_helper(ApplicationHelper)
end
# and write the function in ApplicationHelper
#
# helpers/application_helper.rb
def build_from_template( options={})
tmpl = options.delete(:template)
tmpl = tmpl.class==String ? Template.find_by_name(tmpl) : tmpl
tmpl.render_template( options )
end
# I also have to do a migration which
# builds a table 'templates' and a model in models
#
# > rails generate model Template name:string, content:text, liquid_tempalte:text
#
# what eventually leads me to the model
#
# models/template.rb
class Template < ActiveRecord::Base
def render_template(options = {})
options.merge!( template: self, logger: Rails.logger )
if liquid_content
get_template.render options
else
Haml::Engine.new( ERB.new(content).result ).render
end
end
end
# - and "it just works" (except for the Rails rendering godness and routes and
# what not)
# ie: basic Erb works
"#{2+2}" -> 4
"<%= I18n.translate(:hello) %>" -> Hello world
# Rails stuff does not
"<%= render partial: 'shared/errors' %>" -> undefined method `render'
"#{ link_to( 'test', root_path ) }" -> undefined method `root_path'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment