Module: Cornerstore::Model::Writable

Included in:
Cart, LineItem, Property
Defined in:
lib/cornerstore/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.create(attributes = {}, &block) ⇒ Object



112
113
114
# File 'lib/cornerstore/model.rb', line 112

def self.create(attributes = {}, &block)
  self.new(attributes, &block).tap{|obj| obj.save}
end

Instance Method Details

#destroyObject



108
109
110
# File 'lib/cornerstore/model.rb', line 108

def destroy
  RestClient.delete(url, Cornerstore.headers).success?
end

#new?Boolean Also known as: new_record?

Returns:

  • (Boolean)


73
74
75
# File 'lib/cornerstore/model.rb', line 73

def new?
  id.nil?
end

#saveObject



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/cornerstore/model.rb', line 83

def save
  return false unless valid?
  wrapped_attributes = {self.class.name.split('::').last.underscore => self.attributes}
  if new?
    response = RestClient.post(url, wrapped_attributes, Cornerstore.headers){|response| response}
    self.attributes = ActiveSupport::JSON.decode(response)
  else
    response = RestClient.patch(url, wrapped_attributes, Cornerstore.headers){|response| response}
  end

  if response.success?
    return true
  else
    if data = ActiveSupport::JSON.decode(response) and data.has_key?('errors')
      data['errors'].each_pair do |key, messages|
        messages.map { |message| self.errors.add(key, message) }
      end

      return false
    else
      return false
    end
  end
end

#to_keyObject



79
80
81
# File 'lib/cornerstore/model.rb', line 79

def to_key
  new? ? [id] : nil
end