使方法别名正常工作



我正在尝试从Ruby Commander Gem中"借用"一些代码。在自述文件中的示例中,它们显示了您在程序中放置的许多方法调用,如下所示:

require 'commander/import'
program :name, 'Foo Bar'

方法程序位于 Commander 模块 Runner 类中。如果您点击要求链接,您将进入以下模块:

module Commander
module Delegates
%w(
  add_command
  command
  program
  run!
  global_option
  alias_command
  default_command
  always_trace!
  never_trace!
).each do |meth|
  eval <<-END, binding, __FILE__, __LINE__
    def #{meth}(*args, &block)
      ::Commander::Runner.instance.#{meth}(*args, &block)
    end
  END
end
  def defined_commands(*args, &block)
    ::Commander::Runner.instance.commands(*args, &block)
  end
end
end

在 Commander 模块 Runner 类中,这是相关的代码:

def self.instance
  @singleton ||= new
end
def program(key, *args, &block)
  if key == :help && !args.empty?
    @program[:help] ||= {}
    @program[:help][args.first] = args.at(1)
  elsif key == :help_formatter && !args.empty?
    @program[key] = (@help_formatter_aliases[args.first] || args.first)
  elsif block
    @program[key] = block
  else
    unless args.empty?
      @program[key] = (args.count == 1 && args[0]) || args
    end
    @program[key]
  end
end

已将此代码复制到我自己的程序中,它似乎不起作用,因为我在程序上遇到找不到方法的错误。如果我将 Runner 实例化为运行器并调用 runner.program,它工作正常。

在我的版本中,它都在一个文件中,我有

module Repel
  class Runner
    # the same methods as above
  end
  module Delegates
    def program(*args, &block)
      ::Repel::Runner.instance.program(*args, &block)
    end
  end
end
module Anthematic
  include Repel
  include Repel::Delegates
  #runner = Runner.new
  #runner.program :name, 'Anthematic'
  program :name, 'Anthematic'
  ...
end

我得到的错误是:

:未定义的方法'程序' for Anthematic:Module (NoMethodError)

注释掉的代码在取消注释时有效。

我如何让代码工作,或者,有没有更好的方法?我不知道评估声明的其余部分发生了什么。我知道程序 def 中的参数数量已关闭。我对它们对齐的另一种方法也有同样的问题。

而不是

include Repel::Delegates

其中包括模块方法作为实例方法,您应该

extend Repel::Delegates

这将扩展类方法。

最新更新