diff options
| -rw-r--r-- | app/models/referential_metadata.rb | 3 | ||||
| -rw-r--r-- | lib/activeattr_ext.rb | 39 | ||||
| -rw-r--r-- | spec/models/referential_metadata_spec.rb | 8 | 
3 files changed, 50 insertions, 0 deletions
| diff --git a/app/models/referential_metadata.rb b/app/models/referential_metadata.rb index e752a6ca0..f3f8e2eff 100644 --- a/app/models/referential_metadata.rb +++ b/app/models/referential_metadata.rb @@ -1,3 +1,5 @@ +require 'activeattr_ext.rb' +  class ReferentialMetadata < ActiveRecord::Base    belongs_to :referential    belongs_to :referential_source, class_name: 'Referential' @@ -12,6 +14,7 @@ class ReferentialMetadata < ActiveRecord::Base    class Period      include ActiveAttr::Model +    include ActiveAttr::MultiParameterAttributes      attribute :id, type: Integer      attribute :begin, type: Date diff --git a/lib/activeattr_ext.rb b/lib/activeattr_ext.rb new file mode 100644 index 000000000..b4c112b72 --- /dev/null +++ b/lib/activeattr_ext.rb @@ -0,0 +1,39 @@ +module ActiveAttr::MultiParameterAttributes + +  def assign_attributes(new_attributes, options = {}) +    super( +      expand_multiparameter_attributes(new_attributes), +      options +    ) +  end + +  def expand_multiparameter_attributes(attributes) +    attributes ||= {} + +    single_parameter_attributes = {} +    multi_parameter_attributes = {} + +    attributes.each do |key, value| +      matches = key.match(/^(?<key>[^\(]+)\((?<index>\d+)i\)$/) + +      unless matches +        single_parameter_attributes[key] = value +        next +      end + +      args = (multi_parameter_attributes[matches['key']] ||= []) +      args[matches['index'].to_i - 1] = (value.present? ? value.to_i : nil) +    end + +    single_parameter_attributes.merge( +      multi_parameter_attributes.inject({}) do |hash, (key, args)| +        if args.all?(&:present?) +          hash.merge(key => _attribute_type(key).new(*args)) +        else +          hash +        end +      end +    ) +  end + +end diff --git a/spec/models/referential_metadata_spec.rb b/spec/models/referential_metadata_spec.rb index 50571ad85..7e61c54b1 100644 --- a/spec/models/referential_metadata_spec.rb +++ b/spec/models/referential_metadata_spec.rb @@ -70,6 +70,14 @@ RSpec.describe ReferentialMetadata, :type => :model do        expect(period(end: "2016-11-22").end).to eq(Date.new(2016,11,22))      end +    it "should support multiparameter on begin attribute" do +      expect(period("begin(3i)"=>"18", "begin(2i)"=>"2", "begin(1i)"=>"2017").begin).to eq(Date.new(2017,2,18)) +    end + +    it "should support multiparameter on end attribute" do +      expect(period("end(3i)"=>"18", "end(2i)"=>"2", "end(1i)"=>"2017").end).to eq(Date.new(2017,2,18)) +    end +      it { is_expected.to validate_presence_of(:begin) }      it { is_expected.to validate_presence_of(:end) } | 
