开发者

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:

  1. What does self. means in self.up and self.down ? How it differs from simply up and down ?

  2. What does all these colons (:) means in :posts, :name, etc. ? Is that just a part of the variable name ?

  3. What does t.string :name means ? Is that a call to string function on object t with parameter :name ?

Thanks a lot!!


  1. If you define a method using def foo, you're creating an instance method called foo. I.e. if you have an instance of class CreatePosts you can do the_instance.foo. However by doing def self.foo (or alternatively def CreatePosts.foo which does the same thing, because self == CreatePosts in the class ... end-block), you're defining a singleton method which is only available on CreatePosts itself. I.e. it is called as CreatePosts.foo not the_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).

  2. :name has nothing to do with any variable called name. 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.

  3. Yes, exactly.


  1. self is the migration file and up and down apply and reverse the migration respectively.
  2. The colons are symbols and denote names, type, scale, etc.. and they denote by column type/order
  3. t.sting :name means create a column on the current migration object with name name and type string


  1. 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.

  2. :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.

  3. You got that exactly right.

You may find this helpful.

http://railsapi.com/doc/rails-v3.0.0/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#M000666

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜