Class: TypedEAV::Value

Inherits:
ApplicationRecord show all
Defined in:
app/models/typed_eav/value.rb

Instance Method Summary collapse

Instance Method Details

#valueObject

── Value access ──

The magic here is that we delegate to the correct typed column based on what the field type declares. ActiveRecord handles all casting through the column’s type (schema-inferred).

So ‘value = “42”` on an integer field writes 42 to integer_value, and `value` reads it back as a Ruby Integer. No custom caster needed for storage - the database column type IS the caster.



32
33
34
35
36
# File 'app/models/typed_eav/value.rb', line 32

def value
  return nil unless field

  self[value_column]
end

#value=(val) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/models/typed_eav/value.rb', line 38

def value=(val)
  if field
    # Cast through the field type, then write to the native column.
    # Rails will further cast via the column type on save.
    casted, invalid = field.cast(val)
    self[value_column] = casted
    @cast_was_invalid = invalid
  else
    # Field not yet assigned - stash for later
    @pending_value = val
  end
end

#value_columnObject

Which column this value lives in



52
53
54
# File 'app/models/typed_eav/value.rb', line 52

def value_column
  field.class.value_column
end