class DCA::Models::BaseModel

Attributes

base_id[RW]
created_at[RW]
id[RW]
updated_at[RW]

Public Class Methods

new(params={}) click to toggle source
# File lib/dca/models/base_model.rb, line 18
              def initialize(params={})
  params.each { |attr, value| self.instance_variable_set "@#{attr}", value } if params
end

Public Instance Methods

attributes() click to toggle source
# File lib/dca/models/base_model.rb, line 32
def attributes
  return @attributes unless @attributes.nil?

  @attributes = Hash[instance_variables.map { |var| [var.to_s.delete('@'), instance_variable_get(var)]}]
  @attributes.delete 'errors'
  @attributes.delete 'validation_context'

  @attributes
end
before_create() click to toggle source
# File lib/dca/models/base_model.rb, line 46
def before_create
  self.created_at = Time.now.utc
end
before_update() click to toggle source
# File lib/dca/models/base_model.rb, line 42
def before_update
  self.updated_at = Time.now.utc
end
persisted?() click to toggle source
# File lib/dca/models/base_model.rb, line 22
def persisted?
  true
end
to_hash() click to toggle source
# File lib/dca/models/base_model.rb, line 26
  def to_hash
    include = []
    self.class.associations(true).each { |field, options| include << field.to_s}
    self.serializable_hash include: include
  end

  def attributes
    return @attributes unless @attributes.nil?

    @attributes = Hash[instance_variables.map { |var| [var.to_s.delete('@'), instance_variable_get(var)]}]
    @attributes.delete 'errors'
    @attributes.delete 'validation_context'

    @attributes
  end

  def before_update
    self.updated_at = Time.now.utc
  end

  def before_create
    self.created_at = Time.now.utc
  end

  def validate_associations
    self.class.associations.each do |field, options|
      object = self.send(field)
      next if object.nil?

      if object.is_a? Array
        object.each { |item| validate_child item, field }
      else
        validate_child object, field
      end
    end
  end

  private

  def validate_child object, field
    if object.respond_to?(:invalid?) && object.invalid?
      self.errors.add field, object.errors.full_messages
    end
  end

end
validate_associations() click to toggle source
# File lib/dca/models/base_model.rb, line 50
def validate_associations
  self.class.associations.each do |field, options|
    object = self.send(field)
    next if object.nil?

    if object.is_a? Array
      object.each { |item| validate_child item, field }
    else
      validate_child object, field
    end
  end
end
validate_child(object, field) click to toggle source
# File lib/dca/models/base_model.rb, line 65
def validate_child object, field
  if object.respond_to?(:invalid?) && object.invalid?
    self.errors.add field, object.errors.full_messages
  end
end