Question

i've got a class like this one below. I introduced the loghelper-function to create the necessary logging-elements.

All 3 functions (start, function1, function2) can be run via console with rails r "Foo.start seperately

I'm looking for an elegant solution to make sure @logger is created before executing any of the other three functions and is only created once.

class Foo
  def self.loghelper
    @logger = Logger.new(stdout)
  end

  def self.start
    self.loghelper
    self.function1
    self.function2
  end

  def self.function1
    self.loghelper
    @logger.info 'function1 foo'
  end

  def self.start
    self.loghelper
    @logger.info 'function2 bar'
  end
end
Was it helpful?

Solution

that's why you encapsulate instance variables

class Foo
  def self.logger
    @logger ||= begin
      [...]
      Logger.new(stdout)
    end
  end

  def self.start
    function1
    function2
  end

  def self.function1
    logger.info 'function1 foo'
  end

  def self.start
    logger.info 'function2 bar'
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top