Class: ActiveRecord::TypedStore::TypedHash
- Inherits:
-
HashWithIndifferentAccess
- Object
- HashWithIndifferentAccess
- ActiveRecord::TypedStore::TypedHash
- Defined in:
- lib/active_record/typed_store/typed_hash.rb
Class Attribute Summary collapse
-
.fields ⇒ Object
readonly
Returns the value of attribute fields.
Class Method Summary collapse
Instance Method Summary collapse
- #[]=(key, value) ⇒ Object (also: #store)
-
#initialize(constructor = {}) ⇒ TypedHash
constructor
A new instance of TypedHash.
- #merge!(other_hash) ⇒ Object (also: #update)
Constructor Details
#initialize(constructor = {}) ⇒ TypedHash
Returns a new instance of TypedHash.
23 24 25 26 27 |
# 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 |
Class Attribute Details
.fields ⇒ Object (readonly)
Returns the value of attribute fields.
7 8 9 |
# File 'lib/active_record/typed_store/typed_hash.rb', line 7 def fields @fields end |
Class Method Details
.create(fields) ⇒ Object
9 10 11 12 13 |
# 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 ⇒ Object
15 16 17 |
# 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 |
Instance Method Details
#[]=(key, value) ⇒ Object Also known as: store
29 30 31 |
# File 'lib/active_record/typed_store/typed_hash.rb', line 29 def []=(key, value) super(key, cast_value(key, value)) end |
#merge!(other_hash) ⇒ Object Also known as: update
34 35 36 37 38 39 40 41 42 |
# 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 |