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
|
# File 'lib/flexible_date.rb', line 3
def flexible_date(*params)
params.last.kind_of?(Hash) ? (options, fields = params.pop, params) : (options, fields = {}, params)
suffix = options[:suffix] || "flex"
condition = options[:if]
fields.each do |field|
normalized_field = normalize(field, suffix)
unless methods.include?(:flexible_date_validations)
validate :flexible_date_validations
define_method :flexible_date_validations do
if @flexible_date_errors
@flexible_date_errors.each do |f, message|
errors.add(f, message)
end
end
end
end
define_method "#{normalized_field}_#{suffix}" do
format = I18n.t("flexible_date.configuration.format")
date = self.send("#{normalized_field}")
date.try(:strftime, format)
end
define_method "#{normalized_field}_#{suffix}=" do |value|
try_t = lambda do |option1, option2|
begin
I18n.t option1, :raise => true
rescue I18n::MissingTranslationData
I18n.t option2
end
end
@flexible_date_errors ||= {}
if condition and not condition.call(self)
@flexible_date_errors["#{normalized_field}".to_sym] = try_t.call(
"flexible_date.messages.without_suffix.invalid",
"flexible_date.messages.invalid")
@flexible_date_errors["#{normalized_field}_#{suffix}".to_sym] = try_t.call(
"flexible_date.messages.with_suffix.invalid",
"flexible_date.messages.invalid")
else
begin
format = I18n.t("flexible_date.configuration.format")
self.send("#{normalized_field}=", value.blank? ? "" : Date.strptime(value, format))
rescue ArgumentError
self.send("#{normalized_field}=", nil)
@flexible_date_errors["#{normalized_field}".to_sym] = try_t.call(
"flexible_date.messages.without_suffix.invalid",
"flexible_date.messages.invalid")
@flexible_date_errors["#{normalized_field}_#{suffix}".to_sym] = try_t.call(
"flexible_date.messages.with_suffix.invalid",
"flexible_date.messages.invalid")
end
end
end
end
end
|