diff --git a/README.md b/README.md index d71292c..0c1fcdc 100644 --- a/README.md +++ b/README.md @@ -306,6 +306,24 @@ EggMapper.normalize({}, options: { no_default: true }) EggMapper.denormalize({fried: 4}) ``` +#### Importing mappings from another mapper + +Use `.import_mapper(another_mapper)` to import mappings from another mapper. This is useful when you want to reuse mappings from another mapper. + +```ruby +class Mapper1 + extend HashMapper + map from('/name'), to('/name') +end + +class Mapper2 + extend HashMapper + import_mapper Mapper1 + map from('/age'), to('/age') +end + +# Mapper2 will have mappings from Mapper1 ('/name' => '/name') and its own mappings ('/age' => '/age') +``` ## REQUIREMENTS: diff --git a/lib/hash_mapper.rb b/lib/hash_mapper.rb index 499e923..68a0ea0 100644 --- a/lib/hash_mapper.rb +++ b/lib/hash_mapper.rb @@ -71,6 +71,10 @@ def from(path, &filter) path_map end + def import_mapper(mapper) + self.maps = self.maps + mapper.maps.dup + end + alias :to :from def using(mapper_class) diff --git a/spec/hash_mapper_spec.rb b/spec/hash_mapper_spec.rb index 7b46fcc..001255c 100644 --- a/spec/hash_mapper_spec.rb +++ b/spec/hash_mapper_spec.rb @@ -446,6 +446,25 @@ class DefaultValues end end +describe '.import_mapper(another_mapper)' do + let(:mapper) do + Class.new do + extend HashMapper + + import_mapper DefaultValues + map from('/name'), to('/nombre') + end + end + + it 'imports the mappings from another mapper' do + expect(mapper.maps.size).to eq(3) + expect(mapper.normalize({ + 'without_default' => 'some_value', + 'name' => 'ismael' + })).to eq({ not_defaulted: 'some_value', defaulted: 'the_default_value', nombre: 'ismael' }) + end +end + class MultiBeforeFilter extend HashMapper