Last active
January 2, 2016 23:29
-
-
Save tomclose/8376987 to your computer and use it in GitHub Desktop.
A module that can be used to transform the keys and values for a subset of pairs in a hash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FruitImporter | |
include HashRemapper | |
remaps 'fruit_name', to: :name | |
remaps 'id', to: :fruit_store_id | |
remaps 'coordinates', to: :coordinates_x, value: ->(c) { c[0].to_f if c} | |
remaps 'coordinates', to: :coordinates_y, value: ->(c) { c[1].to_f if c} | |
def import(fruit_hash) | |
Fruit.create(remap(fruit_hash)) | |
end | |
end | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module HashRemapper | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
def remap(old_hash) | |
new_hash = old_hash.dup | |
self.class.mappings.each do |from, params| | |
to = params.fetch(:to) { from } | |
using = params.fetch(:value) { ->(x) {x} } | |
val = old_hash.fetch(from) | |
new_hash.delete(from) | |
new_hash[to] = using.call(val) | |
end | |
new_hash | |
end | |
module ClassMethods | |
def mappings | |
@mappings ||= {} | |
end | |
def remaps(a, params) | |
self.mappings.merge!({a => params}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment