Module: MinceModel

Extended by:
ActiveSupport::Concern
Defined in:
lib/mince_model.rb,
lib/mince_model/version.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#attributes=(hash = {}) ⇒ Object



98
99
100
101
102
# File 'lib/mince_model.rb', line 98

def attributes=(hash={})
  assignable_fields.each do |field|
    send("#{field}=", hash[field]) if hash[field]
  end
end

#ensure_no_extra_fieldsObject



91
92
93
94
95
96
# File 'lib/mince_model.rb', line 91

def ensure_no_extra_fields
  extra_fields = (fields - data_model.data_fields)
  if extra_fields.any?
    raise "Tried to save a #{self.class.name} with fields not specified in #{data_model.name}: #{extra_fields.join(', ')}"
  end
end

#initialize(hash = {}) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/mince_model.rb', line 70

def initialize(hash={})
  @id = hash[:id]
  readonly_fields.each do |field_name|
    self.instance_variable_set("@#{field_name}", hash[field_name]) if hash[field_name]
  end
  self.attributes = hash
end

#persisted?Boolean

Returns:

  • (Boolean)


78
79
80
# File 'lib/mince_model.rb', line 78

def persisted?
  !!id
end

#saveObject



82
83
84
85
86
87
88
89
# File 'lib/mince_model.rb', line 82

def save
  ensure_no_extra_fields
  if persisted?
    data_model.update(self)
  else
    @id = data_model.store(self)
  end
end