Symbol pointing to a method idiom in ror model

IN NEED OF EXPLANATION:

class Comment < ActiveRecord::Base
validate :must_be_friends

def must_be_friends
  errors.add_to_base("Must be friends to leave a comment")
             unless commenter.friend_of?(commentee)
end

end

The above code comes from rails documentation. There is a similar
example inAgile Web D. with Rails by Dave T. and Sam Ruby.

my understanding is that:
validate :must_be_friends
is a method call to the validate method within the ActiveRecord::Base
class. Supposedly it’s contents are:
def validate
end

This of course does not work with ruby because the validate method does
not take parameters.

Is metaporgramming being used? Tnis seems like some sort of Rails
idiom.

Please explain.

I’m trying to get back into Rails after my first attempt.

TIA,
Pete

It’s a stub of sorts. When you use “validate :some_symbol” in your
model, it’s basically adding that symbol to a stack that it’s going to
invoke “model_instance.send(:some_symbol)” (more or less) on when
validation happens.

On Jan 22, 3:28 pm, Hiro P. [email protected] wrote:

This of course does not work with ruby because the validate method does
not take parameters.

Is metaporgramming being used? Tnis seems like some sort of Rails
idiom.

Not really: there are two validate methods. One is an instance method
that takes no arguments, the other is a class method that takes a
method name or block and adds it to the list of validations to run
(this is slightly hidden by the fact that that method comes from the
ActiveSupport callback stuff)

Fred

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs