加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:42:11 所属栏目:百科 来源:网络整理
导读:如何在Ruby中模拟Java类注释? (我们有答案,概括一下 http://bens.me.uk/2009/java-style-annotations-in-ruby) 解决方法 这几个星期前改编自 a piece of code I wrote in an answer to another question,虽然它当然不是原创的.毕竟,这是众所周知的Ruby惯用
如何在Ruby中模拟Java类注释?

(我们有答案,概括一下
http://bens.me.uk/2009/java-style-annotations-in-ruby)

解决方法

这几个星期前改编自 a piece of code I wrote in an answer to another question,虽然它当然不是原创的.毕竟,这是众所周知的Ruby惯用语,多年来一直在使用,至少从耙子的描述法开始.
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

这里有一个小例子:

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

当然,没有一个testuite,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读