Search code examples
ruby-on-railsrubyacts-as-versioned

General question about Ruby


I have installed the acts_as_versioned plugin from github.com in my rails application, and there was a block of code that I don't fully understand, I was hoping someone could clear this up for me

class_eval <<-CLASS_METHODS
  def a_bunch_of_stuff
   ....
  end
CLASS_METHODS

I get that the methods inside the block (or whatever it is) gets defined as instance methods inside the class, but I can't find CLASS_METHODS defined as a constant anywhere in the plugin, and I'm also not sure what <<- after class_eval means. the plugin is located here, and the code in question starts on line 199 of lib/acts_as_versioned.rb. If someone would give me the lowdown here, I would be much-obliged.

thx

-C


Solution

  • It's a heredoc. http://en.wikipedia.org/wiki/Heredoc#Ruby

    The matched CLASS_METHODS tokens are essentially starting and ending quotes. If you use <<- instead of <<, the ending token can be indented with whitespace.

    You can use multiple heredocs at once in Ruby (I made my heredocs the same as the argument names, but that's just for aesthetic - it makes no difference):

    def define_with_description description, code
      puts "defining a method to #{description}"
      class_eval code
    end
    
    define_with_description <<-DESCRIPTION, <<-CODE
      set up us the bomb
    DESCRIPTION
      Bomb.new.set_up(us)
    CODE