Can you alias a scope in Rails?
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
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
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.