Created
June 21, 2010 21:32
-
-
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.
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 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"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.