Class: Zenaton::Services::Properties

Inherits:
Object
  • Object
show all
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.

[Time, Date, DateTime].freeze

Instance Method Summary collapse

Instance Method Details

#blank_instance(class_name) ⇒ Object

Returns an allocated instance of the given class name

Parameters:

  • class_name (String)

    the name of the class to allocate

Returns:

  • (Object)


16
17
18
19
20
21
22
23
# File 'lib/zenaton/services/properties.rb', line 16

def blank_instance(class_name)
  klass = Object.const_get(class_name)
  if klass < Singleton
    klass.instance
  else
    klass.allocate
  end
end

#from(object) ⇒ Hash

Returns a hash with the instance variables of a given object

Parameters:

  • object (Object)

    the object to be read

Returns:

  • (Hash)


28
29
30
31
32
33
34
# File 'lib/zenaton/services/properties.rb', line 28

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

Parameters:

  • class_name (String)

    name of the class to instantiate

  • properties (Hash)

    the properties to be written

  • super_class (Class) (defaults to: nil)

    the optional class the object should inherit

Returns:

  • (Object)


54
55
56
57
58
59
# File 'lib/zenaton/services/properties.rb', line 54

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

Parameters:

  • object (Object)

    the object to write the variables to

  • properties (Hash)

    the properties to be written

Returns:

  • (Object)


40
41
42
43
44
45
46
# File 'lib/zenaton/services/properties.rb', line 40

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