Class: Cornerstore::LineItem::Resource

Inherits:
Resource::Base show all
Includes:
Resource::Remote, Resource::Writable
Defined in:
lib/cornerstore/api/line_item.rb

Instance Attribute Summary

Attributes inherited from Resource::Base

#parent

Instance Method Summary collapse

Methods included from Resource::Writable

#create, #destroy_all, #new

Methods included from Resource::Remote

#fetch, #fetch_all, #find_by_id, #to_a, #url

Methods inherited from Resource::Base

#all, #each, #empty?, #find, #find_by_id, #find_by_id_or_param, #find_by_ids, #from_array, #initialize, #method_missing, #push, #size, #to_a

Constructor Details

This class inherits a constructor from Cornerstore::Resource::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Cornerstore::Resource::Base

Instance Method Details

#create_from_variant(variant, attr = {}) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/cornerstore/api/line_item.rb', line 51

def create_from_variant(variant, attr={})
  attributes = {
    variant_id: variant.id,
    product_id: variant.product._id,
    line_item: attr
  }

  RestClient.post("#{Cornerstore.root_url}/carts/#{@parent.id}/line_items/derive.json", attributes, Cornerstore.headers) do |response, request, result, &block|
    if response.code == 201
      attributes = ActiveSupport::JSON.decode(response)
      line_item = @klass.new(attributes, @parent)
    elsif response.code == 422 and data = ActiveSupport::JSON.decode(response) and data.has_key?('errors')
      line_item = @klass.new(attr, @parent)
      data['errors'].each_pair do |key, messages|
        messages.map { |message| line_item.errors.add(key, message) }
      end
    end

    push line_item
    line_item
  end
end