Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias a class method in rails model?

I want to alias a class method on one of my Rails models.

  def self.sub_agent    id = SubAgentStatus.where(name: "active").first.id    where(type: "SubAgent",sub_agent_status_id: id).order(:first_name)       end 

If this was an instance method, I would simply use alias_method, but that doesn't work for class methods. How can I do this without duplicating the method?

like image 614
beck03076 Avatar asked Apr 27 '15 22:04

beck03076


People also ask

What is alias method in Ruby?

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.

What are class methods in Rails?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition.

What is a method in Ruby?

A method in Ruby is a set of expressions that returns a value. With methods, one can organize their code into subroutines that can be easily invoked from other areas of their program. Other languages sometimes refer to this as a function. A method may be defined as a part of a class or separately.


2 Answers

You can use:

class Foo      def instance_method           end       alias_method :alias_for_instance_method, :instance_method     def self.class_method    end       class <<self        alias_method :alias_for_class_method, :class_method    end    end   

OR Try:

self.singleton_class.send(:alias_method, :new_name, :original_name) 
like image 122
mohamed-ibrahim Avatar answered Oct 05 '22 20:10

mohamed-ibrahim


I can confirm that:

class <<self   alias_method :alias_for_class_method, :class_method end 

works perfectly even when it is inherited from a base class. Thanks!

like image 34
fuzzygroup Avatar answered Oct 05 '22 22:10

fuzzygroup