Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HashMapper.import_mapper #27

Merged
merged 1 commit into from
May 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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