Class: UcbRails::Renderer::Base

Inherits:
Object
  • Object
show all
Defined in:
app/helpers/ucb_rails/renderer/base.rb

Overview

Base class for helper objects inspired by railscasts.com/episodes/101-refactoring-out-helper-object

Use of such classes is indicated when you have:

  • helper methods calling each other, especially if …

  • helper methods are passing around variables (which will become instance variables)

  • the same case/if logic in many methods, indicating a requirement for class hierarchy

Your helper class’s methods can just do calculations which are subsituted into html in the views, or the methods can generate html as well. This is helpful when the html is conditional on some other object’s state.

You have access to all the helper methods available to the view that creates the instance.

Implementing helper classes should inherit from Renderer::Base and the template instance should be passed as an argument to the constructor.

# app/helpers/renderer/my_renderer.rb
class MyRenderer < Renderer::Base
...
end

# app/views/a_controller/a_view.html.erb
<% renderer = MyRenderer.new(self) %>   # must pass in template
...
<div>
  <%= renderer.div_content %>
</div>

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template, options = {}) ⇒ Base

Returns new instance of renderer. The template argument is the view template.



39
40
41
42
# File 'app/helpers/ucb_rails/renderer/base.rb', line 39

def initialize(template, options = {})
  self.template = template
  self.options = options
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object (private)

Method missing sends all calls to template instance. This techniuqe provides access to helper methods available to the template.



48
49
50
# File 'app/helpers/ucb_rails/renderer/base.rb', line 48

def method_missing(*args, &block)
  template.send(*args, &block)
end

Instance Attribute Details

#optionsObject

Options to pass to renderer



36
37
38
# File 'app/helpers/ucb_rails/renderer/base.rb', line 36

def options
  @options
end

#templateObject

Holds reference to view template



33
34
35
# File 'app/helpers/ucb_rails/renderer/base.rb', line 33

def template
  @template
end