如何在Ruby中模拟类似Java的注释?

cib*_*en1 20 ruby annotations

如何在ruby中模拟类似Java的注释?

(我们将得到答案,概括 http://bens.me.uk/2009/java-style-annotations-in-ruby)

Jör*_*tag 30

这是根据几周前在另一个问题的答案中写的一段代码改编的,虽然它当然不是原创的.这一个众所周知的成语红宝石,毕竟,它已经使用了很多年,因为至少rakesdesc方法.

module Annotations
  def annotations(meth=nil)
    return @__annotations__[meth] if meth
    @__annotations__
  end

  private

  def method_added(m)
    (@__annotations__ ||= {})[m] = @__last_annotation__ if @__last_annotation__
    @__last_annotation__ = nil
    super
  end

  def method_missing(meth, *args)
    return super unless /\A_/ =~ meth
    @__last_annotation__ ||= {}
    @__last_annotation__[meth[1..-1].to_sym] = args.size == 1 ? args.first : args
  end
end

class Module
  private

  def annotate!
    extend Annotations
  end
end
Run Code Online (Sandbox Code Playgroud)

这是一个小例子:

class A
  annotate!

  _hello   color: 'red',   ancho:   23
  _goodbye color: 'green', alto:  -123
  _foobar  color: 'blew'
  def m1; end

  def m2; end

  _foobar  color: 'cyan'
  def m3; end
end
Run Code Online (Sandbox Code Playgroud)

如果没有测试套件,当然没有Ruby代码是完整的:

require 'test/unit'
class TestAnnotations < Test::Unit::TestCase
  def test_that_m1_is_annotated_with_hello_and_has_value_red
    assert_equal 'red', A.annotations(:m1)[:hello][:color]
  end
  def test_that_m3_is_annotated_with_foobar_and_has_value_cyan
    assert_equal 'cyan', A.annotations[:m3][:foobar][:color]
  end
  def test_that_m1_is_annotated_with_goodbye
    assert A.annotations[:m1][:goodbye]
  end
  def test_that_all_annotations_are_there
    annotations = {
      m1: {
        hello:   { color: 'red',   ancho:   23 },
        goodbye: { color: 'green', alto:  -123 },
        foobar:  { color: 'blew'               }
      },
      m3: {
        foobar:  { color: 'cyan'               }
      }
    }
    assert_equal annotations, A.annotations
  end
end
Run Code Online (Sandbox Code Playgroud)

  • @jwill:Sun花了8年时间为Java添加注释,它们只能由Sun添加,而不是由其他任何人添加.我花了大约10分钟和23行代码为Ruby添加注释,任何人都可以这样做,你不必依赖语言设计师.我觉得这很酷.如果你想说服我,尝试在不到30行的Java中实现注释. (2认同)