Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you alias a scope in Rails?

Tags:

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!

like image 920
msquitieri Avatar asked Aug 28 '15 22:08

msquitieri


People also ask

What is alias method in Rails?

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.

How does Scope work in Rails?

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.

What is Alias_method?

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 .

Why do we use scope in Rails?

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.


1 Answers

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 
like image 170
max Avatar answered Sep 19 '22 20:09

max