Sha256: 05db4adee5d3c1ca4589d5620b64509e888453231b12caf8a54b45b3910ad48a

Contents?: true

Size: 1.17 KB

Versions: 2

Compression:

Stored size: 1.17 KB

Contents

module TMS::CollectionResource
  def self.included(base)
    base.send(:include, InstanceMethods)
  end

  module InstanceMethods
    include TMS::Base
    attr_accessor :collection

    def initialize(client, href, items=nil)
      super(client, href)
      if items
        initialize_collection_from_items(items)
      else
        self.collection = []
      end

    end

    def get
      response = client.get(href)
      initialize_collection_from_items(response.body)
      #setup page links from header
      links = LinkHeader.parse(response.headers['link']).to_a.collect do |a|
        {a[1][0].last => a[0]}
      end
      parse_links(links)
      self
    end

    def build(attributes=nil)
      thing = instance_class(self.class).new(client, self.href, attributes || {})
      self.collection << thing
      thing
    end

    def to_json
      @collection.map(&:to_json)
    end

    def to_s
      "<#{self.class.inspect} href=#{self.href} collection=#{self.collection.inspect}>"
    end

    private

    def initialize_collection_from_items(items)
      self.collection = items.map do |attrs|
        instance_class(self.class).new(client, nil, attrs)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
tms_client-0.0.3 lib/tms_client/collection_resource.rb
tms_client-0.0.2 lib/tms_client/collection_resource.rb