Class: Hashing::Ivar

Inherits:
Object
  • Object
show all
Defined in:
lib/hashing/ivar.rb

Overview

Represents each one of the instance variables in a class that should be used to represent an object in a ‘Hash` form (serialization).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, to_h = nil, from_hash = nil) ⇒ Ivar

Configure the name of an ‘ivar` and the ’callable’ objects thath will be used to prepare the ‘ivar` value for serialization, and to load the object from a `Hash`.

Parameters:

  • name (Symbol)

    name of a class ‘ivar`

  • to_h (#call) (defaults to: nil)

    callable to transform the value when serializing

  • from_hash (#call) (defaults to: nil)

    callable to transform the value from a ‘Hash`



14
15
16
17
18
# File 'lib/hashing/ivar.rb', line 14

def initialize(name, to_h = nil, from_hash = nil)
  @name = name.to_sym
  @to_h = to_h
  @from_hash = from_hash
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



5
6
7
# File 'lib/hashing/ivar.rb', line 5

def name
  @name
end

Instance Method Details

#from_hash(value, metadata = {}) ⇒ Object

Processes the Object provinient from a ‘Hash` so it can be used to reconstruct an instance.

Parameters:

  • value (Object)

    object provinient from a hash

Returns:

  • the value that will be used to reconstruct the original instance



43
44
45
46
47
48
49
50
# File 'lib/hashing/ivar.rb', line 43

def from_hash(value,  = {})
  return value unless @from_hash

  if value.respond_to? :map
    value = normalize(value, )
  end
  @from_hash.call value
end

#to_h(value) ⇒ Object

Processes the parameter acordingly to the configuration made in the constructor. If some was made, return the value after being processed or else return the value as it is.

Also guarantee that if a value is a #map, every item with ‘Hashing` in his method lookup will be sent the message `#to_h`.

Parameters:

  • value (Object)

    object to be processed before being stored in a ‘Hash`

Returns:

  • the value that will be stored in the ‘Hash`



29
30
31
32
33
34
35
36
# File 'lib/hashing/ivar.rb', line 29

def to_h(value)
  return value unless @to_h

  if value.respond_to? :map
    value = hasherize value
  end
  @to_h.call value
end

#to_sObject



56
57
58
# File 'lib/hashing/ivar.rb', line 56

def to_s
  @name.to_s
end

#to_symObject



52
53
54
# File 'lib/hashing/ivar.rb', line 52

def to_sym
  @name.to_sym
end