【问题标题】:YARD ⇒ how to add custom output to several methods descriptions basing on one DSL statement in YARD pluginYARD ⇒ 如何根据 YARD 插件中的一个 DSL 语句将自定义输出添加到几个方法描述中
【发布时间】:2013-03-11 11:03:55
【问题描述】:

我在为以下 DSL 编写 YARD 插件时遇到问题:

class MyClass
  my_dsl :do_it, :do_other
  def do_it
    # do it
  end
  def do_other
    # do other
  end
  def do_unrelated
    # do unrelated
  end
end

现在我想在这些方法的文档 sn-ps 中添加注释,它们受到 DSL my_dsl 的“影响”。在my_dsl 处理程序中,范围完全不同(我不想添加一些新文档,我想扩展现有的方法。)

所以我决定在MyDSLHandler#process 中使用Proxy 代码对象来标记延迟未来后处理所需的方法(这将发生在def do_it ; … ; end 上的内置MethodHandler 中。)它看起来像:

class MyDSLHandler < YARD::Handlers::Ruby::DSLHandler
  handles method_call(:my_dsl)
  namespace_only

  def process
    statement.parameters.each { |astnode|
      mthd = astnode.jump(:string_content).source if astnode.respond_to? :jump
      obj = YARD::CodeObjects::Proxy.new(namespace, "\##{mthd}", :method)
      register(obj)
      obj[:my_dsl_params] << {
        name: mthd,
        file: statement.file, line: statement.line # I need this!
      }
    }
  end
end

现在的问题是Proxy 对象是从普通的Object 派生的,而不是从YARD::CodeObjects::Base 派生的,因此没有定义[]= 方法:

[warn]: Load Order / Name Resolution Problem on MyClass#do_it:
[warn]: -
[warn]: Something is trying to call [] on object MyClass#do_it before it has been recognized.
[warn]: This error usually means that you need to modify the order in which you parse files
[warn]: so that MyClass#do_it is parsed before methods or other objects attempt to access it.
[warn]: -
[warn]: YARD will recover from this error and continue to parse but you *may* have problems
[warn]: with your generated documentation. You should probably fix this.
[warn]: -
[error]: Unhandled exception in Yard::Handlers::MyDSLHandler:
[error]:   in `example_mydsl.rb`:5:

    5: my_dsl :do_it, :do_other

[error]: ProxyMethodError: Proxy cannot call method #[] on object 'MyClass#do_it'

我应该如何将当前上下文中的一些值存储到 Proxy 对象,以便在对象实际实例化期间可用?

【问题讨论】:

    标签: ruby yard


    【解决方案1】:

    好吧,我能够解决它。

    这里不应该使用ProxyCodeObjects 有一个非常特殊的地方:它们是“沉默的”单身人士。因此,当您通过CodeObject.new 定义了一个对象时,所有即将对同一对象(根据Registry)对new 的调用都将重新映射到现有对象。

    因此,就我而言,我只是创建了MethodObject

    m = "#{astnode.jump(:string_content).source[1..-1]}";
    obj = YARD::CodeObjects::MethodObject.new(namespace, "#{m}")
    

    然后我在新创建的对象上做我想做的事:

    obj.my_dsl_params = { :win => true, :mthd => "#{m}", … }
    

    方法定义解析中的对象将merge这些属性与它自己的。唯一需要的就是要么用register(obj)注册一个对象,要么从process方法返回它进行系统注册。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 2011-11-26
      • 2012-02-10
      • 2017-10-17
      • 2012-02-21
      • 1970-01-01
      相关资源
      最近更新 更多