Commit
…ods like scoped_by_user_name(user_name) and scoped_by_user_name_and_password(user_name, password) that will use the scoped method with attributes you supply. [#1648 state:committed] Signed-off-by: David Heinemeier Hansson <david@loudthinking.com>
- Loading branch information
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
module ActiveRecord | ||
class DynamicScopeMatch | ||
def self.match(method) | ||
ds_match = self.new(method) | ||
ds_match.scope ? ds_match : nil | ||
end | ||
|
||
def initialize(method) | ||
@scope = true | ||
case method.to_s | ||
when /^scoped_by_([_a-zA-Z]\w*)$/ | ||
names = $1 | ||
else | ||
@scope = nil | ||
end | ||
@attribute_names = names && names.split('_and_') | ||
end | ||
|
||
attr_reader :scope, :attribute_names | ||
|
||
def scope? | ||
!@scope.nil? | ||
end | ||
end | ||
end |
6 comments
on commit 66ee589
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@shingara well, actually we can since we use fixtures :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I would suggest dropping the “scoped_” preffix, as it IMO improves readability:
User.by_name_and_password.find(:all)
User.by_name.by_password.find(:all, :order => 'created_at')
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Still, the “scoped_” prefix allows for clarity of what’s happening.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I prefer it with the “scoped_” prefix, as it’s more in keeping with related declarations (e.g. “named_scope”, “default_scope” etc.)
Using fabiokungs examples, I think it actually rolls of the tongue worse without the prefixes!
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I am ok with “scoped_” prefix
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’d agree with fabiokung except that I tend to use “by_x” for named scopes that add an :order. E.g. “by_created”, so having “by_name” use conditions instead of order could get weird, for me at least. “with_” might make more sense for conditions anyway.
To be clear, I don’t mind “scoped_by” or “find_by” since the “by” is prefixed.
it’s not better with assert on :
Post.find(:first, :conditions => { :author_id => 1})
because we can’t assume that Post(1) is allways to author_id(1).