1

你好

我尝试构建一些动态定义的方法并链接一些范围方法,例如:

define_method "#{instance_name_method}" do
        Kernel.const_get(model_name).___some_chaining methods basd on condition
end

一个想法是这样的:

method_action = model_name #ex Post

['latest', 'old', 'deleted','latest_deleted','archived'].each do |prefix| 

  method_action << ".deleted"  if prefix.match('deleted') 
  method_action << ".latest"  if prefix.match('latest')
  method_action << ".old"  if prefix.match('old')

  define_method "#{prefix}_#{instance_name_method}" do
           eval( method_action)
    end


end

在帖子中,我们有最新的、旧的...

现在我们可以调用如下方法:

Post.latest or Post.old_archived etc...

我的问题是:

  1. 有没有更好的方法来做到这一点?(类似于活动记录查找但没有method_missing)这有点难看......

  2. 如何动态链接方法?

我已经知道 send('method',var) 但我不知道如何根据条件从字符串中加入这些方法......

谢谢

4

1 回答 1

0

很抱歉,但我很难准确理解你在问什么。而且我不确定您是否正确使用了某些术语,例如“范围方法”是什么意思?您是说类方法还是实例方法?这与范围有关。

当您说链时,您是指一个接一个地调用一个方法吗?像这样?

f = Foo.new
puts f.method1(some_value).method2(some_other_value)

我只想评论一下,你上面不那么动态的部分可以写成:

method_action << ".#{prefix}"

我在您的问题中没有看到任何实际的链接,所以我不确定您是否只是想连接字符串以动态构建名称。如果您确实打算链接方法,则需要记住,您需要始终在要使可链接回该类的方法结束时返回 self 。

例如:

class Foo

  def method1(value)
    puts "method1 called with #{value}"
    self
  end

  def method2(value)
    puts "method2 called with #{value}"
    self
  end

end

f = Foo.new
puts f.method1("Hello").method2("World").method1("I can").method2("do this").method2("all").method1("day!")

会输出:

method1 called with Hello
method2 called with World
method1 called with I can
method2 called with do this
method2 called with all
method1 called with day!
#<Foo:0x0000010084de50>
于 2010-12-09T05:49:54.797 回答