1

I have a class:

class MyExecutor
  @@dry_run = false
  @@shared_instance = nil

  def self.shared_instance
      @@shared_instance ||= setup_new_instance()
  end

  # setup
  def self.setup_new_instance (dry_run = false)
    @@dry_run = dry_run
    new
  end

  # execution

  def self.exec_block(block)
    if (@@dry_run)
      # dry run, only output
    else
      # we-e-e-t, run all code here
    end
  end
end

and possible usage:

# here we want perform action
array.each { |elem|
  elem.sub!(/one/,'two')
  logger.debug "element now: #{elem}"
}

# here we do dry_run if needed
MyExecutor.exec_block {
  array.each { |elem|
    elem.sub!(/one/,'two')
    logger.debug 'element now: #{elem}'
  }    
}

Dry run will only output logger.debug. Could anybody explain how to implement such thing? Does Ruby have ready-solution?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
gaussblurinc
  • 3,642
  • 9
  • 35
  • 64

1 Answers1

0

Well, in this case all you need to do is to duplicate all the elements of your array:

def perform(array, dry = false)
  array.each do |elem|
    elem = elem.dup if dry
    elem.sub!(/one/,'two')
    logger.debug 'element now: #{elem}'
  end
end

Another option would be to use non-modyfying sub in place of sub!, but this would be a little harder to read:

   def perform(array, dry = false)
     method = dry ? :sub : :sub!
     array.each do |elem|
       result = elem.send(method, /one/,'two')
       logger.debug 'element now: #{result}'
     end
end
BroiSatse
  • 44,031
  • 8
  • 61
  • 86