Module Hirb::DynamicView
In: lib/hirb/dynamic_view.rb

This module extends a Helper with the ability to have dynamic views for configured output classes. After a Helper has extended this module, it can use it within a render() by calling dynamic_options() to get dynamically generated options for the object it‘s rendering. See Hirb::Helpers::AutoTable as an example.

Dynamic Views

Whereas normal views are generated from helpers with static helper options, dynamic views are generated from helpers and dynamically generated helper options. Let‘s look at an example for Rails’ ActiveRecord classes:

  Hirb.add_dynamic_view("ActiveRecord::Base", :helper=>:auto_table) {|obj|
   {:fields=>obj.class.column_names} }

From this dynamic view definition, any ActiveRecord model class will render a table with the correct fields, since the fields are extracted from the output object‘s class at runtime. Note that dynamic view definitions should return a hash of helper options.

To define multiple dynamic views, create a Views module where each method ending in ‘_view’ maps to a class/module:

  module Hirb::Views::ORM
    def data_mapper__resource_view(obj)
      {:fields=>obj.class.properties.map {|e| e.name }}
    end

    def sequel__model_view(obj)
      {:fields=>obj.class.columns}
    end
  end

  Hirb.add_dynamic_view Hirb::Views::ORM, :helper=>:auto_table

In this example, ‘data_mapper__resource_view’ maps to DataMapper::Resource and ‘sequel__model_view’ maps to Sequel::Model. Note that when mapping method names to class names, ‘__’ maps to ’::’ and ‘_’ signals the next letter to be capitalized.

Methods

Public Class methods

Add dynamic views to output class(es) for a given helper. If defining one view, the first argument is the output class and a block defines the dynamic view. If defining multiple views, the first argument should be a Views::* module where each method in the module ending in _view defines a view for an output class. To map output classes to method names in a Views module, translate’::’ to ‘__’ and a capital letter translates to a ‘_’ and a lowercase letter.

Options:

*:helper*
Required option. Helper class that view(s) use to format. Hirb::Helpers::AutoTable is the only valid helper among default helpers. Can be given in aliased form i.e. :auto_table -> Hirb::Helpers::AutoTable.

Examples:

   Hirb.add_dynamic_view Hirb::Views::ORM, :helper=>:auto_table
   Hirb.add_dynamic_view("ActiveRecord::Base", :helper=>:auto_table) {|obj| {:fields=>obj.class.column_names} }

Public Instance methods

Returns a hash of options based on dynamic views defined for the object‘s ancestry. If no config is found returns nil.

Stores view methods that a Helper has been given via DynamicView.add

[Validate]