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
|
# File 'lib/time_splitter/accessors.rb', line 3
def split_accessor(*attrs)
options = attrs.
attrs.each do |attr|
composed_of "#{attr}_time".to_sym, class_name: 'DateTime' if self.respond_to?(:composed_of)
define_method("#{attr}_or_new") do
self.send(attr) || options.fetch(:default, ->{ Time.new(0, 1, 1, 0, 0, 0, "+00:00") }).call
end
define_method("#{attr}_date=") do |date|
return unless date.present?
unless date.is_a?(Date) || date.is_a?(Time)
if options[:date_format]
date = Date.strptime(date.to_s, options[:date_format])
else
date = Date.parse(date.to_s)
end
end
self.send("#{attr}=", self.send("#{attr}_or_new").change(year: date.year, month: date.month, day: date.day))
end
define_method("#{attr}_hour=") do |hour|
return unless hour.present?
self.send("#{attr}=", self.send("#{attr}_or_new").change(hour: hour, min: self.send("#{attr}_or_new").min))
end
define_method("#{attr}_min=") do |min|
return unless min.present?
self.send("#{attr}=", self.send("#{attr}_or_new").change(min: min))
end
define_method("#{attr}_time=") do |time|
return unless time.present?
unless time.is_a?(Date) || time.is_a?(Time)
if options[:time_format]
time = Time.strptime(time, options[:time_format])
else
time = Time.parse(time)
end
end
self.send("#{attr}=", self.send("#{attr}_or_new").change(hour: time.hour, min: time.min))
end
define_method("#{attr}_date") do
date = self.send(attr).try :to_date
date && options[:date_format] ? date.strftime(options[:date_format]) : date
end
define_method("#{attr}_hour") do
self.send(attr).try :hour
end
define_method("#{attr}_min") do
self.send(attr).try :min
end
define_method("#{attr}_time") do
time = self.send(attr)
time && options[:time_format] ? time.strftime(options[:time_format]) : time
end
end
end
|