Module: ValueClass

Defined in:
lib/value_class.rb,
lib/value_class/version.rb,
lib/value_class/attribute.rb,
lib/value_class/constructable.rb

Defined Under Namespace

Modules: ClassMethods, Constructable Classes: Attribute

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
# File 'lib/value_class.rb', line 7

def self.included(base)
  base.extend(ClassMethods)
end

.struct(*args) ⇒ Object



47
48
49
50
51
52
# File 'lib/value_class.rb', line 47

def self.struct(*args)
  Class.new do
    include ValueClass::Constructable
    value_attrs(*args)
  end
end

Instance Method Details

#eql?(other) ⇒ Boolean

TODO: These need to be added to attr_comparible

Returns:

  • (Boolean)


21
22
23
# File 'lib/value_class.rb', line 21

def eql?(other)
  self == other
end

#hashObject



25
26
27
28
29
# File 'lib/value_class.rb', line 25

def hash
  self.class.value_attributes.map do |attribute|
    instance_variable_get("@#{attribute.name}")
  end.hash
end

#initialize(config = {}) ⇒ Object

Default constructor



12
13
14
15
16
17
18
# File 'lib/value_class.rb', line 12

def initialize(config = {})
  check_constructor_params(config)
  self.class.declare_comparison_operators
  self.class.value_attributes.each do |attribute|
    instance_variable_set("@#{attribute.name}", attribute.get_value(config).freeze)
  end
end

#to_hashObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/value_class.rb', line 31

def to_hash
  self.class.value_attributes.each_with_object({}) do |attribute, hash|
    # Attributes are frozen, but hash with indifferent access mutates values (!!!), so we have to dup
    # in order to get a value we can use
    unsafe_version = attribute.hash_value(instance_variable_get("@#{attribute.name}"))
    safe_version =
      begin
        unsafe_version.dup
      rescue TypeError
        unsafe_version
      end

    hash[attribute.name.to_sym] = safe_version
  end
end