Class: SimpleShipping::Abstract::Model

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Validations
Defined in:
lib/simple_shipping/abstract/model.rb

Overview

Base class for all simple shipping models.

Direct Known Subclasses

SimpleShipping::Address, Contact, Package, Party, Shipment

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values = {}) ⇒ Model

Create a new model and set the default and passed values.



32
33
34
35
36
37
38
# File 'lib/simple_shipping/abstract/model.rb', line 32

def initialize(values = {})
  values.reverse_merge!(default_values || {})
  values.each do |attribute, value|
    raise("Undefined attribute `#{attribute}` for #{self}") unless respond_to?(attribute)
    send("#{attribute}=", value)
  end
end

Class Method Details

.set_default_values(values = {}) ⇒ Object

Define the default values of the attributes which should be set when the model is created.



10
11
12
# File 'lib/simple_shipping/abstract/model.rb', line 10

def self.set_default_values(values = {})
  self.default_values = values 
end

.validates_submodel(name, opts = {}) ⇒ Object

Add a validation callback to validate the submodel. Submodel is a model which belongs to current model.

Parameters:

  • name - name of attribute which is submodel

  • opts - hash with only on key :as. It should points to class of submodel.



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/simple_shipping/abstract/model.rb', line 19

def self.validates_submodel(name, opts = {})
  validate do
    klass = opts[:as] || raise(":as option should be passed")
    submodel = send(name)
    if !submodel.instance_of?(klass)
      errors.add(name.to_sym, "must be an instance of #{klass.inspect}") 
    elsif submodel.invalid?
      errors.add(name.to_sym, "is invalid")
    end
  end
end