General Ruby Question

I installed the act_as_versioned plugin from github.com in my rails application, and there was a block of code that I do not quite understand, I was hoping someone could clear this

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

I understand that methods inside a block (or something else) are defined as instance methods within a class, but I cannot 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 here , and this code starts at line 199 lib / actions_as_versioned.rb. If someone gave me a low price here, I would be very obliged.

THX

-C

+5
source share
3 answers

heredoc. http://en.wikipedia.org/wiki/Heredoc#Ruby

CLASS_METHODS , , . < < - < <, .

heredocs Ruby ( heredocs , , - ):

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
+7

"here document" , inline. Ruby:

, . . , Ruby <<identifier <<quoted string, , . , , . <<, . , ; .

, class_eval CLASS_METHODS . CLASS_METHODS , - .

+6

They are equivalent:

class SomeClass
  class_eval <<-CLASS_METHODS
    def first_method
    end
    def second_method
    end
  CLASS_METHODS
end

class SomeClass
  def self.first_method
  end
  def self.second_method
  end
end
-2
source

All Articles