diff options
| author | Alban Peignier | 2017-02-18 13:23:15 +0100 | 
|---|---|---|
| committer | Alban Peignier | 2017-02-18 13:23:15 +0100 | 
| commit | 34ff53159c40b3bec72b479317a1692e36c6f413 (patch) | |
| tree | bae60ffc7880b82320dacb18e53e34ab59f9efb1 /lib/activeattr_ext.rb | |
| parent | 556920ec50788cda6f07832a42f222fa22ce66e0 (diff) | |
| download | chouette-core-34ff53159c40b3bec72b479317a1692e36c6f413.tar.bz2 | |
Support multi parameter in ReferentialMetadata::Period to fix begin/end dates. Refs #2621
Diffstat (limited to 'lib/activeattr_ext.rb')
| -rw-r--r-- | lib/activeattr_ext.rb | 39 | 
1 files changed, 39 insertions, 0 deletions
| 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 | 
