blob: da8eb10dc6d1eda98cd51d99abf87aa357160cb5 (
plain) (
blame)
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
64
65
66
67
68
69
70
71
72
73
74
75
|
module ActiveRecord
class Attribute # :nodoc:
class << self
def from_database(value, type)
FromDatabase.new(value, type)
end
def from_user(value, type)
FromUser.new(value, type)
end
end
attr_reader :value_before_type_cast, :type
# This method should not be called directly.
# Use #from_database or #from_user
def initialize(value_before_type_cast, type)
@value_before_type_cast = value_before_type_cast
@type = type
end
def value
# `defined?` is cheaper than `||=` when we get back falsy values
@value = type_cast(value_before_type_cast) unless defined?(@value)
@value
end
def value_for_database
type.type_cast_for_database(value)
end
def changed_from?(old_value)
type.changed?(old_value, value, value_before_type_cast)
end
def changed_in_place_from?(old_value)
type.changed_in_place?(old_value, value)
end
def type_cast
raise NotImplementedError
end
protected
def initialize_dup(other)
if defined?(@value) && @value.duplicable?
@value = @value.dup
end
end
class FromDatabase < Attribute # :nodoc:
def type_cast(value)
type.type_cast_from_database(value)
end
end
class FromUser < Attribute # :nodoc:
def type_cast(value)
type.type_cast_from_user(value)
end
end
class Null # :nodoc:
class << self
attr_reader :value, :value_before_type_cast, :value_for_database
def changed_from?(*)
false
end
alias changed_in_place_from? changed_from?
end
end
end
end
|