Ruby:如何实现' dry_run选项'?

时间:2014-03-20 09:57:02

标签: ruby design-patterns options

我有一个班级:

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

和可能的用法:

# 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}'
  }    
}

空跑只会输出logger.debug。任何人都可以解释如何实现这样的事情吗? Ruby有没有现成的解决方案?

1 个答案:

答案 0 :(得分:0)

嗯,在这种情况下,您需要做的就是复制数组的所有元素:

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

另一个选择是使用非modyfying sub代替sub!,但这有点难以理解:

   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