Sha256: f852d111c715005ae2c1271e1a05cafd5a5209af910746849b48598b4d4984c2

Contents?: true

Size: 1.25 KB

Versions: 5

Compression:

Stored size: 1.25 KB

Contents

Reform::Form.class_eval do
  module MultiParameterAttributes
    def self.included(base)
      base.features << self
    end

    class DateParamsFilter
      def call(params)
        date_attributes = {}

        params.each do |attribute, value|
          if value.is_a?(Hash)
            call(value) # TODO: #validate should only handle local form params.
          elsif matches = attribute.match(/^(\w+)\(.i\)$/)
            date_attribute = matches[1]
            date_attributes[date_attribute] = params_to_date(
              params.delete("#{date_attribute}(1i)"),
              params.delete("#{date_attribute}(2i)"),
              params.delete("#{date_attribute}(3i)")
            )
          end
        end
        params.merge!(date_attributes)
      end

    private
      def params_to_date(year, month, day)
        return nil if blank_date_parameter?(year, month, day)

        Date.new(year.to_i, month.to_i, day.to_i) # TODO: test fails.
      end

      def blank_date_parameter?(year, month, day)
        year.blank? || month.blank? || day.blank?
      end
    end

    def validate(params)
      # TODO: make it cleaner to hook into essential reform steps.
      # TODO: test with nested.
      DateParamsFilter.new.call(params)

      super
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
reform-1.0.4 lib/reform/form/multi_parameter_attributes.rb
reform-1.0.3 lib/reform/form/multi_parameter_attributes.rb
reform-1.0.2 lib/reform/form/multi_parameter_attributes.rb
reform-1.0.1 lib/reform/form/multi_parameter_attributes.rb
reform-1.0.0 lib/reform/form/multi_parameter_attributes.rb