Dasmowenator
Dasmowenator

Reputation: 5428

Ruby: How to reference a variable defined outside of a module

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

Upvotes: 2

Views: 121

Answers (1)

Konstantin Strukov
Konstantin Strukov

Reputation: 3019

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
      end
      module_function :default_executor
    end
  end
end

Dummy.new.threadpool.default_executor # => "It works"

Upvotes: 3

Related Questions