Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module TemplateRenderer
- # This class is used to give ERB templates access to objects of our choosing.
- #
- # TemplateContext.bind(:object => value) # => <Binding>
- #
- # The binding returned here can then be passed into an ERB instance's #result method
- # giving it access to the values passed into the #bind method of TemplateContext.
- #
- # It uses method missing to expose the content of the hash, so it's not the most speedy
- # solutions, but it is reasonably OK.
- class TemplateContext
- def self.bind(locals)
- new(locals).send(:binding)
- end
- def initialize(locals)
- @locals = locals
- end
- def method_missing(method_name)
- @locals[method_name] || super
- end
- def partial(template_name)
- template = IO.read(File.join(PROPER_ROOT, "/app/views/#{template_name}.rhtml"))
- ERB.new(template).result(binding)
- end
- end
- # Renders the template at the given path. This path is calculated relative to the
- # rails default view directory.
- def render(template_name, locals = {})
- template = IO.read(File.join(PROPER_ROOT, "app/views/#{template_name}.rhtml"))
- ERB.new(template).result(TemplateContext.bind(locals))
- end
- end
Add Comment
Please, Sign In to add comment