module DomainModel

Constants

InvalidModel
VERSION

Public Class Methods

included(base) click to toggle source
# File lib/domain_model.rb, line 4
def self.included(base)
  base.extend(ClassMethods)
end
new(attributes={}) click to toggle source
# File lib/domain_model.rb, line 8
def initialize(attributes={})
  self.class.fields.select(&:collection?).each do |field|
    send("#{field.name}=", [])
  end

  attributes.each { |k,v | send("#{k}=", v) }
end

Public Instance Methods

==(other) click to toggle source
# File lib/domain_model.rb, line 64
def ==(other)
  other.is_a?(self.class) && attributes == other.attributes
end
attributes() click to toggle source
# File lib/domain_model.rb, line 80
def attributes
  attributes = {}
  self.class.fields.map(&:name).each do |name|
    attributes[name] = send(name)
  end
  attributes
end
empty?() click to toggle source
# File lib/domain_model.rb, line 76
def empty?
  self.class.fields.all? { |f| send(f.name).nil? }
end
errors() click to toggle source
# File lib/domain_model.rb, line 16
def errors
  errors = ModelErrors.new

  self.class.fields.each do |field|
    errors.add(field.name, field.errors(self.send(field.name)))
  end

  self.class.validations.each { |v| v.execute(self, errors) }

  errors
end
flat_errors() click to toggle source
# File lib/domain_model.rb, line 28
def flat_errors
  errors = self.errors

  self.class.fields.each do |field|
    next unless field.validate?

    value = self.send(field.name)

    if !field.collection? && value.is_a?(DomainModel)
      value.flat_errors.each { |k, v| errors.add(:"#{field.name}.#{k}", v) }
    end

    if field.collection? && value.is_a?(Enumerable)
      value.each_with_index do |element, index|
        if element.is_a?(DomainModel)
          element.flat_errors.each { |k, v| errors.add(:"#{field.name}[#{index}].#{k}", v) }
        end
      end
    end
  end

  errors
end
inspect() click to toggle source
# File lib/domain_model.rb, line 72
def inspect
  "#<#{self.class} " + attributes.map { |n, v| "#{n}: #{v.inspect}" }.join(", ") + ">"
end
to_primitive() click to toggle source
# File lib/domain_model.rb, line 88
def to_primitive
  Serializer.serialize(self)
end
to_s() click to toggle source
# File lib/domain_model.rb, line 68
def to_s
  inspect
end
valid!() click to toggle source
# File lib/domain_model.rb, line 56
def valid!
  cached_errors = errors # Just in case #errors is non-deterministic

  if !cached_errors.empty?
    raise InvalidModel.new("This #{self.class} object contains the following errors: #{cached_errors.to_hash}")
  end
end
valid?() click to toggle source
# File lib/domain_model.rb, line 52
def valid?
  errors.empty?
end