Class: BettyResource::Model::Record

Inherits:
Object
  • Object
show all
Includes:
DirtyAttributes::InstanceMethods, MethodMap
Defined in:
lib/betty_resource/model/record.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, attributes = {}) ⇒ Record

Returns a new instance of Record.



34
35
36
37
38
39
40
41
# File 'lib/betty_resource/model/record.rb', line 34

def initialize(model, attributes = {})
  @model = model
  @id = attributes.delete(:id) || attributes.delete('id')
  @errors = {}
  super()
  self.attributes = Hash[model.attributes.map { |x| [x, nil] }].merge attributes
  self.attributes.instance_variable_set(:@model, model)
end

Instance Attribute Details

#idObject (readonly)

Returns the value of attribute id.



27
28
29
# File 'lib/betty_resource/model/record.rb', line 27

def id
  @id
end

#modelObject (readonly)

Returns the value of attribute model.



27
28
29
# File 'lib/betty_resource/model/record.rb', line 27

def model
  @model
end

Instance Method Details

#_classObject



29
# File 'lib/betty_resource/model/record.rb', line 29

alias :_class :class

#as_json(options = {}) ⇒ Object

TODO: Test this update



85
86
87
# File 'lib/betty_resource/model/record.rb', line 85

def as_json(options = {})
  attributes_as_json(options).merge! 'id' => id
end

#attributes=(other) ⇒ Object

TODO: Test this



48
49
50
51
52
# File 'lib/betty_resource/model/record.rb', line 48

def attributes=(other)
  other.each do |key, value|
    send "#{key}=", value
  end
end

#classObject



30
31
32
# File 'lib/betty_resource/model/record.rb', line 30

def class
  model
end

#errorsObject



54
55
56
# File 'lib/betty_resource/model/record.rb', line 54

def errors
  @errors.dup
end

#inspectObject Also known as: to_s



78
79
80
81
# File 'lib/betty_resource/model/record.rb', line 78

def inspect
  inspection = "id: #{id.inspect}, #{attributes.map { |key, value| "#{key}: #{value.inspect}"}.join(", ")}"
  "#<#{model.name} #{inspection}>"
end

#new_record?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/betty_resource/model/record.rb', line 43

def new_record?
  @id.nil?
end

#saveObject



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/betty_resource/model/record.rb', line 58

def save
  @errors.clear

  result = begin
    if new_record?
      Api.post("/models/#{model.id}/records/new", to_params)
    else
      Api.put("/models/#{model.id}/records/#{id}", to_params)
    end
  end

  result.success?.tap do |success|
    if success
      model.send :load, result.parsed_response, self
    else
      @errors = result.parsed_response ? result.parsed_response['errors'] : { '' => ['Er is iets mis gegaan met het verwerken van het formulier. Probeer u het later nog eens. Onze excuses voor het ongemak'] }
    end
  end
end