如何在守护进程中添加方法/模块访问控制?

时间:2012-01-10 11:22:04

标签: ruby daemons

我想在Ruby脚本中禁用rm\_rf模块的FileUtils方法。

foo.rb包含:

FileUtils.rm_rf(file)

它不应该由:

运行
Daemons.run("foo.rb", some_options)

并且应该给出错误消息。

Daemons能做到吗?或者其他一些图书馆可以简单有效地完成这项工作吗?

1 个答案:

答案 0 :(得分:2)

以下是您想要做的大致概述。

除非您将旧方法定义为其他内容,否则使用alias_method可能不是一个好主意;这里定义了方法。这种方法的危险在于内部行为可能以预期的方式受到影响,例如,允许的方法在内部使用不允许的方法。

以下是单例(类)方法,相同的逻辑可用于实例方法。有几种方法可以实现,这只是一个,作为指南。

> FileUtils.pwd
=> "/home/dave"
> FileUtils.cp '.bashrc', 'tmpbashrc'
=> nil
> class Object
*   def deimplement_singleton_methods *methods
*     methods.each do |msym|
*       define_singleton_method msym do |*args|
*         raise NotImplementedError.new "#{msym} not implemented"
*       end
*     end
*   end
* end
> FileUtils.deimplement_singleton_methods :cp
> FileUtils.pwd
=> "/home/dave"
> FileUtils.cp '.bashrc', 'tmpbashrc'
NotImplementedError: cp not implemented
from (pry):10:in `block (2 levels) in deimplement_singleton_methods'

还有Module::undef_methodModule::remove_method,它们可能会也可能不会提供您想要的行为(不确定您需要它做什么)。