Skip to content

Commit

Permalink
Merge pull request #27 from ismasan/import_mapper
Browse files Browse the repository at this point in the history
HashMapper.import_mapper
  • Loading branch information
ismasan authored May 24, 2024
2 parents d5c1eda + a9e209d commit dbf3c9e
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down
4 changes: 4 additions & 0 deletions lib/hash_mapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions spec/hash_mapper_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit dbf3c9e

Please sign in to comment.