What does this Ruby code means?
The command
rails generate scaffold Post name:string title:string content:text
generated the following 20101109001203_create_posts.rb
file:
class CreatePosts < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :name
t.string :title
t.text :content
t.timestamps
end
end
def self.开发者_如何学Cdown
drop_table :posts
end
end
Since I'm new to Ruby (just read one book), I have some questions on this block of code:
What does
self.
means inself.up
andself.down
? How it differs from simplyup
anddown
?What does all these colons (
:
) means in:posts
,:name
, etc. ? Is that just a part of the variable name ?What does
t.string :name
means ? Is that a call tostring
function on objectt
with parameter:name
?
Thanks a lot!!
If you define a method using
def foo
, you're creating an instance method calledfoo
. I.e. if you have an instance of classCreatePosts
you can dothe_instance.foo
. However by doingdef self.foo
(or alternativelydef CreatePosts.foo
which does the same thing, becauseself == CreatePosts
in theclass ... end
-block), you're defining a singleton method which is only available onCreatePosts
itself. I.e. it is called asCreatePosts.foo
notthe_instance.foo
(this is somewhat similar to static methods in other languages, but not quite because you can use the same syntax to define singleton methods on objects that aren't classes).:name
has nothing to do with any variable calledname
. It's a symbol literal, which is kind of like an interned immutable string (though the Symbol class does not define any methods for string-manipulation). You can think of symbols as some sort of mini-strings which are used when you just need to label something and don't need to do string manipulation.Yes, exactly.
self
is the migration file andup
anddown
apply and reverse the migration respectively.- The colons are symbols and denote names, type, scale, etc.. and they denote by column type/order
t.sting :name
means create a column on the current migration object with namename
and typestring
def self.up defines the class method up. When rails runs that migration it will call CreatePosts.up. The alternative being def up which would define an instance method which could be called with CreatePosts.new.up.
:name (for example) is an example of a Symbol. As symbol is similar to a string, but stripped down to the point where there's almost nothing there but the text. In this case they're just using it to tell the #string method what you want the column to be called.
You got that exactly right.
You may find this helpful.
http://railsapi.com/doc/rails-v3.0.0/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#M000666
精彩评论