Reputation: 7
I'm trying to migrate my database in a ruby on rails app, and I'm a bit confused about the proper syntax shown below:
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.string :thumburl
t.timestamps
end
end
end
(1) Why is a symbol :Migration
being used at the class naming area? The way I'm reading it is that a class, CreateCategories
, is being created, and it inherits all attributes of the ActiveRecord
class. I was taught that the double colon signifies a class method call, yet the syntax coloring makes me think the :Migration
component is actually a symbol. What's going on here?
(2) I get that create_table
is a method, yet why use :categories
, i.e. a symbol, instead of a class or instance variable, i.e. @@categories
or @categories
? I suppose you have to name the table that's being created, but why a symbol?
(3) Why are :name
and :thumburl
symbols and not variables?
Upvotes: 0
Views: 91
Reputation: 1675
ActiveRecord::Migration
isn't a symbol, it's the name of the superclass being inherited from. ::
is the scope resolution operator, so Migration
is a member of the ActiveRecord
module.
As for why symbols are being used in various places, they're used in place of where you might otherwise use a String, such as giving the table a name. You could use 'categories' but as symbols are essentially just a pointer to an object, there's a certain amount of extra efficiency in terms of memory storage, as you don't have a new string being created everywhere that symbol is used.
To illustrate this idea, take the following script for example:
puts 'categories'.object_id
puts 'categories'.object_id
puts '---------------------'
puts :categories.object_id
puts :categories.object_id
Running of the script might produce something similar to this:
19608760
19608660
---------------------
839388
839388
The string versions have two different IDs, which means two separate String objects were created. The symbols version, however, prints the same ID, which means only a single object was created to represent the symbol, and the same object is used wherever the symbol is used.
Upvotes: 2
Reputation: 168071
(1) Your tokenization :Migration
is wrong. It should be understood as ::Migration
. The ::
is a scope resolution operator. It means Migration
as understood within the namespace of ActiveRecord
. You are right that ::
is used as a class method call. Actually, ::
has two uses: the scope resolution operator, and a class method call; it is ambiguous. Here, it is the former.
(2, 3) @@categories
or @categories
or any other variable will be evaluated to a certain value it holds. It would not mean anything like "category". In order to tell something like "category", expressing it as "category"
in a string, or :category
as in a symbol is the way to go.
Upvotes: 0