/
default_value.rb
63 lines (54 loc) · 1.35 KB
/
default_value.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
module Virtus
class Attribute
# Class representing the default value option
class DefaultValue
DUP_CLASSES = [ ::NilClass, ::TrueClass, ::FalseClass,
::Numeric, ::Symbol ].freeze
# @api private
attr_reader :attribute
# @api private
attr_reader :value
# Initializes an default value instance
#
# @param [Virtus::Attribute] attribute
# @param [Object] value
#
# @return [undefined]
#
# @api private
def initialize(attribute, value)
@attribute = attribute
@value = case value when *DUP_CLASSES then value else value.dup end
end
# Evaluates the value
#
# @param [Object]
#
# @return [Object] evaluated value
#
# @api private
def evaluate(instance)
callable? ? call(instance) : value
end
private
# Evaluates a proc value
#
# @param [Object]
#
# @return [Object] evaluated value
#
# @api private
def call(instance)
value.call(instance, attribute)
end
# Returns if the value is callable
#
# @return [TrueClass,FalseClass]
#
# @api private
def callable?
value.respond_to?(:call)
end
end # class DefaultValue
end # class Attribute
end # module Virtus