Sha256: 814e3133d4a012a3725a823d7a76f066e1a1904f2e5b7995343a7790db1fdfac

Contents?: true

Size: 1.11 KB

Versions: 1

Compression:

Stored size: 1.11 KB

Contents

require 'json'

module Argonaut
  class Generator
    instance_methods.each {|m| undef_method(m) unless %w(__id__ __send__ to_json to_xml instance_eval nil? is_a? class).include?(m.to_s)}
  
    def initialize(array_keys=[], &block)
      @array_keys = array_keys.map(&:to_sym)
      @hash = {}
      block.call(self)
    end
    
    def array_keys!(array_keys)
      @array_keys = array_keys.map(&:to_sym)
    end
  
    def method_missing(key, *values)
      value = if block_given?
        Generator.new(@array_keys) { |a| yield a }
      else
        values.size == 1 ? values.first : values
      end
      
      if @array_keys.include?(key) || @hash[key].is_a?(Array)
        if @hash.include?(key)
          @hash[key] << value
        else
          @hash[key] = [value]
        end
      elsif @hash[key].nil?
        @hash[key] = value
      else
        @hash[key] = [@hash[key], value]
      end
    end
  
    def respond_to?(method)
      true
    end
    
    def to_json(extra=false)
      @hash.to_json(extra)
    end
    
    def to_s
      @hash.to_s
    end
    
    def inspect
      @hash.inspect
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
argonaut-0.0.1 lib/argonaut/generator.rb