Guest User

Untitled

a guest
Apr 25th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.21 KB | None | 0 0
  1. module TemplateRenderer
  2. # This class is used to give ERB templates access to objects of our choosing.
  3. #
  4. # TemplateContext.bind(:object => value) # => <Binding>
  5. #
  6. # The binding returned here can then be passed into an ERB instance's #result method
  7. # giving it access to the values passed into the #bind method of TemplateContext.
  8. #
  9. # It uses method missing to expose the content of the hash, so it's not the most speedy
  10. # solutions, but it is reasonably OK.
  11. class TemplateContext
  12. def self.bind(locals)
  13. new(locals).send(:binding)
  14. end
  15.  
  16. def initialize(locals)
  17. @locals = locals
  18. end
  19.  
  20. def method_missing(method_name)
  21. @locals[method_name] || super
  22. end
  23.  
  24. def partial(template_name)
  25. template = IO.read(File.join(PROPER_ROOT, "/app/views/#{template_name}.rhtml"))
  26. ERB.new(template).result(binding)
  27. end
  28. end
  29.  
  30. # Renders the template at the given path. This path is calculated relative to the
  31. # rails default view directory.
  32. def render(template_name, locals = {})
  33. template = IO.read(File.join(PROPER_ROOT, "app/views/#{template_name}.rhtml"))
  34. ERB.new(template).result(TemplateContext.bind(locals))
  35. end
  36. end
Add Comment
Please, Sign In to add comment