Class: Supplejack::ItemRelation

Inherits:
Object
  • Object
show all
Includes:
Request
Defined in:
lib/supplejack/item_relation.rb

Overview

The ItemRelation class provides ActiveRecord like functionality to the relationship between a UserSet object and it’s Item objects.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Request

#delete, #get, #post, #put

Constructor Details

#initialize(user_set) ⇒ ItemRelation

Returns a new instance of ItemRelation.



24
25
26
27
28
# File 'lib/supplejack/item_relation.rb', line 24

def initialize(user_set)
  @user_set = user_set
  items_array = user_set.attributes[:records] || []
  @items = items_array.map { |hash| Supplejack::Item.new(hash.merge(user_set_id: user_set.id, api_key: user_set.api_key)) }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Any method missing on this class is delegated to the Item objects array so that the developer can easily execute any Array method on the ItemRelation

Examples:

user_set.items.each ....     => Iterate through the Item objects array
user_set.items.size          => Get the size of the Item objects array


69
70
71
# File 'lib/supplejack/item_relation.rb', line 69

def method_missing(method, *args, &block)
  @items.send(method, *args, &block)
end

Instance Attribute Details

#itemsObject (readonly)

Returns the value of attribute items.



22
23
24
# File 'lib/supplejack/item_relation.rb', line 22

def items
  @items
end

#user_setObject (readonly)

Returns the value of attribute user_set.



22
23
24
# File 'lib/supplejack/item_relation.rb', line 22

def user_set
  @user_set
end

Instance Method Details

#allObject

Returns an Array with all items for the current UserSet



32
33
34
# File 'lib/supplejack/item_relation.rb', line 32

def all
  @items
end

#build(attributes = {}) ⇒ Supplejack::Item

Initializes a new Item with the provided attributes

Returns:



46
47
48
49
50
51
# File 'lib/supplejack/item_relation.rb', line 46

def build(attributes={})
  attributes ||= {}
  attributes[:user_set_id] = self.user_set.id
  attributes[:api_key] = self.user_set.api_key
  Supplejack::Item.new(attributes)
end

#create(attributes = {}) ⇒ true, false

Initializes and persists the Item to the API

Returns:

  • (true, false)

    True if the API response was successful, false if not.



57
58
59
60
# File 'lib/supplejack/item_relation.rb', line 57

def create(attributes={})
  item = self.build(attributes)
  item.save
end

#find(record_id) ⇒ Object

Finds the item based on the record_id and returns it.



38
39
40
# File 'lib/supplejack/item_relation.rb', line 38

def find(record_id)
  @items.detect {|i| i.record_id == record_id.to_i}
end