Ruby on rails RubyonRails:有没有一种方法可以将方法指针传递给函数?
我正在尝试这样做:Ruby on rails RubyonRails:有没有一种方法可以将方法指针传递给函数?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我正在尝试这样做: 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_f
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})
我得到一个错误,删除没有参数。。。这是有道理的,因为delete是一个rails测试函数
那么,有没有一种方法可以将指向方法的指针作为参数传递,而不是传递方法本身?最简单的方法是使用ruby块:
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。最简单的方法是使用ruby块:
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风格。您可能想作为一种替代方法来看看 Ruby文档中的示例代码:
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
你可能想看看,作为一个替代方案 Ruby文档中的示例代码:
class Klass
def hello(*args)
"Hello " + args.join(' ')
end
end
k = Klass.new
k.send :hello, "gentle", "readers" #=> "Hello gentle readers"
但是如何调用def assert_record_not_foundobject、action、params和block?编辑的帖子包含答案。但是如何调用def assert_record_not_foundobject、action、params和block?编辑的帖子包含答案。