0

I am trying to write a Ruby Gem which, when required, adds a function to the global scope.

I have followed the ideas here: How can I add a method to the global scope in Ruby?, however, it just doesn't work! (on Ruby 2.4.3 anyway)

Here is my actual source code, but the below also summarises what I've done and what isn't working:

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

Then

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

Where did I go wrong?

Convincible
  • 314
  • 2
  • 10
  • 1
    Drop the `self.` – Sergio Tulentsev Dec 20 '18 at 20:33
  • Thanks!!! Can you clarify why, as this differs from the accepted answer in the other thread? This stumped me as removing `self.` causes every RSpec test to fail - but when I rebuilt the gem anyway, it works. – Convincible Dec 20 '18 at 20:39
  • Another thing to drop is the brackets. Ruby omits these by convention to make the syntax cleaner: `def hello` and later calling it as just `hello` is the style to use. – tadman Dec 20 '18 at 22:00

1 Answers1

0

Sergio solved this for me, though I don't quite understand how!

It was considered good practice to encapsulate the methods in a module, so that users of the gem can use them directly (hello) or scoped (Example::hello) as they pleased.

By removing self. the method can be accessed directly only. By including self. it doesn't work at all. However, by doing:

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

...it does work in both ways.

Convincible
  • 314
  • 2
  • 10
  • 1
    Should be `extend self`. And no, this code doesn't work :) `hello` won't be available at top level – Sergio Tulentsev Dec 20 '18 at 21:23
  • 1
    That's how `extend` works. You give it a module and it adds module's instance methods to current object methods. This is why this code won't work. `Example` doesn't have any [non-built-in] instance methods. Again. solution is to omit `self.` – Sergio Tulentsev Dec 20 '18 at 21:23
  • Thanks Sergio, whoops, typo fixed! Please can you vote back up. I am new to the site and only trying my best to participate but I am really getting kicked here. Thanks for your help. – Convincible Dec 22 '18 at 06:11