Class Cell::Base
In: lib/cell/base.rb
Parent: Object

Basic overview

A Cell is the central notion of the cells plugin. A cell acts as a lightweight controller in the sense that it will assign variables and render a view. Cells can be rendered from other cells as well as from regular controllers and views (see ActionView::Base#render_cell and ControllerMethods#render_cell_to_string)

A render_cell() cycle

A typical render_cell state rendering cycle looks like this:

  render_cell :blog, :newest_article, {...}
  • an instance of the class BlogCell is created, and a hash containing arbitrary parameters is passed
  • the state method newest_article is executed and assigns instance variables to be used in the view
  • if the method returns a string, the cycle ends, rendering the string
  • otherwise, the corresponding state view is searched. Usually the cell will first look for a view template in app/cells/blog/newest_article.html. [erb|haml|…]
  • after the view has been found, it is rendered and returned

It is common to simply return nil in state methods to advice the cell to render the corresponding template.

Design Principles

A cell is a completely autonomous object and it should not know or have to know from what controller it is being rendered. For this reason, the controller‘s instance variables and params hash are not directly available from the cell or its views. This is not a bug, this is a feature! It means cells are truly reusable components which can be plugged in at any point in your application without having to think about what information is available at that point. When rendering a cell, you can explicitly pass variables to the cell in the extra opts argument hash, just like you would pass locals in partials. This hash is then available inside the cell as the @opts instance variable.

Directory hierarchy

To get started creating your own cells, you can simply create a new directory structure under your app directory called cells. Cells are ruby classes which end in the name Cell. So for example, if you have a cell which manages all user information, it would be called UserCell. A cell which manages a shopping cart could be called ShoppingCartCell.

The directory structure of this example would look like this:

  app/
    models/
      ..
    views/
      ..
    helpers/
      application_helper.rb
      product_helper.rb
      ..
    controllers/
      ..
    cells/
      shopping_cart_cell.rb
      shopping_cart/
        status.html.erb
        product_list.html.erb
        empty_prompt.html.erb
      user_cell.rb
      user/
        login.html.erb
    ..

The directory with the same name as the cell contains views for the cell‘s states. A state is an executed method along with a rendered view, resulting in content. This means that states are to cells as actions are to controllers, so each state has its own view. The use of partials is deprecated with cells, it is better to just render a different state on the same cell (which also works recursively).

Anyway, render :partial in a cell view will work, if the partial is contained in the cell‘s view directory.

As can be seen above, Cells also can make use of helpers. All Cells include ApplicationHelper by default, but you can add additional helpers as well with the Cell::Base.helper class method:

  class ShoppingCartCell < Cell::Base
    helper :product
    ...
  end

This will make the ProductHelper from app/helpers/product_helper.rb available from all state views from our ShoppingCartCell.

Cell inheritance

Unlike controllers, Cells can form a class hierarchy. When a cell class is inherited by another cell class, its states are inherited as regular methods are, but also its views are inherited. Whenever a view is looked up, the view finder first looks for a file in the directory belonging to the current cell class, but if this is not found in the application or any engine, the superclass’ directory is checked. This continues all the way up until it stops at Cell::Base.

For instance, when you have two cells:

  class MenuCell < Cell::Base
    def show
    end

    def edit
    end
  end

  class MainMenuCell < MenuCell
    .. # no need to redefine show/edit if they do the same!
  end

and the following directory structure in app/cells:

  app/cells/
    menu/
      show.html.erb
      edit.html.erb
    main_menu/
      show.html.erb

then when you call

  render_cell :main_menu, :show

the main menu specific show.html.erb (app/cells/main_menu/show.html.erb) is rendered, but when you call

  render_cell :main_menu, :edit

cells notices that the main menu does not have a specific view for the edit state, so it will render the view for the parent class, app/cells/menu/edit.html.erb

Gettext support

Cells support gettext, just name your views accordingly. It works exactly equivalent to controller views.

  cells/user/user_form.html.erb
  cells/user/user_form_de.html.erb

If gettext is set to DE_de, the latter view will be chosen.

Methods

Included Modules

Caching ActionController::Helpers ActionController::RequestForgeryProtection

Attributes

cell_name  [R] 
controller  [RW] 
state_name  [RW] 

Public Class methods

Get the name of this cell‘s class as an underscored string, with _cell removed.

Example:

 UserCell.cell_name
 => "user"

[Source]

     # File lib/cell/base.rb, line 304
304:     def self.cell_name
305:       self.name.underscore.sub(/#{name_suffix}/, '')
306:     end

Given a cell name, find the class that belongs to it.

Example: Cell::Base.class_from_cell_name(:user)

> UserCell

[Source]

     # File lib/cell/base.rb, line 319
319:     def self.class_from_cell_name(cell_name)
320:       "#{cell_name}#{name_suffix}".classify.constantize
321:     end

Creates a cell instance of the class nameCell, passing through opts.

[Source]

     # File lib/cell/base.rb, line 360
360:     def self.create_cell_for(controller, name, opts={})
361:       class_from_cell_name(name).new(controller, opts)
362:     end

Find a possible template for a cell‘s current state. It tries to find a template file with the name of the state under a subdirectory with the name of the cell under the app/cells directory. If this file cannot be found, it will try to call this method on the superclass. This way you only have to write a state template once when a more specific cell does not need to change anything in that view.

[Source]

     # File lib/cell/base.rb, line 265
265:     def self.find_class_view_for_state(state)
266:       return [view_for_state(state)] if superclass == Cell::Base
267:       
268:        superclass.find_class_view_for_state(state) << self.view_for_state(state)
269:     end

Declare a controller method as a helper. For example,

  helper_method :link_to
  def link_to(name, options) ... end

makes the link_to controller method available in the view.

[Source]

     # File lib/cell/base.rb, line 347
347:     def self.helper_method(*methods)
348:       methods.flatten.each do |method|
349:         master_helper_module.module_eval "def \#{method}(*args, &block)\n@cell.send(%(\#{method}), *args, &block)\nend\n"
350:       end
351:     end

The name suffix of a cell. Always ‘_cell’.

[Source]

     # File lib/cell/base.rb, line 309
309:     def self.name_suffix
310:       # XXX Why is this needed?  Seems like superfluous "abstraction"
311:       '_cell'
312:     end

[Source]

     # File lib/cell/base.rb, line 154
154:     def initialize(controller, options={})
155:       @controller = controller
156:       @cell_name  = self.class.cell_name
157:       @opts       = options
158:       self.allow_forgery_protection = true
159:     end

Return the default view for the given state on this cell subclass. This is a file with the name of the state under a directory with the name of the cell followed by a template extension.

[Source]

     # File lib/cell/base.rb, line 284
284:     def self.view_for_state(state)
285:       "#{cell_name}/#{state}"
286:     end

[Source]

     # File lib/cell/base.rb, line 188
188:     def self.view_paths=(value)
189:       # this just creates a ActionView::PathSet.
190:       @@view_paths = ::ActionView::Base.process_view_paths(value)
191:     end

Public Instance methods

Prepares the hash {instance_var => value, …} that should be available in the ActionView when rendering the state view.

[Source]

     # File lib/cell/base.rb, line 290
290:     def assigns_for_view
291:       assigns = {}
292:       (self.instance_variables - ivars_to_ignore).each do |k|
293:        assigns[k[1..-1]] = instance_variable_get(k)
294:       end
295:       assigns
296:     end

Call the state method.

[Source]

     # File lib/cell/base.rb, line 177
177:     def dispatch_state(state)
178:       send(state)
179:     end

Climbs up the inheritance hierarchy of the Cell, looking for a view for the current state in each level. As soon as a view file is found it is returned as an ActionView::Template instance.

[Source]

     # File lib/cell/base.rb, line 223
223:     def find_family_view_for_state(state, action_view)
224:       missing_template_exception = nil
225:       
226:       possible_paths_for_state(state).each do |template_path|
227:         # we need to catch MissingTemplate, since we want to try for all possible
228:         # family views.
229:         begin
230:           if view = action_view.try_picking_template_for_path(template_path)
231:             return view
232:           end
233:         rescue ::ActionView::MissingTemplate => missing_template_exception
234:         end
235:       end
236:       
237:       raise missing_template_exception
238:     end

When passed a copy of the ActionView::Base class, it will mix in all helper classes for this cell in that class.

[Source]

     # File lib/cell/base.rb, line 326
326:     def include_helpers_in_class(view_klass)
327:       view_klass.send(:include, self.class.master_helper_module)
328:     end

Defines the instance variables that should not be copied to the View instance.

[Source]

     # File lib/cell/base.rb, line 333
333:     def ivars_to_ignore
334:       ['@controller', '@_already_rendered']
335:     end

Find possible files that belong to the state. This first tries the cell‘s view_for_state method and if that returns a true value, it will accept that value as a string and interpret it as a pathname for the view file. If it returns a falsy value, it will call the Cell‘s class method find_class_view_for_state to determine the file to check.

You can override the Cell::Base#view_for_state method for a particular cell if you wish to make it decide dynamically what file to render.

[Source]

     # File lib/cell/base.rb, line 249
249:     def possible_paths_for_state(state)
250:       if view_file = view_for_state(state) # instance.
251:         return [view_file]
252:       end
253:       
254:       self.class.find_class_view_for_state(state).reverse!
255:     end

Render the given state. You can pass the name as either a symbol or a string.

[Source]

     # File lib/cell/base.rb, line 164
164:     def render_state(state)
165:       @cell = self
166:       #state = state.to_s ### DISCUSS: why convert?
167:       self.state_name = state
168: 
169:       content = dispatch_state(state)
170: 
171:       return content if content.kind_of? String
172: 
173:       return self.render_view_for_state(state)
174:     end

Render the view belonging to the given state. Will raise ActionView::MissingTemplate if it can not find one of the requested view template. Note that this behaviour was introduced in cells 2.3 and replaces the former warning message.

[Source]

     # File lib/cell/base.rb, line 198
198:     def render_view_for_state(state)
199:       ### DISCUSS: create Cell::View directly? maybe we can fix a gettext problem this way?
200:       view_class  = Class.new(Cell::View)
201:       action_view = view_class.new(@@view_paths, {}, @controller)
202:       action_view.cell = self
203:       ### FIXME/DISCUSS: 
204:       action_view.template_format = :html # otherwise it's set to :js in AJAX context!
205:       
206:       # Make helpers and instance vars available
207:       include_helpers_in_class(view_class)
208:       
209:       action_view.assigns = assigns_for_view
210:       
211:       
212:       template = find_family_view_for_state(state, action_view)
213:       ### TODO: cache family_view for this cell_name/state in production mode,
214:       ###   so we can save the call to possible_paths_for_state.
215:       
216:       action_view.render(:file => template)      
217:     end

Empty method. Returns nil. You can override this method in individual cell classes if you want them to determine the view file dynamically.

If a view filename is returned here, we assume it really exists and don‘t invoke the superclass view finding chain.

[Source]

     # File lib/cell/base.rb, line 277
277:     def view_for_state(state)
278:       nil
279:     end

[Validate]