Module: ValueObjects::ActiveRecord

Defined in:
lib/value_objects/active_record.rb

Defined Under Namespace

Classes: JsonCoder

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
# File 'lib/value_objects/active_record.rb', line 6

def self.included(base)
  base.extend self
end

Instance Method Details

#value_object(attribute, value_class, options = {}) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/value_objects/active_record.rb', line 10

def value_object(attribute, value_class, options = {})
  type =
    begin
      column_for_attribute(attribute)&.type
    rescue ::ActiveRecord::StatementInvalid
      # This can happen if `column_for_attribute` is called but the database table does not exist
      # as will be the case when migrations are run and the model class is loaded by initializers
      # before the table is created.
      # This is a workaround to prevent such migrations from failing.
      nil
    end
  coder =
    case type
    when :string, :text
      JsonCoder.new(value_class)
    else
      value_class
    end
  serialize(attribute, coder)
  validates_with(::ValueObjects::ValidValidator, options.merge(attributes: [attribute])) unless options[:no_validation]
  setter = :"#{attribute}="
  define_method("#{attribute}_attributes=") do |attributes|
    send(setter, value_class.new(attributes))
  end
end