Module: ValidatesTimeliness::ActionView::InstanceTag

Defined in:
lib/validates_timeliness/action_view/instance_tag.rb

Overview

Intercepts the date and time select helpers to reuse the values from the the params rather than the parsed value. This allows invalid date/time values to be redisplayed instead of blanks to aid correction by the user. Its a minor usability improvement which is rarely an issue for the user.

Defined Under Namespace

Classes: TimelinessDateTime

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



17
18
19
20
21
22
23
24
# File 'lib/validates_timeliness/action_view/instance_tag.rb', line 17

def self.included(base)
  selector_method = Rails::VERSION::STRING.to_f < 2.2 ? :date_or_time_select : :datetime_selector
  base.class_eval do
    alias_method :datetime_selector_without_timeliness, selector_method
    alias_method selector_method, :datetime_selector_with_timeliness
  end
  base.alias_method_chain :value, :timeliness
end

Instance Method Details

#datetime_selector_with_timeliness(*args) ⇒ Object



56
57
58
59
# File 'lib/validates_timeliness/action_view/instance_tag.rb', line 56

def datetime_selector_with_timeliness(*args)
  @timeliness_date_or_time_tag = true
  datetime_selector_without_timeliness(*args)
end

#value_with_timeliness(object) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/validates_timeliness/action_view/instance_tag.rb', line 61

def value_with_timeliness(object)
  unless @timeliness_date_or_time_tag && @template_object.params[@object_name]
    return value_without_timeliness(object)
  end

  pairs = @template_object.params[@object_name].select {|k,v| k =~ /^#{@method_name}\(/ }
  return value_without_timeliness(object) if pairs.empty?

  values = pairs.map do |(param, value)|
    position = param.scan(/\(([0-9]*).*\)/).first.first
    [position, value.to_i]
  end.sort {|a,b| a[0] <=> b[0] }.map {|v| v[1] }

  TimelinessDateTime.new(*values)
end