Sha256: 02a344618236c4484115b28d23141872d3b6497b577e98e995b75a80bc657bc9

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

$:.unshift(File.dirname(__FILE__)) unless
  $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))

class JsonT
  VERSION = '0.1.3'
  
  def initialize(rules)
    @rules = rules
    @rules.each do |r,v| 
      if r[0,4] != 'self'
        @rules["self.#{r}"] = @rules.delete(r)
      end
    end
  end
  
  def transform(target)
    @parent = target
    apply!('self',@parent)
  end
  
  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
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsont-0.1.3 lib/jsont.rb