require 'blankslate' unless defined? BlankSlate require 'json' module Argonaut class Generator < BlankSlate # 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 key(key, value) method_missing(key.to_sym, value) 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 # Sometimes Rails adds a parameter def to_json(filler=nil) JSON.generate(@hash) end def to_s @hash.to_s end def inspect @hash.inspect end end end