Class: Hashblock::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/hashblock/parser.rb

Constant Summary collapse

DEFAULTS =
{
 :allow_nil => false,
 :merge_strategy => :exception
}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Parser

Returns a new instance of Parser.



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/hashblock/parser.rb', line 13

def initialize(*args)
  @options = {}
  
  if args.last.is_a? Hash
    args.pop.each do |key, value|
      @options[key.to_sym] = value
    end
  end
  
  sanitize_options!
end

Class Method Details

.hashify_block(block, merge_strategy = ) ⇒ Object



48
49
50
# File 'lib/hashblock/parser.rb', line 48

def self.hashify_block(block, merge_strategy = DEFAULTS[:merge_strategy])
  Hashblock::BlockEvaluator.new(block, merge_strategy).to_hash
end

Instance Method Details

#allow_nil?Boolean

Returns:

  • (Boolean)


9
10
11
# File 'lib/hashblock/parser.rb', line 9

def allow_nil?
  self.allow_nil
end

#parse(hash_or_block, merge_strategy = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/hashblock/parser.rb', line 25

def parse(hash_or_block, merge_strategy = nil)
  merge_strategy ||= self.merge_strategy
  
  if hash_or_block.nil? and allow_nil?
    return nil
  end
  
  hash = case hash_or_block
  when Proc then self.class.hashify_block(hash_or_block, merge_strategy)
  when Hash then hash_or_block
  else
    class_list = [Proc, Hash]
    if allow_nil?
      class_list.unshift(NilClass)
    end
    
    raise ArgumentError, "Cannot parse a `#{hash_or_block.class}'; not one "\
     "of #{class_list.map(&:to_s).join(', ')}"
  end
  
  hash
end