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] ||=, 'rt').read)

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: