Question

I have a situation where I can access a module's functions from one file but not another. These files are both in the same directory. I'll try to recreate the code the best I can:

Directory Structure:

init.rb
lib/FileGenerator.rb
lib/AutoConfig.rb
lib/modules/helpers.rb

lib/AutoConfig.rb

#!/usr/bin/env ruby

require 'filegenerator'
require 'modules/helpers'

class AutoConfig
  include Helpers

  def initialize
  end

  def myFunction
    myhelper #here's the module function
  end

  def mySecondFunction
    FileGenerator.generatorFunction # call to the FileGenerator
  end
end

lib/FileGenerator.rb

#!/usr/bin/env ruby

require 'modules/helpers'

class FileGenerator
  include Helpers

  def initialize
  end

  def self.generatorFunction
    myhelper #here's the module function that doesn't work
  end
end

lib/modules/helper.rb

#!/usr/bin/env ruby

module Helpers
    def myhelper
      #Do Stuff
    end
end

The AutoConfig file is the main workhorse of the app. When it calls to the myhelper module function it gives me no problems what-so-ever. The AutoConfig part way through calls the FileGenerator.generatorFunction.

The FileGenerator.generatorFunction also contains this same module function, but for some reason when I run the program I get the following error:

filegenerator.rb:26:in `generatorFunction': undefined method `myhelper' for FileGenerator:Class (NoMethodError)

I've been at this now for several hours trying many different combinations and can't figure out where I'm going wrong. Any help would be appreciated.

Was it helpful?

Solution

generatorFunction is a class method. It doesn't see instance-level methods. And myhelper (brought in by include Helpers) is an instance method. To remedy that, you should extend Helpers instead. It works like include, but makes class methods.

class FileGenerator
  extend Helpers

end

BTW, the name generatorFunction is not in ruby style. You should name methods in snake_case (generator_function).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top