Module: Zena::Use::NestedAttributesAlias::ModelMethods
- Included in:
- Node
- Defined in:
- lib/zena/use/nested_attributes_alias.rb
Overview
Adds a class method called ‘resolve_attributes_alias’ to rewrite attributes.
Example:
class Foo < ActiveRecord::Base
include Zena::Use::NestedAttributesAlias::ModelMethods
has_one :redaction
nested_attributes_alias /^r_(.+)/ => 'redaction'
end
Class Method Summary collapse
Instance Method Summary collapse
- #attributes_with_nested_alias=(*args) ⇒ Object
- #nested_model_names_for_alias(attribute) ⇒ Object
- #resolve_attributes_alias(attributes) ⇒ Object
Class Method Details
.included(base) ⇒ Object
74 75 76 77 78 79 80 81 |
# File 'lib/zena/use/nested_attributes_alias.rb', line 74 def self.included(base) base.extend Zena::Use::NestedAttributesAlias::ClassMethods if !base.method_defined?(:attributes_without_nested_alias=) base.class_eval do alias_method_chain :attributes=, :nested_alias end end end |
Instance Method Details
#attributes_with_nested_alias=(*args) ⇒ Object
83 84 85 |
# File 'lib/zena/use/nested_attributes_alias.rb', line 83 def attributes_with_nested_alias=(*args) self.attributes_without_nested_alias = resolve_attributes_alias(*args) end |
#nested_model_names_for_alias(attribute) ⇒ Object
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/zena/use/nested_attributes_alias.rb', line 102 def nested_model_names_for_alias(attribute) attribute = attribute.to_s nested_model_names = nil self.class.nested_attr_alias_list.each do |regexp, target| if attribute =~ regexp if target.kind_of?(Proc) if nested_model_names = target.call(self, $~.to_a) break end else nested_model_names = target + [$1] break end end end nested_model_names end |
#resolve_attributes_alias(attributes) ⇒ Object
87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/zena/use/nested_attributes_alias.rb', line 87 def resolve_attributes_alias(attributes) new_attributes = {} attributes.each do |k, v| if nested_model_names = nested_model_names_for_alias(k) if new_key = nested_model_names.pop v = v.stringify_keys if v.kind_of?(Hash) merge_nested_model_names_in_hash(new_attributes, nested_model_names.map {|nested_model_name| "#{nested_model_name}_attributes"})[new_key] = v end else deep_merge_hash(new_attributes, k => v) end end new_attributes end |