Thursday, February 23, 2017

Rendering ERB Like Rails Without Rails

While Rails 5 has the ability to render templates outside of controllers, and you can typically just use partials to share ERB between various parts of your Rails app (e.g. between a mailer's and controller's views), you can get pretty close on your own with just ERB:
require 'erb'

module YourModule
  class ErbRenderer
    def self.render(some_value)
      tempate_context = binding
      tempate_context.local_variable_set(:some_variable, some_value)
      @@template_cache ||= {}
      @@template_cache[template_pathname] ||= ::ERB.new(File.open(template_pathname, 'rt').read)
      @@template_cache[template_pathname].result(tempate_context)
    end
  end
end

Looks a bit nasty, but works and can be extended as needed. If you don't pass the binding in, it will create a new binding each time, and if you don't specify '-', it won't interpret the -%> tags as you'd expect in Rails ERB templates.

No comments: