2

関数に具体的に名前を付けて(モジュール全体ではなく)、モジュールからRubyのグローバル名前空間に関数を取り込むことは可能ですか?

元々モジュールを使用していなかったモジュールがあり、クラス/メソッドをモジュールに移動したいのですが、互換性のためにグローバルレベルですべてを持つモジュールを保持したいと考えています。これまでのところ、私はこれを持っています。

# graph.rb
require 'foo_graph'
include foo

# foo_graph.rb
module foo
    # contents of the old graph.rb
end

しかし、モジュールfooはまったく関係のないファイルでも使用されており、呼び出すと、include意図したよりも多くのものをグローバル名前空間に取り込むことができます。

プルしたい関数を指定する方法はありますincludeか、それとも私がやりたいことを行うための代替手段はありますか?

4

1 に答える 1

2

サブモジュールを使用します。

module Foo
  module Bar
    def bar_method; end
  end
  include Bar

  module Baz
    def baz_method; end
  end
  include Baz
end

# only include methods from Bar
include Foo::Bar

bar_method
#=> nil

baz_method
#=> NameError: undefined local variable or method `baz_method' for main:Object

include Foo

# include all methods from Foo and submodules
baz_method
#=> nil
于 2012-11-05T15:49:35.690 に答える