How to simulate Java-like annotations in Ruby?

后端 未结 3 1043
太阳男子
太阳男子 2020-12-05 14:37

How to simulate Java-like annotations in ruby?

(We\'ll I have the answer, generalizing http://bens.me.uk/2009/java-style-annotations-in-ruby)

3条回答
  •  隐瞒了意图╮
    2020-12-05 14:47

    This is the intended usage:

    First you annotate a class.

    class A
    
      extend Annotations
    
      extend MyAnnotations
    
      create_annotation("_foobar")
    
      _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
    

    Then you would like do inspect A's annoations like this:

    anots = A.annotations
    puts anots.keys
    
    puts anots[:m1][:_hello][:color]
    puts anots[:m3][:_foobar][:color]
    
    puts anots[:m1].key?(:_goodbye)
    
    puts "---------------"
    
    anots.each do |met| # each annotated method
      puts "-- annotated method --"
      puts met[0] # method name
      met[1].each do |a| # each annotation for the method
        puts "-> " + a[0].to_s # annotation name
        a[1].each do |par| # each pair: key-value
          puts " key=" +   par[0].to_s + " value=" + par[1].to_s
        end
      end
    end
    

    Well. To do that, you will need this module

    module Annotations
    
      @@annotation_list = {}
      @@pending = {}
    
      def method_added(met_sym)
        #puts "-> adding " + met_sym.to_s + " to class + self.to_s
        if @@pending.size > 0
          #puts met_sym.to_s + " is annotated "
          @@annotation_list[met_sym] = @@pending
          #puts @@annotation_list
        else
          #puts met_sym.to_s + " is not annotated "
        end
        @@pending = {}
      end
    
      def annotate_method(a,b)
        @@pending[a] = b
      end
    
      def create_annotation(anot_sym)
        code = "def  #{anot_sym.to_s}(val)
          annotate_method( :#{anot_sym} ,val)
          end"
        instance_eval code
      end
    
      def annotations
        return @@annotation_list
      end
    
    end
    

    and you can define a set of annotations in a module of yours:

    module MyAnnotations
    
      def _goodbye(val)
        annotate_method(:_goodbye, val)
      end
    
      def _hello(val)
        annotate_method(:_hello, val)
      end
    end
    

    or define them right into the class you are annotating:

    create_annotation("_foobar")
    

提交回复
热议问题