class ActiveRecord::TypedStore::TypedHash

Attributes

fields[R]

Public Class Methods

create(fields) click to toggle source
# File lib/active_record/typed_store/typed_hash.rb, line 9
def create(fields)
  Class.new(self) do
    @fields = fields.index_by { |c| c.name.to_s }
  end
end
defaults_hash() click to toggle source
# File lib/active_record/typed_store/typed_hash.rb, line 15
def defaults_hash
  Hash[fields.values.select(&:has_default?).map { |c| [c.name, c.default] }]
end
new(constructor={}) click to toggle source
Calls superclass method
# File lib/active_record/typed_store/typed_hash.rb, line 23
def initialize(constructor={})
  super()
  update(defaults_hash)
  update(constructor.to_h) if constructor.respond_to?(:to_h)
end

Public Instance Methods

[]=(key, value) click to toggle source
Calls superclass method
# File lib/active_record/typed_store/typed_hash.rb, line 29
def []=(key, value)
  super(key, cast_value(key, value))
end
Also aliased as: store
merge!(other_hash) { |convert_key(key), self, value| ... } click to toggle source
# File lib/active_record/typed_store/typed_hash.rb, line 34
def merge!(other_hash)
  other_hash.each_pair do |key, value|
    if block_given? && key?(key)
      value = yield(convert_key(key), self[key], value)
    end
    self[convert_key(key)] = convert_value(value)
  end
  self
end
Also aliased as: update
store(key, value)
Alias for: []=
update(other_hash)
Alias for: merge!

Private Instance Methods

cast_value(key, value) click to toggle source
# File lib/active_record/typed_store/typed_hash.rb, line 49
def cast_value(key, value)
  key = convert_key(key)
  field = fields[key]
  return value unless field

  casted_value = field.cast(value)

  if casted_value.nil? && !field.null && field.has_default?
    return field.default
  end

  casted_value
end