Class: Traverse::JSON

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

Instance Method Summary collapse

Constructor Details

#initialize(json) ⇒ JSON

Returns a new instance of JSON.



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/traverse.rb', line 194

def initialize json

  setup_underlying_json json

  if @json.is_a? Array
    @proxy = @json.map do |item|
      JSON.new item
    end
  elsif @json.is_a? Hash
    @json.each_pair do |k,v|
      define_singleton_method k do
        if v.is_a? Hash
          JSON.new(v)
        elsif v.is_a? Array
          v.map { |i| JSON.new(i) }
        else
          v
        end
      end
      define_singleton_method "_keys_" do
        @json.keys
      end
    end
  elsif @json.is_a? Array
    @json.map! { |i| JSON.new i }
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object (private)



223
224
225
226
227
228
229
# File 'lib/traverse.rb', line 223

def method_missing m, *args, &block
  if @proxy
    @proxy.send m, *args, &block
  else
    super
  end
end