Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 993
Chris Drappier Avatar asked Mar 03 '09 02:03

Chris Drappier


People also ask

Why use Ruby?

Ruby is mainly used to build web applications and is useful for other programming projects. It is widely used for building servers and data processing, web scraping, and crawling. The leading framework used to run Ruby is Ruby on Rails, although that's not the only one.


1 Answers

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
like image 166
ben_h Avatar answered Oct 01 '22 22:10

ben_h