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

NUMERIC_INITIALIATION =

Handle blank object instantiation differently for these classes

[
  ::Rational,
  ::Complex,
  defined?(::BigDecimal) ? ::BigDecimal : nil
].compact.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)


22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/zenaton/services/properties.rb', line 22

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

Parameters:

  • object (Object)

    the object to be read

Returns:

  • (Hash)


38
39
40
# File 'lib/zenaton/services/properties.rb', line 38

def from(object)
  object.to_zenaton
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)


59
60
61
62
63
64
# File 'lib/zenaton/services/properties.rb', line 59

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)


46
47
48
49
50
51
# File 'lib/zenaton/services/properties.rb', line 46

def set(object, properties)
  klass = object.class
  return klass.from_zenaton(properties) if defined?(klass.from_zenaton)

  fallback_set(object, properties)
end