Sha256: ce26dca208aba054a880462463c9525021e75cd05bce85384c071b5d4931c3c7

Contents?: true

Size: 1 KB

Versions: 4

Compression:

Stored size: 1 KB

Contents

module Rainforest
  class ApiObject
    include Enumerable
    attr_reader :json

    def self.construct(json)
      if json.is_a?(Array)
        return json.map{ |a| ApiObject.construct(a) }
      elsif json.is_a?(Hash)
        return ApiObject.new(json)
      else
        return json
      end
    end

    def initialize(json=nil)
      refresh_from(json)
    end

    def refresh_from(json={})
      @json = Util.sorta_deep_clone(json)
      @json.each do |k, v|
        @json[k] = ApiObject.construct(v)
      end
      self
    end

    def inspect
      @json.inspect
    end

    def to_json(*args)
      JSON.generate(@json)
    end

    def method_missing(name, *args, &blk)
      if name.to_s.end_with?('=')
        attr = name.to_s[0...-1].to_sym
        @json[attr] = args[0]
      else
        if @json.respond_to?(name)
          @json.send(name, *args, &blk)
        elsif @json.has_key?(name.to_sym)
          return @json[name.to_sym]
        else
          super
        end
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rainforest-2.1.0 lib/rainforest/apibits/api_object.rb
rainforest-2.0.2 lib/rainforest/apibits/api_object.rb
rainforest-2.0.1 lib/rainforest/apibits/api_object.rb
rainforest-2.0.0 lib/rainforest/apibits/api_object.rb