Class: Valuable

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(atts = {}) ⇒ Valuable

Returns a new instance of Valuable.



9
10
11
# File 'lib/valuable.rb', line 9

def initialize(atts = {})
  atts.each { |name, value| __send__("#{name}=", value ) } 
end

Class Method Details

.attributesObject



19
20
21
# File 'lib/valuable.rb', line 19

def attributes
  @attributes ||= []
end

.create_accessor_for(name) ⇒ Object



70
71
72
73
74
# File 'lib/valuable.rb', line 70

def create_accessor_for(name)
  define_method name do
    attributes[name]
  end
end

.create_setter_for(name, klass, default) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/valuable.rb', line 35

def create_setter_for(name, klass, default)

  if klass == nil
    define_method "#{name}=" do |value|
      attributes[name] = value 
    end

  elsif klass == Integer

    define_method "#{name}=" do |value|
      value_as_integer = value && value.to_i
      attributes[name] = value_as_integer
    end

  elsif klass == String

    define_method "#{name}=" do |value|
      value_as_string = value && value.to_s
      attributes[name] = value_as_string
    end

  else

    define_method "#{name}=" do |value|
      if value.nil?
        attributes[name] = nil 
      elsif value.is_a? klass
        attributes[name] = value
      else
        attributes[name] = klass.new(value)
      end
    end
  end
end

.defaultsObject



23
24
25
# File 'lib/valuable.rb', line 23

def defaults
  @defaults ||= {}
end

.has_collection(name) ⇒ Object



76
77
78
# File 'lib/valuable.rb', line 76

def has_collection(name)
  has_value(name, default: [] )
end

.has_value(name, options = {}) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/valuable.rb', line 27

def has_value(name, options={})
  attributes << name 
  defaults[name] = options[:default] unless options[:default].nil?

  create_accessor_for(name)
  create_setter_for(name, options[:klass], options[:default])
end

Instance Method Details

#attributesObject



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

def attributes
  @attributes ||= HashWithIndifferentAccess.new(deep_duplicate_of(self.class.defaults)) 
end

#deep_duplicate_of(value) ⇒ Object



13
14
15
# File 'lib/valuable.rb', line 13

def deep_duplicate_of(value)
  Marshal.load(Marshal.dump(value))
end