2011-07-18 57 views
1

我试图做到这一点:Ruby on Rails:有没有办法将一个方法指针传递给一个函数?

def assert_record_not_found(method, object, action, params) 
    begin 
    method action, params 
    object.find_by_id(p.id).should_not be_nil 
    rescue ActiveRecord::RecordNotFound 
    assert true 
    end 
end 

但是当我做呼叫:

assert_record_not_found(delete, MyObject, :destroy, {:id => o.id}) 

我得到的删除没有参数这是有道理的错误...,因为删除是一个轨道测试功能。

那么,有没有办法将指针传递给方法作为参数,而不是传递方法本身?

回答

4

最简单的方法是使用红宝石块:

def assert_record_not_found(object, action, params, &block) 
    begin 
    block.call action, params 
    object.find_by_id(p.id).should_not be_nil 
    rescue ActiveRecord::RecordNotFound 
    assert true 
    end 
end 

然后调用你的方法:

assert_record_not_found(MyObject, :destroy, {:id => o.id}) do |action, params| 
    delete action, params 
end 

您还可以得到该方法的对象,并把它传递给你的函数:

def assert_record_not_found(method, object, action, params, &block) 
    begin 
    method.call action, params 
    object.find_by_id(p.id).should_not be_nil 
    rescue ActiveRecord::RecordNotFound 
    assert true 
    end 
end 

delete = method(:delete) 
assert_record_not_found(delete, MyObject, :destroy, {:id => o.id}) 

使用块是非常ruby-ish。

+0

但如何调用高清assert_record_not_found(对象,操作,参数,可以与块) ? – NullVoxPopuli

+0

编辑帖子以包含答案。 – Yossi

0

您可能想看看Object::send作为替代。从Ruby的文档

示例代码:

class Klass 
def hello(*args) 
    "Hello " + args.join(' ') 
end 
end 
k = Klass.new 
k.send :hello, "gentle", "readers" #=> "Hello gentle readers" 
相关问题