Ruby gem不会使用扩展将方法添加到全局范围

时间:2018-12-20 20:26:17

标签: ruby-on-rails ruby

我正在尝试编写一个Ruby Gem,当require d时,它将一个函数添加到全局范围。

我遵循了这里的想法: How can I add a method to the global scope in Ruby?,但是,它根本不起作用! (无论如何,在Ruby 2.4.3上)

这是我的actual source code,但以下内容也总结了我已完成的工作和无效的工作:

# example.rb
module Example
    def self.hello()
        puts "Hello"
    end
end
extend Example

然后

# app.rb
require 'example' # Having built as a gem
hello() #=> `<main>': undefined method `hello' for main:Object (NoMethodError)

我哪里出错了?

1 个答案:

答案 0 :(得分:0)

塞尔吉奥为我解决了这个问题,尽管我不太了解如何!

将方法封装在模块中被认为是一种好习惯,这样gem的用户可以根据需要直接使用它们(hello或使用范围(Example::hello)。

通过删除self.,该方法只能直接访问。通过包含self.根本不起作用。但是,可以这样做:

module Example
    extend self
    def hello
        puts "Hello"
    end
end
extend Example

...它确实有两种工作方式。