Class: Jsont

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

Constant Summary collapse

VERSION =
'0.1.0'

Instance Method Summary collapse

Constructor Details

#initialize(rules) ⇒ Jsont

Returns a new instance of Jsont.



10
11
12
13
14
15
16
17
# File 'lib/jsont.rb', line 10

def initialize(rules)
  @rules = rules.is_a?(String) ? JSON.parse(rules) : rules.dup
  @rules.each do |r,v| 
    if r[0,4] != 'self'
      @rules["self.#{r}"] = @rules.delete(r)
    end
  end
end

Instance Method Details

#apply!(target_path, target) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/jsont.rb', line 24

def apply!(target_path, target)
  case target
  when Array
    target.each_index do |i|
      target[i] = apply!("#{target_path}[*]", apply!("#{target_path}[#{i}]", target[i]))
    end
  when Hash
    target.each do |k, v|
      target[k] = apply!("#{target_path}.?", apply!("#{target_path}.#{k}", target[k]))
    end
  end
  
  if (rule = @rules[target_path])
    rule.gsub(/\{([a-z0-9\$\.]+)\}/) do |match|
      path = match[1,match.size - 2]
      n = case path[0]
      when ?$
        target
      else
        @parent
      end
      path.gsub!(/^\$\.?/,'')

      if path.size > 0
        path.split('.').each do |piece|
          n = case piece
          when /^[0-9]+$/
            n[Integer(piece)]
          else
            n[piece]
          end
        end
      end
      n
    end
  else
    target
  end
end

#transform(target) ⇒ Object



19
20
21
22
# File 'lib/jsont.rb', line 19

def transform(target)
  @parent = target.is_a?(String) ? JSON.parse(target) : target
  apply!('self',@parent)
end