Module: Ohm::Typecast::ClassMethods
- Defined in:
- lib/ohm/contrib/typecast.rb
Instance Method Summary collapse
-
#attribute(name, type = Ohm::Types::String, klass = ) ⇒ Array?
(also: #typecast)
Defines a typecasted attribute.
Instance Method Details
#attribute(name, type = Ohm::Types::String, klass = ) ⇒ Array? Also known as: typecast
Defines a typecasted attribute.
315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/ohm/contrib/typecast.rb', line 315 def attribute(name, type = Ohm::Types::String, klass = Ohm::Types[type]) # Primitive types maintain a reference to the original object # stored in @_attributes[att]. Hence mutation works for the # Primitive case. For cases like Hash, Array where the value # is `JSON.parse`d, we need to set the actual Ohm::Types::Hash # (or similar) to @_attributes[att] for mutation to work. if klass.superclass == Ohm::Types::Primitive define_method(name) { klass[read_local(name)] } else define_method(name) { write_local(name, klass[read_local(name)]) } end define_method(:"#{name}=") do |value| write_local(name, klass[value].to_s) end attributes << name unless attributes.include?(name) end |