Skip to content

Instantly share code, notes, and snippets.

@koic
Last active August 29, 2015 14:07
Show Gist options
  • Save koic/8c6a5fc07d050723b748 to your computer and use it in GitHub Desktop.
Save koic/8c6a5fc07d050723b748 to your computer and use it in GitHub Desktop.
Array#map_chain
#
# 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