开发者

Ruby on Rails: is there a way to pass a method pointer to a function?

I'm trying to do this:

def assert_开发者_C百科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

but when I do the call:

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

I get an error that delete has no arguments... which makes sense, given that delete is a rails testing function.

So, is there a way to pass a pointer to the method as an argument instead of passing the method itself?


The easiest way is to use ruby blocks:

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

And then call your method:

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

You can also get the method object and pass it to your function:

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})

Using blocks is far more ruby-ish.


You might want to take a look at Object::send as an alternative.

Example code from the Ruby Docs:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜