Last active
August 29, 2015 14:07
-
-
Save koic/8c6a5fc07d050723b748 to your computer and use it in GitHub Desktop.
Array#map_chain
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
# | |
# RSpec の its('foo.bar.baz') { ... } にインスパイアされたものです。 | |
# | |
# array.map(&:foo).map(&:bar).map(&:baz) を array.map_chain('foo.bar.baz') と | |
# 書けるものを書いてみたけれど、実際のところ AR でもちいると n+1 query が起きるため | |
# Gems にするには今ひとつはばかれるのであった。 | |
# | |
class Array | |
def map_chain(method_names) | |
case method_names | |
when Array | |
method_names.inject(self) {|result, method_name| | |
result.map {|elem| elem.method(method_name).call } | |
} | |
when String | |
map_chain(method_names.split('.').map(&:strip)) | |
else | |
raise ArgumentError | |
end | |
end | |
alias collect_chain map_chain | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment