Class: JsonT

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

Constant Summary collapse

VERSION =
'0.1.3'

Instance Method Summary collapse

Constructor Details

#initialize(rules) ⇒ JsonT

Returns a new instance of JsonT.



7
8
9
10
11
12
13
14
# File 'lib/jsont.rb', line 7

def initialize(rules)
  @rules = rules
  @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



21
22
23
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
63
# File 'lib/jsont.rb', line 21

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])
    if rule.respond_to?(:call)
      rule.call(target, :target_path => target_path)
    else
      rule.gsub(/\{([a-z0-9\$\.]+)\}/i) 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
    end
  else
    target
  end
end

#transform(target) ⇒ Object



16
17
18
19
# File 'lib/jsont.rb', line 16

def transform(target)
  @parent = target
  apply!('self',@parent)
end