Module: Justimmo::Parser::Conversions::Node

Included in:
Justimmo::Parser
Defined in:
lib/justimmo/parser.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#apply_mapping(key, mapper = nil) ⇒ Object


91
92
93
94
# File 'lib/justimmo/parser.rb', line 91

def apply_mapping(key, mapper = nil)
  mapped = mapper.nil? ? key : mapper[key]
  mapped.nil? ? key : mapped
end

#format_key(key) ⇒ Object


87
88
89
# File 'lib/justimmo/parser.rb', line 87

def format_key(key)
  key.underscore.to_sym
end

#parse_value(value) ⇒ Object


76
77
78
79
80
81
82
83
84
85
# File 'lib/justimmo/parser.rb', line 76

def parse_value(value)
  case value
  when /^\d*\.\d+$/ then value.to_f
  when /^\d+$/ then value.to_i
  when 'true' then true
  when 'false' then false
  when /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/ then value.to_date
  else value
  end
end

#to_h(hash = {}, mapper = nil) ⇒ Object


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/justimmo/parser.rb', line 47

def to_h(hash = {}, mapper = nil)
  node_hash = {}
  node_name = apply_mapping(format_key(name), mapper)

  attribute_nodes.each { |a| a.to_h(node_hash, mapper) }

  children.each do |c|
    if c.element?
      c.to_h(node_hash, mapper)
    elsif node_hash.empty?
      node_hash = parse_value(c.content)
    else
      node_hash[:value] = parse_value(c.content)
    end
  end

  node_hash = nil if node_hash == {}

  # Insert into parent hash
  case hash[node_name]
  when Array then hash[node_name] << node_hash
  when Hash  then hash[node_name] = [hash[node_name], node_hash]
  when nil   then hash[node_name] = node_hash
  else            hash[node_name] = [hash[node_name], node_hash]
  end

  hash
end