Home > front end >  Ruby: How to reference a variable defined outside of a module
Ruby: How to reference a variable defined outside of a module

Time:01-21

How do I pass processor_pool to the method inside the module?

class Dummy

  def initialize
    processor_pool = Concurrent::FixedThreadPool.new(10)

    @threadpool = Module.new do
      extend Concurrent::Promises::FactoryMethods
      def self.default_executor
        return processor_pool  # this cannot find the processor_pool variable
      end
    end
  end

end

I get the same error even if I make it an instance variable like @processor_pool

CodePudding user response:

Something like this (I simplified your class a bit to get rid of dependencies for the sake of example, but its structure is the same):

class Dummy
  attr_reader :threadpool
  
  def initialize
    processor_pool = "It works"

    @threadpool = Module.new do
      define_method :default_executor do
        return processor_pool  # this cannot find the processor_pool variable
      end
      module_function :default_executor
    end
  end
end

Dummy.new.threadpool.default_executor # => "It works"
  •  Tags:  
  • Related