我已经用通常的方式定义了Sinatra助手:
module Sinatra
module FooHelper
# code goes here
end
end在我的帮助器中,除了其他东西之外,我还想向Numeric添加一个方法
module Sinatra
module FooHelper
class ::Numeric
def my_new_method
end
end
end
end但是,为了不引起注意,我只想在应用程序中包含Sinatra helper的情况下添加这个方法;如果没有人运行helpers Sinatra::FooHelper,我就不想影响任何东西(对于Sinatra扩展来说,这似乎是合理的)。
有没有任何钩子,当我的帮助器被包含在内时,它会触发,这样我就可以只在发生一次的时候添加我的方法?
发布于 2013-07-17 01:13:58
您可以使用Module#included方法来完成此操作。我认为您需要稍微修改您的类定义才能使用class_eval。我已经测试了以下内容,它的运行情况与预期一致:
module Sinatra
module FooHelper
def self.included(mod)
::Numeric.class_eval do
def my_new_method
return "whatever"
end
end
end
end
endhttps://stackoverflow.com/questions/17678504
复制相似问题