Class: Builder::Hash

Inherits:
Abstract show all
Defined in:
lib/builder/hash.rb

Direct Known Subclasses

Json

Instance Method Summary collapse

Methods inherited from Abstract

#comment!, #declare!, #instruct!, #nil?

Constructor Details

#initialize(options = {}) ⇒ Hash

Returns a new instance of Hash.



4
5
6
7
8
9
10
11
# File 'lib/builder/hash.rb', line 4

def initialize(options = {})
  # @default_content_key is used in such case: markup.key(value, :attr_key => attr_value)
  # in this case, we need some key for value.
  @default_content_key  = (options[:default_content_key] || :content).to_sym
  @include_root = options[:include_root]
  @target = {}
  @array_mode = false
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args, &block) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/builder/hash.rb', line 61

def method_missing(key, *args, &block)
  key = args.first.is_a?(Symbol) ? "#{key}:#{args.shift}".to_sym : key.to_sym
  args[0] = {@default_content_key => args[0]} if args.size > 1 && !args[0].is_a?(::Hash)
  unless @root
    _root(key, args, &block)
  else
    _child(key, args, &block)
  end
  target!
end

Instance Method Details

#<<(_target) ⇒ Object



38
39
40
41
42
43
44
45
# File 'lib/builder/hash.rb', line 38

def <<(_target)
  if @array_mode
    eval("#{_current} << _target")
  else
    eval("#{_current} ||= {}")
    eval("#{_current}.merge!(_target)")
  end
end

#array_mode(key = nil, &block) ⇒ Object

NOTICE: you have to call this method to use array in json

Raises:

  • (RuntimeError)


14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/builder/hash.rb', line 14

def array_mode(key = nil, &block)
  raise RuntimeError.new("cannot call inside array_mode block") if @array_mode
  @array_mode = true
  if eval("#{_current}").is_a?(::Hash)
    key ||= :entry
    eval("#{_current}.merge!(key => [])")
    @path.push(key.to_sym)
    yield(self)
    @path.pop
  else
    eval("#{_current} = []")
    yield(self)
  end
  @array_mode = false
end

#tag!(key, *attrs, &block) ⇒ Object



57
58
59
# File 'lib/builder/hash.rb', line 57

def tag!(key, *attrs, &block)
  method_missing(key, *args, &block)
end

#target!Object



30
31
32
33
34
35
36
# File 'lib/builder/hash.rb', line 30

def target!
  if @include_root
    @target
  else
    @target[@root]
  end
end

#text!(text) ⇒ Object Also known as: cdata!

Raises:

  • (RuntimeError)


47
48
49
50
51
52
53
54
# File 'lib/builder/hash.rb', line 47

def text!(text)
  raise RuntimeError.new("cannot call inside array_mode block") if @array_mode
  if eval("#{_current}").is_a?(::Hash)
    eval("#{_current}.merge!({@default_content_key => text})")
  else
    eval("#{_current} = text")
  end
end