Ruby annotations

In the programming world, an annotation is a way to mark the code that is below it for many purposes. In Cucumber, the tags it uses are a kind of annotation to apply callbacks and classify some features and scenarios:

@billing
Feature: Verify billing
 
  @important
  Scenario: Missing product description
 
  Scenario: Several products

In the case of VRaptor, we can use annotations to specify a controller as a REST resource or to restrict the access method to an action:

@Resource
public class ShoppingCartController {
    ...
}
 
public class ProductsController {
    @Post
    @Path("/products")
    public void add(Product product) {...}
    ...
}

In the Ruby language, two annotations that are very used are the methods protected and private, which without arguments restrict the visibility of the methods defined below them:

class User
  def jump; end;
 
  protected
  def eat; end;
  def flirt; end;
 
  private
  def sleep; end;
  def dream; end;
end

In some situations we may want to annotate our code like this, for example to specify that a method is deprecated, functionality that is offered by the gem Canivete from Douglas Campos:

class Bomb
  deprecate
  def explode; end
end

In the previous code, when somebody calls Bomp#explode, the interpreter will effectively execute the method, but also will output: Warning: calling deprecated method Bomb.explode.

The key to this behavior is the method_added method which is present in all Ruby modules and which is called every time a method is defined, receiving the name of the method as the parameter.

We can use this method, for example, to create an annotation that specifies that the methods declared below it can only be called by an admin, something like this:

class Module
  def method_added(name)
    unless @_admin_only.nil? or @_proxy_method
      @_proxy_method = true
      alias_method "_admin_#{name}", name
      module_eval <<-STRING
        def #{name}(*args, &block)
          _admin_#{name}(*args, &block) if admin?
        end
      STRING
      @_proxy_method = false
    end
  end
 
  def admin_only
    @_admin_only = true
  end
end
 
class User
  def admin?
    [true, false][rand(2)]
  end
 
  admin_only
 
  def update_password
    puts "password updated"
  end
 
  def restart_server
    puts "server restarted"
  end
end

In the previous code, #admin? will randonmly return true or false and depending of the result the called method will be executed or not.

15 thoughts on “Ruby annotations

  1. An interesting point is that the private and protected methods can also take a block, and it would be simple to add that functionality to your helper like so:

    
    def admin_only
      @_admin_only = true
      if block_given?
        yield
        @_admin_only = false
      end
    end
    

    you might also want to override the private and protected methods to set @_admin_only to false again, so that they can work better

    Lenary

  2. Youre so awesome, man! I cant believe I missed this blog for so long. Its just great stuff all round. Your design, man…too amazing! I cant wait to read what youve got next. I love everything that youre saying and want more, more, MORE! Keep this up, man! Its just too good.:)

  3. Seriosly, I’m a blog fan and with all of the blogs out there now, not all of them that has been posted stands out like yours does. Your blog caught my eye and I really like your ideas that you’ve benn shared with us..Thumbs up!

  4. Great post. One sugestion: I think .method_added(name) would be better moved to a module e.g. AdminOnly and super should be added into .method_added(name) somewhere. Then class User can be extended with AdminOnly without overhead (from extending Module directly) and without breaking any other magic already using .method_added.

    module AdminOnly
    def method_added(name)
    # …
    super
    end

    def admin_only
    @_admin_only = true
    end
    end

    class User
    extend AdminOnly

    # …
    end

  5. Thanks for your recommendations on this blog. One particular thing I would choose to say is always that purchasing gadgets items in the Internet is nothing new. The fact is, in the past several years alone, the market for online electronic products has grown noticeably. Today, you will find practically just about any electronic system and gizmo on the Internet, including cameras as well as camcorders to computer parts and games consoles.

  6. Wonderful work! This is the kind of info that are meant to be shared across the net. Shame on search engines for now not positioning this submit higher! Come on over and discuss with my web site . Thanks =)

  7. Wonderful items of your stuff, man. I’ve comprehend your own stuff before and you are too excellent. I like what you have acquired right here, definitely like what youíre stating and exactly how in which you say it. You make this enjoyable but you just take care of to keep this wise. We canít wait to read a lot more from you. This is really a terrific web site.I truly wanted to make a small remark to be able to convey appreciation for you for all the fantastic info you are discussing only at that website. Time intensive web research has at the conclusion been rewarded along with wonderful understanding to write about along with my friends. I’d point out that most of us readers are unequivocally rendered to stay in an excellent location along with lots of marvellous people with useful techniques. Personally i think truly fortunate to possess come across your entire web page and look toward really more enjoyable times reading through here. Thanks once again with regard to everything.

  8. I’ve observed that in the world the present moment, video games are the latest rage with children of all ages. There are times when it may be difficult to drag your children away from the activities. If you want the best of both worlds, there are several educational games for kids. Great post.

  9. Pingback: konstauktioner
  10. Hi there, I do think your site may be having browser compatibility problems.
    When I look at your website in Safari, it looks fine however, when opening in Internet Explorer, it’s got some
    overlapping issues. I just wanted to give you a quick heads up!
    Apart from that, fantastic website!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">