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
|
# File 'lib/type_cast.rb', line 8
def type_cast(*args)
caster = args.pop
if args.empty?
raise ArgumentError, 'Instance methods for type casting supposed to be provided (e.g. type_cast :created_at, :updated_at, Time).'
end
if caster.respond_to?(:parse)
args.each do |attribute|
class_eval " def \#{attribute}\n @\#{attribute}_after_type_cast ||= begin\n uncasted = if defined?(super)\n super\n else\n method_missing(:\#{attribute})\n end\n self.\#{attribute}_before_type_cast = uncasted\n if uncasted.kind_of?(String)\n \#{caster}.parse(uncasted)\n else\n uncasted\n end\n rescue\n uncasted\n end\n end\n attr_writer :\#{attribute}_before_type_cast\n def \#{attribute}_before_type_cast\n @\#{attribute}_before_type_cast || (\#{attribute}; \#{attribute}_before_type_cast)\n end\n RUBY\n end\n elsif caster.respond_to?(:to_sym)\n conversion_method = caster.to_sym\n args.each do |attribute|\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def \#{attribute}\n @\#{attribute}_after_type_cast ||= begin\n uncasted = if defined?(super)\n super\n else\n method_missing(:\#{attribute})\n end\n self.\#{attribute}_before_type_cast = uncasted\n if uncasted.respond_to?(:\#{conversion_method})\n uncasted.__send__(:\#{conversion_method})\n else\n uncasted\n end\n rescue\n uncasted\n end\n end\n attr_writer :\#{attribute}_before_type_cast\n def \#{attribute}_before_type_cast\n @\#{attribute}_before_type_cast || (\#{attribute}; \#{attribute}_before_type_cast)\n end\n RUBY\n end\n else\n raise ArgumentError, 'Type casting needs an object with parse method or method name which should be called on casted attributes. Supply it as last argument (e.g. type_cast :created_at, Time).'\n end\nend\n", __FILE__, __LINE__ + 1
|