0

あるファイルからはモジュールの関数にアクセスできるが、別のファイルからはアクセスできないという状況があります。これらのファイルは両方とも同じディレクトリにあります。できる限りコードを再作成してみます。

ディレクトリ構造:

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

AutoConfig ファイルは、アプリの主力です。モジュール関数を呼び出すと、myhelper何の問題もありません。AutoConfig は途中で を呼び出しますFileGenerator.generatorFunction

FileGenerator.generatorFunctionも同じモジュール関数が含まれていますが、何らかの理由でプログラムを実行すると次のエラーが発生します。

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

私はこれで数時間、さまざまな組み合わせを試してみましたが、どこが間違っているのかわかりません。どんな助けでも大歓迎です。

4

1 に答える 1

3

generatorFunctionクラスメソッドです。インスタンス レベルのメソッドは表示されません。そしてmyhelper(によって持ち込まれたinclude Helpers)はインスタンスメソッドです。それを解決するには、extend Helpers代わりにすべきです。のように動作includeしますが、クラス メソッドを作成します。

class FileGenerator
  extend Helpers

end

ところで、名前generatorFunctionはルビースタイルではありません。snake_case ( generator_function) でメソッドに名前を付ける必要があります。

于 2013-06-07T23:45:17.303 に答える