开发者

How do I make module methods available to a constant Proc variable? (Ruby)

This is in my application helper:

def call_me
 "blah"
end开发者_开发知识库

P = Proc.new { call_me }

def test_me
  P.call
end

If I then do this in my view:

<%= test_me %>

I get an error saying that call_me is an undefined method.

How do I get the Proc to be able to call call_me? require doesn't do it. Prefixing with ApplicationHelper::call_me doesn't either. :(

This works, but I really don't like it since test_me will be called lots of times and in reality there are many many more Procs:

def test_me
  p = Proc.new { call_me }
  p.call
end


It should work as is in Ruby 1.9.2, but in earlier versions you can pass your helper as an argument to the Proc:

P = Proc.new { |helper| helper.call_me }

def test_me
    P.call self
end

Since call_me is an instance method on your helper, you need to invoke it with an instance.


I think you were looking for this?

def call_me
    Proc.new
end

proc = call_me { "blah" }
proc.call   #=> "blah"


you have to pass call_me in. gets kind of convoluted...

p = Proc.new { |m| m.call }

def test_me
  p.call(call_me)
end

I'm not entirely sure what your aim here is in the larger sense so this is more or less a stab in the dark...


The most pragmatic way to do this is to make the module methods static, and then simply using them wherever you want:

module Sample::SillyModule
  def self.say_hello(my_cool_var)
    puts "Hello #{my_cool_var}!"
  end
end

proc do
  Sample::SillyModule.say_hello("stackoverflow")
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜