Class: Tokamak::Builder::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/tokamak/builder/base.rb

Direct Known Subclasses

Json, Xml

Constant Summary collapse

@@global_media_types =
{}

Class Method Summary collapse

Class Method Details

.build(obj, options = {}, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/tokamak/builder/base.rb', line 24

def build(obj, options = {}, &block)
  if block_given?
    recipe = block
  else
    recipe = options.delete(:recipe)
  end

  unless recipe.respond_to?(:call)
    recipe = Tokamak::Recipes[recipe]
    raise Tokamak::BuilderError.new("Recipe required to build representation.") unless recipe.respond_to?(:call)
  end

  builder = self.new(obj, options)

  recipe.call(*[builder, obj, options][0, recipe.arity])

  builder.representation
end

.builder_for(*args) ⇒ Object



8
9
10
11
12
13
14
# File 'lib/tokamak/builder/base.rb', line 8

def builder_for(*args)
  # class instance variable to store media types handled by a builder
  @media_types = args
  args.each do |media_type|
    @@global_media_types[media_type] = self
  end
end

.collection_helper_default_options(options = {}, &block) ⇒ Object



50
51
52
# File 'lib/tokamak/builder/base.rb', line 50

def collection_helper_default_options(options = {}, &block)
  generic_helper(:collection, options, &block)
end

.generic_helper(section, options = {}, &block) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/tokamak/builder/base.rb', line 58

def generic_helper(section, options = {}, &block)
  helper.send(:remove_method, section)
  var_name = "@@more_options_#{section.to_s}".to_sym
  helper.send(:class_variable_set, var_name, options)
  helper.module_eval <<-EOS
    def #{section.to_s}(obj, *args, &block)
      #{var_name}.merge!(args.shift)
      args.unshift(#{var_name})
      #{self.name}.build(obj, *args, &block)
    end
  EOS
end

.global_media_typesObject



20
21
22
# File 'lib/tokamak/builder/base.rb', line 20

def global_media_types
  @@global_media_types
end

.helperObject



43
44
45
46
47
48
# File 'lib/tokamak/builder/base.rb', line 43

def helper
  unless instance_variable_get(:@helper_module)
    @helper_module = Tokamak::Builder.helper_module_for(self)
  end
  @helper_module
end

.media_typesObject



16
17
18
# File 'lib/tokamak/builder/base.rb', line 16

def media_types
  @media_types
end

.member_helper_default_options(type, options = {}, &block) ⇒ Object



54
55
56
# File 'lib/tokamak/builder/base.rb', line 54

def member_helper_default_options(type, options = {}, &block)
  generic_helper(:member, options, &block)
end