Skip to content

Instantly share code, notes, and snippets.

@croaky
Created June 21, 2010 21:32
Show Gist options
  • Save croaky/447526 to your computer and use it in GitHub Desktop.
Save croaky/447526 to your computer and use it in GitHub Desktop.
Taking an Array of Hashes and turning them into key-value pairs using a style similar to ActiveRecord's dynamic finders.
class Array
attr_accessor :dynamic_mapper_key, :dynamic_mapper_value
def method_missing(method, *args, &block)
if dynamic_mapper?(method)
map_dynamically(method)
else
super
end
end
def dynamic_mapper?(method)
if method.to_s =~ /^map_([_a-zA-Z]\w*)_to_([_a-zA-Z]\w*)$/
self.dynamic_mapper_key = $1
self.dynamic_mapper_value = $2
end
end
def map_dynamically(method)
inject({}) do |result, hash|
result.update(hash[dynamic_mapper_key] => hash[dynamic_mapper_value])
end
end
end
puts project_hashes.map_name_to_color.inspect
# {"suspenders"=>"red", "shoulda"=>"green", "high_voltage"=>"green", "gemcutter"=>"green",
# "paperclip"=>"green", "factory_girl"=>"green", "umbrellatoday"=>"green", "hoptoad"=>"green"}
@damselem
Copy link

Really nice... I recently read about it in the Metaprogramming Ruby book.

@jnunemaker
Copy link

Instead of openening array, I would maybe just decorate each array with a module that includes the dynamic stuff. Then you aren't messing with core libs and it only adds the functionality to the specific arrays that need it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment