Module: Institutions::Merge
- Included in:
- Institution
- Defined in:
- lib/institutions/institution/merge.rb
Overview
:no_doc
Instance Method Summary collapse
-
#merge(arg = {}) ⇒ Object
Merges the given arguments into the Institution.
Instance Method Details
#merge(arg = {}) ⇒ Object
Merges the given arguments into the Institution. Internally uses a “recursive merge” algorithm to preserve as much of the original Institution as possible. Assumes the argument has a to_hash method Example.
require 'institutions'
hash1 = { "string_attribute" => "first string",
:nested_hash_attribute => {
:h1 => {:h1_2 => "first12"},
:h2 => {:h2_1 => "first21", :h2_2 => "first22"}},
:array_attribute => [1, 2, 4] }
institution1 = Institutions::Institution.new("first_inst", "First Institution", hash1)
p institution1 # -> #<Institutions::Institution @code=:first_inst, @name="First Institution", @array_attribute=[1, 2, 4], @default=false, @string_attribute="first string", @nested_hash_attribute={:h1=>{:h1_2=>"first12"}, :h2=>{:h2_1=>"first21", :h2_2=>"first22"}}>
hash2 = { "string_attribute" => "second string",
:nested_hash_attribute => {:h1 => {
:h1_2 => "second12"},
:h2 => {:h2_2 => "second22"}},
:array_attribute => [1, 2, 3], :default => true }
institution2 = Institutions::Institution.new("second_inst", "Second Institution", hash2)
p institution2 # -> <Institutions::Institution @code=:second_inst, @name="Second Institution", @array_attribute=[1, 2, 3], @default=true, @string_attribute="second string", @nested_hash_attribute={:h1=>{:h1_2=>"second12"}, :h2=>{:h2_2=>"second22"}}>
institution1.merge(institution2)
p institution1 # -> #<Institutions::Institution @code=:first_inst, @name="First Institution", @array_attribute=[1, 2, 4, 3], @default=true, @string_attribute="second string", @nested_hash_attribute={:h1=>{:h1_2=>"second12"}, :h2=>{:h2_1=>"first21", :h2_2=>"second22"}}>
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/institutions/institution/merge.rb', line 28 def merge(arg={}) arg.to_hash.each do |key, value| next unless valid_instance_variable? key instance_variable = instance_variablize(key) if instance_variable_defined? instance_variable instance_variable_set(instance_variable, deep_merge(instance_variable_get(instance_variable), value, key)) else writer_method = "#{key}=".to_sym if respond_to? writer_method send writer_method, value else next if [:code, :name].include? key.to_sym # Set each hash value as an instance variable, but don't overwrite code or name values. instance_variable_set(instance_variable, value) end end end end |