Skip to content

Instantly share code, notes, and snippets.

@rsierra
Last active December 16, 2015 13:49
Show Gist options
  • Save rsierra/5444452 to your computer and use it in GitHub Desktop.
Save rsierra/5444452 to your computer and use it in GitHub Desktop.
Multiple params assignment and dates with multiparams

Simple class multiassignment

Module to use similar model multiple params assignment and dates with multiparams (params["date(1i)"], params["date(2i)"], params["date(3i)"]) in a non ActiveModel class.

class Sample
  include ActiveModel::Multiassignment

  attr_accessor :name, :date
  multiparameter_dates :date
end
params[:sample] = {
  "name" => "John Doe",
  "date(1i)" => 2000,
  "date(2i)" => 1,
  "date(3i)" => 1
}

sample = Sample.new params[:sample]
=> #<Sample:0x007fdf19b4cb70 @date=Sat, 01 Jan 2000, @name="John Doe">
module ActiveModel
module Multiassignment
extend ActiveSupport::Concern
include ActiveModel::MultiparameterDates
def initialize(new_attributes = {})
multiassign_attributes new_attributes
end
def multiassign_attributes new_attributes
return unless new_attributes.is_a?(Hash)
self.class.parse_multiparameter_dates new_attributes
new_attributes.each do |name, value|
send("#{name}=", value)
end
end
end
end
module ActiveModel
module MultiparameterDates
extend ActiveSupport::Concern
module ClassMethods
def multiparameter_dates *date_fields
@date_fields = date_fields
end
def parse_multiparameter_dates attributes
@date_fields.each do |field|
date_keys = ["#{field}(1i)", "#{field}(2i)", "#{field}(3i)"]
if (date_keys - attributes.keys).empty?
date_values = date_keys.map { |key| attributes.delete(key).to_i }
attributes[field] = Date.civil(*date_values)
end
attributes[field] = attributes[field].to_date if attributes[field].kind_of? String
end unless @date_fields.blank?
attributes
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment