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!
Updated on March 07, 2019. To alias a method or variable name in Ruby is to create a second name for the method or variable. Aliasing can be used either to provide more expressive options to the programmer using the class or to help override methods and change the behavior of the class or object.
Scopes are custom queries that you define inside your Rails models with the scope method. Every scope takes two arguments: A name, which you use to call this scope in your code. A lambda, which implements the query.
The alias_method Method We have alias_method , which is a method defined on Module . You can only use this method at the class & module level, but not inside instance methods. Here's a description from the documentation: alias_method: “Makes new_name a new copy of the method old_name .
Scopes are used to assign complex ActiveRecord queries into customized methods using Ruby on Rails. Inside your models, you can define a scope as a new method that returns a lambda function for calling queries you're probably used to using inside your controllers.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With