Find which alias method is called in rails model
-
30-06-2021 - |
Question
I am new to rails development. I have created some aliases to a method and I want to know that which alias is called.
I have this code.
alias_method :net_stock_quantity_equals :net_stock_quantity
alias_method :net_stock_quantity_gte :net_stock_quantity
alias_method :net_stock_quantity_lte :net_stock_quantity
alias_method :net_stock_quantity_gt :net_stock_quantity
alias_method :net_stock_quantity_lt :net_stock_quantity
def net_stock_quantity
#some code here
end
I want to know that user has called which alias. Like if user calls net_stock_quantity_equals
then I should know that the user has called net_stock_quantity_equals
not net_stock_quantity
.
Any help would be appreciated.
Solution 3
def net_stock_quantity(alias_used = :net_stock_quantity)
method_called = caller[0]
#some code
end
The method_called
will contain the name of called alias.
OTHER TIPS
You could override method_missing to do it.
def method_missing(method_name, *args, &block)
if method_name.to_s =~ /^net_stock_quantity_/
net_stock_quantity method_name
else
super
end
end
def net_stock_quantity(alias_used = :net_stock_quantity)
#some code
end
There's a tutorial here doing something similar http://net.tutsplus.com/tutorials/ruby/ruby-for-newbies-missing-methods/
It think you are approaching the problem incorrectly - instead of using alias methods, send through :equals, :gte, :lte
etc. as a parameter to the method ie:
def net_stock_quantity(type = :all)
# do something with the type here
end