Ruby-on-rails – Rails: I can’t call a function in a module in /lib – what am I doing wrong

rubyruby-on-rails

I have a module saved in /lib as test_functions.rb that looks like this

module TestFunctions
  def abc
    puts 123
  end
end

Going into ruby script/runner, I can see that the module is loading automatically (good ol' convention over configuration and all that…)

>> TestFunctions.instance_methods
=> ["abc"]

so the method is known, let's try calling it

>> TestFunctions.abc
NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):3

Nope. How about this?

>> TestFunctions::abc
NoMethodError: undefined method `abc' for TestFunctions:Module from (irb):4

Test
Nope again.

defined?(TestFunctions::abc) #=> nil, but
TestFunctions.method_defined? :abc #=> true

Like I said at the top, I know I'm being dumb, can anyone de-dumb me?

Best Answer

If you want Module-level functions, define them in any of these ways:

module Foo
  def self.method_one
  end

  def Foo.method_two
  end

  class << self
    def method_three
    end
  end
end

All of these ways will make the methods available as Foo.method_one or Foo::method_one etc

As other people have mentioned, instance methods in Modules are the methods which are available in places where you've included the Module

Related Topic