Created
May 15, 2012 06:24
-
-
Save brookr/2699567 to your computer and use it in GitHub Desktop.
Add collector methods for all attributes on objects in an array.
This file contains hidden or 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(method_name, *args, &block) | |
| if method_name.to_s.is_plural? | |
| map{ |e| e.send(method_name.to_s.singularize) } | |
| else | |
| super | |
| end | |
| end | |
| def respond_to?(method_name, include_private = false) | |
| method_name.to_s.is_plural? ? true : super | |
| end | |
| end | |
| class String | |
| def is_plural? | |
| pluralize == self | |
| end | |
| end |
Author
- Have the
to_shappen inis_plural?and you'll save yourself a method call. - This is probably the Databases job, not Ruby. Especially if it's SQL.
- Do you not have to pass those parameters to
super? - Your map could look like this: map(&method_name.singularize.to_sym)` ... I think.
Oh, and make this into a microgem instead.
(Tomorrow, I'll add the class method, so it can be just User.ids. Scandalous!)
You've just described a scope. Well, a poorly named one. You'd have something like this:
class User < ActiveRecord::Base
scope :ids, order(:id).select(:id)
endIt's probably a brazillion times faster, and also trackable better (because it's in SQL).
Author
Thanks, Kurtis! Great ideas.
method_namecomes in as a symbol, but I can putis_plural?on theSymbolclass to simplify themethod_missingcheck a bit. Seemed more useful onString, but no reason to not have it on both!- There are definitely cases where a scope is the better solution. But this also makes some scope-calling/-building easier.
- I'm not sure, having not mucked with
method_missingmuch, but the examples I found do not seem to need to pass the params on. - I'd have to
.to_sit first to singularize it. Maybe Symbol#singularize would be a good candidate to include here as well for tidyness.
Rockin. You are right, this is solid microgem territory.
Appreciate the comments!
Author
Yeah, the class version is scope-like, for sure. I'll think about adding scopes based on attribute names. I don't think I come across as many use cases for that, but it sure could be handy in the console when troubleshooting.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yay! Now I can write
User.all.idsinstead of the unsightly and awkwardly-typedUser.all.map(&:id). So much easier on the pinkies! Also much easier to read.Any good arguments against doing this?
(Tomorrow, I'll add the class method, so it can be just
User.ids. Scandalous!)