Module: Gambit::Viewable

Overview

This single module is the complete view layer of the Gambit framework.

It’s a simple wrapper around ERb that allows objects to mixin Viewable, register views for all the different ways an object needs to present itself and finally, draw those views as needed.

WARNING: This is not a typical Ruby module. You get a class method, a VIEWS Hash, and an instance method when mixing it in.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(viewable) ⇒ Object

The black magic that adds the class method and constant on include.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/gambit/viewable.rb', line 23

def self.append_features( viewable )
  super
  viewable.instance_eval do
    self.const_set(:VIEWS, Hash.new)
    
    # 
    # The class method added to classes that mixin Viewable.
    # 
    # This method registers a new view for all objects of the type
    # it is called on, by _name_.  These views can later be rendered
    # by object with a call to view().
    # 
    # The _template_ parameter is expected to be an ERb String, or a
    # String of the format "file: FILENAME", in which case the 
    # template will be loaded from the file FILENAME.
    # 
    def self.register_view( name, template )
      self.const_get(:VIEWS)[name] = template
    end
  end
end

Instance Method Details

#view(erb_template_name) ⇒ Object

Returns the text of the processed template erb_template_name. The template is evaluated in the context of the parent object.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/gambit/viewable.rb', line 51

def view( erb_template_name )
  erb_views = self.class.const_get(:VIEWS)
  unless erb_views.include?(erb_template_name)
    raise ArgumentError, "That view is not registered."
  end
  
  erb_view     = erb_views[erb_template_name]
  if erb_view =~ /^file:\s*(.+?)\s*$/
    erb_file = $1
    if test(?e, erb_file)
      erb_template = ERB.new(File.read(erb_file), nil, "%<>")
    else
      raise Gambit::Server::GambitError, "Missing view file."
    end
  else
    erb_template = ERB.new(erb_view, nil, "%<>")
  end
  erb_template.result(binding)
end