module RD3::Model
Public Class Methods
attribute(*args)
click to toggle source
NOTE: this method must be declared
before the attribute declarations
# File lib/rd3/model.rb, line 15 def self.attribute(*args) @class_attributes ||= [] attributes_with_defaults = args.reduce({}) do |hash, arg| arg.instance_of?(Hash) ? hash.merge(arg) : hash.merge(arg => nil) end @class_attributes.concat(attributes_with_defaults.keys) attributes_with_defaults.each do |attribute, default| getter = "@#{attribute}" getter.prepend("@#{attribute} = #{default} if @#{attribute}.nil?;") unless default.nil? self.module_eval <<-EVAL def #{attribute}=(value) # set dirty flag @dirty = true unless @dirty || @#{attribute} == value @#{attribute} = value end def #{attribute} #{getter} end EVAL end end
class_attributes()
click to toggle source
# File lib/rd3/model.rb, line 9 def self.class_attributes @class_attributes end
new(*args)
click to toggle source
NOTE: 1) we can create a new instance with a hash
in such a case, default values will be set 2) we can also create a new instance by COPYING properties from one object to another via its attributes in such a case, default values will NOT be set
# File lib/rd3/model.rb, line 49 def initialize(*args) # default to an empty hash if Class.new is called, i.e., args = nil obj = args[0] || {} # an instance SHOULD be marked as dirty if: # 1) it's initialized w/ a non-empty hash # # it SHOULD NOT be marked as dirty if: # 1) Class.new is called (empty hash) # 2) we're mapping from one object to another is_dirty = obj.instance_of?(Hash) && !obj.blank? # grab attributes hash if we're dealing w/ mapping # an object instance obj = obj.attributes unless obj.instance_of? Hash # map properties obj.each do |k,v| self.send("#{k}=", v) if self.class_attributes.include? k end # reset dirty flag @dirty = is_dirty # return self for method chaining self end
Public Instance Methods
attributes()
click to toggle source
# File lib/rd3/model.rb, line 91 def attributes self.instance_values.select { |key| class_attributes.include? key.to_sym }.symbolize_keys end
class_attributes()
click to toggle source
# File lib/rd3/model.rb, line 87 def class_attributes return self.class.class_attributes end
dirty?()
click to toggle source
tracks whether or not the instance has been updated/changed post initialization
# File lib/rd3/model.rb, line 79 def dirty? return @dirty ||= false end
errors=(value)
click to toggle source
add errors to errors collection allows errors to bubble up from a child model to its parent model when working with repositories
# File lib/rd3/model.rb, line 99 def errors=(value) unless value.blank? value.each do |k, v| self.errors[k] = v end end end
persisted?()
click to toggle source
# File lib/rd3/model.rb, line 83 def persisted? id.present? end