How to simulate Java-like annotations in Ruby?

后端 未结 3 1046
太阳男子
太阳男子 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 15:06

    My requirement is

    On a page I display a list of all instance_methods for a Class ABC, and there should be a 1 line description too with every method

    Now I don' know if it is just me or storing the descriptions for all those methods with their names in a new table in the DB sounds "Super LAME"

    Answer is - "Annotations"

    Here's how I did it -

    1. The module Annotations given by cibercitizen1
    2. Code to include the module and activate the functionality in the desired class

    Class abc.rb

    class Abc
       extend Annotations
       create_annotation("_annotation")
    
     _annotation({:description=>"Info e-mail address"})
     def info_email
        APP_CONFIG['info_email']
     end
    
     _annotation({:description=>"Location of order"})
     def location
        unless self.order.blank?
          @location ||= self.order.location.description
        end
     end
    
    1. Code to display the given descriptions (only, not the method name) through the annotation attribute hash for the collection of instance_methods, in the view which has access to the class Abc.

    VIEW methods_list.html.erb

     
     
     
      
     <% default_description = "Description not specified" %>
      <% Abc.instance_methods.each do |method| %>
         
         <%= (Abc.annotations[method.to_sym].present?
         ?
         (Abc.annotations[method.to_sym][:_annotation][:description].blank?
         ? default_description :
         Abc.annotations[method.to_sym][:_annotation][:description])
         : default_description) %>
         
    
       <% end %> 
       
    
    

    Hope it helps!

提交回复
热议问题