Reputation: 342
Say I have this scope:
scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
and I want an equivalent scope
scope :has_zipcode, lambda { |zip| where(zipcode: zip) }
is there a way to alias one scope to another? For instance something like
alias :with_zipcode, :has_zipcode
P.S. I know this is a contrived and unrealistic example, just curious to know if it is possible!
Thanks!
Upvotes: 25
Views: 6585
Reputation: 17735
An alternative way to define an alias for a class method which I personally find a bit more self-explanatory:
class User < ActiveRecord::Base
scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
class << self
alias has_zipcode with_zipcode
end
end
Upvotes: 14
Reputation: 102222
Yes you can. Just remember that scopes are class methods so that you need to alias in the context of the class:
class User < ActiveRecord::Base
scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
singleton_class.send(:alias_method, :has_zipcode, :with_zipcode)
end
Upvotes: 40
Reputation: 7038
Another solution is to call one scope from another
class User < ActiveRecord::Base
scope :with_zipcode, lambda { |zip| where(zipcode: zip) }
scope :has_zipcode, lambda { |zip| with_zipcode(zip) } # essentially an alias
end
Using singleton_class.send(:alias_method, :a, :b)
is probably less ambiguous, but just wanted to alert to another option.
Upvotes: 9