Sha256: 82525140b724755d8693f1b5fa171240d090f6cda2bfa5e5018b815bc23c1768

Contents?: true

Size: 1.8 KB

Versions: 6

Compression:

Stored size: 1.8 KB

Contents

module ValidatesTimeliness
  module Extensions
    module DateTimeSelect
      extend ActiveSupport::Concern

      # Intercepts the date and time select helpers to reuse the values from
      # 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.
      # It's a minor usability improvement which is rarely an issue for the user.

      included do
        alias_method_chain :value, :timeliness
      end

      class TimelinessDateTime
        attr_accessor :year, :month, :day, :hour, :min, :sec

        def initialize(year, month, day, hour, min, sec)
          @year, @month, @day, @hour, @min, @sec = year, month, day, hour, min, sec
        end

        # adapted from activesupport/lib/active_support/core_ext/date_time/calculations.rb, line 36 (3.0.7)
        def change(options)
          TimelinessDateTime.new(
            options[:year]  || year,
            options[:month] || month,
            options[:day]   || day,
            options[:hour]  || hour,
            options[:min]   || (options[:hour] ? 0 : min),
            options[:sec]   || ((options[:hour] || options[:min]) ? 0 : sec)
          )
        end
      end

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

        @template_object.params[@object_name]

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

        values = [nil] * 6
        pairs.map do |(param, value)|
          position = param.scan(/\((\d+)\w+\)/).first.first
          values[position.to_i-1] = value.to_i
        end

        TimelinessDateTime.new(*values)
      end

    end
  end
end

Version data entries

6 entries across 6 versions & 2 rubygems

Version Path
validates_timeliness-4.1.1 lib/validates_timeliness/extensions/date_time_select.rb
validates_timeliness-4.1.0 lib/validates_timeliness/extensions/date_time_select.rb
enju_leaf-1.2.1 vendor/bundle/ruby/2.3/gems/validates_timeliness-4.0.2/lib/validates_timeliness/extensions/date_time_select.rb
validates_timeliness-4.0.2 lib/validates_timeliness/extensions/date_time_select.rb
validates_timeliness-4.0.1 lib/validates_timeliness/extensions/date_time_select.rb
validates_timeliness-4.0.0 lib/validates_timeliness/extensions/date_time_select.rb