Module: PipeLineDealer::Model::Base::Concern::Persistance

Includes:
ActiveSupport::Concern
Included in:
PipeLineDealer::Model::Base
Defined in:
lib/pipe_line_dealer/model/base/concern/persistance.rb

Constant Summary collapse

IGNORE_ATTRIBUTES_WHEN_SAVING =
[:updated_at, :created_at]

Instance Method Summary collapse

Instance Method Details

#destroyObject



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/pipe_line_dealer/model/base/concern/persistance.rb', line 44

def destroy
  status, response = @collection.client.connection.send(:delete, object_url)
  #TODO: Check response

  if status == 200 && response["msg"] == " "
    @destroyed = true #todo: store that this model has been destroyed.
    true
  else
    false
  end
end

#new_record?Boolean

Returns:

  • (Boolean)


8
9
10
# File 'lib/pipe_line_dealer/model/base/concern/persistance.rb', line 8

def new_record?
  not @persisted
end

#persisted?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/pipe_line_dealer/model/base/concern/persistance.rb', line 12

def persisted?
  @persisted
end

#saveObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/pipe_line_dealer/model/base/concern/persistance.rb', line 18

def save
  # Use :post for new records, :put for existing ones
  method = new_record? ? :post : :put

  # Ignore some attributes
  save_attrs = @attributes.reject { |k, v| IGNORE_ATTRIBUTES_WHEN_SAVING.member?(k) }

  # And allow a model class to modify / edit attributes even further
  if respond_to?(:attributes_for_saving)
    save_attrs = attributes_for_saving(save_attrs)
  end

  # Execute the request
  status, response = @collection.client.connection.send(method, object_url, model_attribute_name => save_attrs)

  if status == 200
    import_attributes!(response) # Set the stuff.
    self
  elsif status == 422
    errors = response.collect { |error| { field: error["field"], message: error["msg"] } }
    raise Error::Connection::Unprocessable.new(errors)
  else
    raise "Unexepcted response status #{status.inspect}"
  end
end