Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

basic rails question

  class Person < ActiveRecord::Base
    validates_uniqueness_of :user_name, :scope => :account_id
  end

my question is about the above three lines of code. by the way I'm c++ programmer and new to ruby and rails. I'm very very confused by the line: validates_... what's that? variable definition? function call? or something eles. For me, it's a weird line whithin a class definition.

like image 605
Haiyuan Zhang Avatar asked May 06 '26 13:05

Haiyuan Zhang


1 Answers

It's a function call.

The function is defined in module (ActiveRecord::Validations). Modules in Ruby are objects and can have functions and variables attached to them.

You can include module and get it's members. Here it's done in your parent class: ActiveRecord::Base. If You look at it's definition it starts with something like:

module ActiveRecord
  class Base
    include ActiveRecord::Naming
    # ...
    include ActiveRecord::Validations
    #...
  end
end

There are some noticeable differences in way C++ and Ruby handles class declaration. Firstly, there is no compilation in Ruby. So class definition can be changed during runtime. And actually it's the default way of declaring a class. In other words: classes in Ruby are always open.

Secondly, class body can have any executable code. In C++ you can't invoke a function from class definition. It wouldn't make much sense. Yet in Ruby it makes, since You are able to do metaprogramming. This way you can invoke a function which constructs some members. That's writing functions which can write another functions. It can be a big productivity boost and a source of worst errors at the same time.

I'd highly recommend consulting the Ruby Metaprogramming: Declaratively Adding Methods to a Class entry.

like image 99
Rekin Avatar answered May 09 '26 02:05

Rekin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!