使用代码包围Ruby方法

Jor*_*rdi 1 ruby refactoring

我有很多像这样的方法:

def enableMotors
  @posIface.Lock 1
  @posIface.data.cmdEnableMotors = 1
  @posIface.Unlock
end

def goTo (pos)
  @posIface.Lock 1
  @posIface.data.cmdVelocity.pos = pos
  @posIface.Unlock
end
Run Code Online (Sandbox Code Playgroud)

我想创建以下功能:before_filter和:after_filter或任何其他方式我可以将此代码保持为DRY尽可能.我不想仅仅依靠Rails或其他重要的东西.

Sim*_*tti 6

你真的需要一个完整的:之前:回调系统之后还是这个对你来说足够了?

def with_lock(&block)
  @posIface.Lock 1
  yield
  @posIface.Unlock
end

def enableMotors
  with_lock { @posIface.data.cmdEnableMotors = 1 }
end

def goTo (pos)
  with_lock { @posIface.data.cmdVelocity.pos = pos }
end
Run Code Online (Sandbox Code Playgroud)