【问题标题】:Find which alias method is called in rails model查找在 rails 模型中调用了哪个别名方法
【发布时间】:2012-09-05 15:17:46
【问题描述】:

我是 Rails 开发的新手。我为一个方法创建了一些别名,我想知道调用了哪个别名。

我有这个代码。

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

我想知道用户调用了哪个别名。就像如果用户调用net_stock_quantity_equals 那么我应该知道用户调用了net_stock_quantity_equals 而不是net_stock_quantity

任何帮助将不胜感激。

【问题讨论】:

  • 您是该方法的别名——听起来更像是您实际上想要生成一个 real 方法并根据调用的方法执行某些操作。所有 alias_method 所做的就是给方法取别名。你正在尝试做一些不同的事情。
  • 如果您尝试动态过滤记录,您可能会发现“Ransack” gem 很有帮助。 github.com/ernie/ransack
  • 是的,我正在尝试最小化模型中的方法。我想在调用别名的基础上使用net_stock_quantity 中的 if 条件。这是更好的方法吗?如果是,那么告诉我我该怎么做,如果不是,那么告诉我替代和更好的方法。谢谢。
  • @BaylorRae' 我知道 Ransack,但我已经在使用 ernie/meta_search gem。
  • @KashifUmairLiaqat 那么你能在你的控制器中使用search 方法吗(或者你在哪里使用这些方法)?

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2 meta-search


【解决方案1】:

您可以覆盖 method_missing 来执行此操作。

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

这里有一个教程做类似的事情http://net.tutsplus.com/tutorials/ruby/ruby-for-newbies-missing-methods/

【讨论】:

  • 非常好的答案,我相信它也有效。但也有一个简单的解决方案。我将在此问题的新答案中编写该解决方案,因为代码无法在 cmets 中正确显示。
【解决方案2】:

它认为您错误地解决了问题-而不是使用别名方法,而是通过:equals, :gte, :lte 等作为方法的参数发送,即:

def net_stock_quantity(type = :all)
  # do something with the type here
end 

【讨论】:

  • Sachnir,如果您阅读 meta_search 文档,您会很清楚我们无法将这些参数(:equals,:gte,:lte)发送到自定义搜索方法,如果我们可以判断我怎么样?
【解决方案3】:
def net_stock_quantity(alias_used = :net_stock_quantity)
    method_called = caller[0]
    #some code
end

method_called 将包含被调用别名的名称。

【讨论】:

    猜你喜欢
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 2013-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多