Created
March 8, 2012 03:14
-
-
Save JeffCohen/1998347 to your computer and use it in GitHub Desktop.
Fun with array mapping
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 | |
def method_missing(m, *args) | |
map_elements(m, args) || super | |
end | |
def map_elements(m, *args) | |
target_method = singular_of(m) | |
new_array = map do |element| | |
if element.respond_to?(target_method) | |
if args.length > 0 | |
element.send(target_method) | |
else | |
element.send(target_method, args) | |
end | |
else | |
nil | |
end | |
end | |
return nil if new_array.compact.empty? | |
new_array | |
end | |
def singular_of(m) | |
begin | |
# Hope that Rails is installed | |
m.to_s.singularize | |
rescue | |
# Poor man's attempt to singularize | |
if m.to_s =~ /s$/ | |
m = m.to_s[0..-2] | |
end | |
m | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment