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



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

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

  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 Also known as: add_media_type



8
9
10
11
12
13
14
15
# 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.each do |media_type|
    @media_types << media_type
    @@global_media_types[media_type] = self
  end
end

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



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

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

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



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/tokamak/builder/base.rb', line 54

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



23
24
25
# File 'lib/tokamak/builder/base.rb', line 23

def global_media_types
  @@global_media_types
end

.helperObject



42
43
44
# File 'lib/tokamak/builder/base.rb', line 42

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

.media_typesObject



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

def media_types
  @media_types
end

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



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

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