Class: Zenaton::Services::Properties
- Inherits:
-
Object
- Object
- Zenaton::Services::Properties
- Defined in:
- lib/zenaton/services/properties.rb
Overview
Wrapper class to read instance variables from an object and to create new objects with a given set of instance variables.
Constant Summary collapse
- SPECIAL_CASES =
Handle (de)serializaton separately for these classes.
[ ::Complex, ::Date, ::DateTime, ::Range, ::Rational, ::Regexp, ::Symbol, ::Time, defined?(::OpenStruct) ? ::OpenStruct : nil, defined?(::BigDecimal) ? ::BigDecimal : nil ].compact.freeze
- NUMERIC_INITIALIATION =
Handle blank object instantiation differently for these classes
[ ::Rational, ::Complex, defined?(::BigDecimal) ? ::BigDecimal : nil ].compact.freeze
Instance Method Summary collapse
-
#blank_instance(class_name) ⇒ Object
Returns an allocated instance of the given class name.
-
#from(object) ⇒ Hash
Returns a hash with the instance variables of a given object.
-
#object_from(class_name, properties, super_class = nil) ⇒ Object
Given a class name and a set of properties, return a new instance of the class with the given properties as instance variables.
-
#set(object, properties) ⇒ Object
Returns the given object with the properties as instance variables.
Instance Method Details
#blank_instance(class_name) ⇒ Object
Returns an allocated instance of the given class name
45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/zenaton/services/properties.rb', line 45 def blank_instance(class_name) klass = Object.const_get(class_name) if klass < ::Singleton klass.instance elsif NUMERIC_INITIALIATION.include?(klass) Kernel.send(klass.to_s, 1, 1) elsif klass == Symbol :place_holder else klass.allocate end end |
#from(object) ⇒ Hash
Returns a hash with the instance variables of a given object
61 62 63 64 65 66 67 |
# File 'lib/zenaton/services/properties.rb', line 61 def from(object) return from_complex_type(object) if special_case?(object) object.instance_variables.map do |ivar| value = object.instance_variable_get(ivar) [ivar, value] end.to_h end |
#object_from(class_name, properties, super_class = nil) ⇒ Object
Given a class name and a set of properties, return a new instance of the class with the given properties as instance variables
87 88 89 90 91 92 |
# File 'lib/zenaton/services/properties.rb', line 87 def object_from(class_name, properties, super_class = nil) blank_instance(class_name).tap do |object| check_class(object, super_class) set(object, properties) end end |
#set(object, properties) ⇒ Object
Returns the given object with the properties as instance variables
73 74 75 76 77 78 79 |
# File 'lib/zenaton/services/properties.rb', line 73 def set(object, properties) return set_complex_type(object, properties) if special_case?(object) properties.each do |ivar, value| object.instance_variable_set(ivar, value) end object end |