Sha256: 6f0506bce5158cdec6301744531a905dfd3e7142d42b38f986b1bc57c6be3caf

Contents?: true

Size: 1.75 KB

Versions: 4

Compression:

Stored size: 1.75 KB

Contents

module Rainforest
  class ApiList < ApiResource
    include Enumerable

    attr_reader :api_method
    attr_reader :client
    attr_reader :data
    attr_reader :klass

    def initialize(klass, json={}, api_method=nil, client=nil)
      if klass.is_a?(Class)
        @klass = klass
      else
        @klass = Util.constantize(klass)
      end

      refresh_from(json, api_method, client)
    end

    def refresh_from(json, api_method=nil, client=nil)
      unless json.is_a?(Hash)
        json = {
          :data => json
        }
      end
      json = Util.symbolize_keys(json)

      clear_api_attributes
      @api_method = api_method
      @client = client
      @data = []
      @json = Util.sorta_deep_clone(json)

      json.each do |k, v|
        if k.to_sym == :data
          if v.respond_to?(:map)
            instance_variable_set("@#{k}", v.map{ |i| @klass.new(i, @api_method, @client) })
          else
            instance_variable_set("@#{k}", v || [])
          end
        elsif self.class.api_attribute_names.include?(k)
          instance_variable_set("@#{k}", determine_api_attribute_value(k, v))
        end
      end
      self
    end

    def [](k)
      data[k]
    end

    def []=(k, v)
      data[k]=v
    end

    def last
      data.last
    end

    def length
      data.length
    end

    def each(&blk)
      data.each(&blk)
    end

    def inspect
      "#<#{self.class}[#{@klass}]:0x#{self.object_id.to_s(16)}> Data: " + JSON.pretty_generate(inspect_data)
    end

    def inspect_data
      ret = []
      data.each do |d|
        if d.respond_to?(:inspect_nested)
          ret << d.inspect_nested
        else
          ret << d
        end
      end
      ret
    end

    @api_attributes = {
      :data => { :readonly => true }
    }
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

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