Rn2dy
Rn2dy

Reputation: 4190

Need explanation of some Ruby syntax

I am new to ruby on rails, could anybody explain what does the symbol ':' mean, what would be 'validates' and 'create_table'? So much confused...

class Post < ActiveRecord::Base
   validates :name, :presence => true
   validates :title, :presence => true, :length => {:minimum => 5}
end

class CreatePosts < ActiveRecord::Migration
   def change
     create_table :posts do |t|
       t.string :name
       t.string :title
       t.text :content
       t.timestamps
     end
    end
 end

Upvotes: 1

Views: 310

Answers (8)

rubyprince
rubyprince

Reputation: 17793

Apart from the symbols, the point to be noted here is that in Ruby, we dont have to implicitly give {} to specify that an argument is a hash if it is the last argument. I mean by calling

validates :name, :presence => true

you are calling

validates :name, {:presence => true}

or

validates(:name, {:presence => true})

then it becomes clear that you are calling a method validates with 2 arguments, a symbol and a hash. If we ignore the symbol and substitute strings in place, like this:

validates("name", {"presence" => true})

it is pretty much similar to a method call in any other language. So, watchout for this as it is used almost in every helper tags Rails use.

For the other methods also you can see this:

validates(:title, {:presence => true, :length => {:minimum => 5}})

In the case of create_table, it is a method call with 2 arguments, a symbol and a block.

Upvotes: 0

ghoppe
ghoppe

Reputation: 21784

Ruby Documentation and Ruby on Rails Documentation:

"what does the symbol : mean?" Class:Symbol

Symbol objects represent names and some strings inside the Ruby interpreter. They are generated using the :name and :"string" literals syntax, and by the various to_sym methods. The same Symbol object will be created for a given name or string for the duration of a program‘s execution, regardless of the context or meaning of that name. Thus if Fred is a constant in one context, a method in another, and a class in a third, the Symbol :Fred will be the same object in all three contexts.

"what would be validates?" ActiveModel::Validations::ClassMethods

This method is a shortcut to all default validators and any custom validator classes ending in ‘Validator’. Note that Rails default validators can be overridden inside specific classes by creating custom validator classes in their place such as PresenceValidator.

"what would be create_table?" ActiveRecord::ConnectionAdapters::SchemaStatements

Creates a new table

(The link shows examples, showing SQL statements generated by this method.)

Upvotes: 1

Sufendy
Sufendy

Reputation: 1242

as everybody is saying, : is a start of a symbol. Symbol is simple a string or variable name for me. In your example, :name is a variable/symbol that reflect one of the field name in Post table. Rails automatically creates these symbols when you create a Model class.

In Ruby, you can call a method/function and specify their parameters with/without the brackets. So,

validates :name, :presence => true

can be written as

validates(:name, :presence => true)

So, you are actually passing the :name and the true as the parameters for validates method

hope this help you see clearer about the methods calling in Ruby.

Same as validates, create_table is also a method.

Upvotes: 0

maerics
maerics

Reputation: 156384

  1. The colon character (:) is the beginning of a syntax literal for a Ruby "Symbol":

    :abc.class # => Symbol
    "abc".to_sym # => :abc

    Symbols are like strings but they are "interned", meaning the Ruby interpreter only has a single copy of it in memory despite multiple possible references (whereas there can be many equivalent strings in memory at once).

  2. The 'validates' token in your example above is a class method (of something in the class hierarchy of the "Post class") that is being called with a symbol argument (:name) and a hash argument with a single key/value pair of :presence => true.

  3. The 'create_table' token is a method which is being called with a single argument (the symbol ":posts") and is given a block which takes a single argument "t" (do |t| ... end).

Upvotes: 6

Jim Deville
Jim Deville

Reputation: 10662

:foo is a "symbol" which is essentially an immutable string. It's major advantage is the fact that it doesn't allocate a new object every time you use it. If you were to use the string "name" every time you needed to use it, you would be making a new String object every time. However, if you use :name instead, you are using the same Symbol object every time (same in terms of pointer equality and object identity).

validates and create_table are both methods. In ruby, a method doesn't need parenthesis when called, so validates :foo is the same as validates(:foo). The methods come via inheritance and module mixins. validates is a class method put onto ActiveRecord objects during the inheritance, and create_table is a instance method

Upvotes: 1

Adam Albrecht
Adam Albrecht

Reputation: 6870

In Ruby, the : means that it is a Symbol. A Symbol is sort of like a lightweight string that's specifically used as an identifier. For example, in a hash, you use symbols as keys that point to their respective values.

my_hash = {:key_1 => "A", :key_2 => "B"}

In your examples above, you use symbols to specify the properties of your Post model and the columns of your posts table.

Here are a few links for further reading on Ruby symbols:

Upvotes: 1

Venkat Raghavan G
Venkat Raghavan G

Reputation: 33

@Grimm

As you should know, everything is object on RoR. There are cases where you need to differentiate String from others as the memory handling techniques of String are different from other data structures. Colon : is a form of consideration of such type. They're just symbols like the one that makes hash entry on the memory!
Get used to that, it'll be interesting!! :)

Upvotes: 0

elder_george
elder_george

Reputation: 7879

:foo is a symbol, i.e. a constant string that is guaranteed to be unique. They are often used in Ruby to reference fields or methods.

validates is used in ActiveRecord to set a constraint on field's values.

validates :name, :presence => true means that field name must be always set (not null, undefined or empty) for all instances of Post (and corresponding table in DB). validates :title, :presence => true, :length => {:minimum => 5} means that field title must be always set and its length must be greater than 5.

Upvotes: 1

Related Questions