顯示具有 ruby 標籤的文章。 顯示所有文章
顯示具有 ruby 標籤的文章。 顯示所有文章

2015年11月5日 星期四

Ruby [ class variable, class instance variable, instance variable]

所以
@a 是 class variable
@b 是 class instance variable
@c 是 instance variable



class Hi @@a = 1 # class variable @b = 2 # class instance variable def initialize @c = 3 # instance variable end def test # instance method, works on objects of class A puts @@a # => 1 puts @b # => nil, there is no instance variable @b puts @c # => 3 # we defined this instance variable in the initialize end def self.test2 # instance method, works on objects of class A puts @@a # => 1 puts @b # => 2 puts @c # => nil end end

2015年1月23日 星期五

[Ruby] class_eval and instance_eval

一些實驗. in Ruby1.9.3
class A; end A.class_eval do attr_accessor :x def barx; end define_method :foox do; end end p A.instance_methods(false).sort 結果: [:barx, :defined_in_class_eval, :foox, :x, :x=] p A.singleton_methods 結果 : [:defined_in_instance_eval, :yaml_tag, :const_missing] class B; end B.instance_eval do attr_accessor :y def bary; end define_method :fooy do; end end p B.instance_methods(false).sort 結果: [:fooy, :y, :y=] p B.singleton_methods 結果: [:bary, :yaml_tag, :const_missing] class C; end singleton_class = class << C; self end singleton_class.instance_eval do attr_accessor :z def barz; puts 'where is barz ?' end define_method :fooz do; end end p C.instance_methods(false).sort 結果: [] p C.singleton_methods 結果: [:z, :z=, :fooz, :yaml_tag, :const_missing] singleton_class.barz 結果: where is barz ? p singleton_class.methods(false) 結果: [:barz] 所有結果對照: A.instance_methods : ["barx", "foox", "x", "x="] A.singleton_methods : [] B.instance_methods : ["fooy", "y", "y="] B.singleton_methods : ["bary"] C.instance_methods : [] C.singleton_methods : ["z", "z=", "fooz"] singleton_class.barz : where is barz ? singleton_class.methods : ["barz"]

2015年1月20日 星期二

[ruby] install rvm has error in CentOS


Error running 'requirements_centos_libs_install libffi-devel',
showing last 15 lines of /usr/local/rvm/log/1421736709/package_install_libffi-devel.log
Error: Package: libffi-devel-3.0.5-3.2.el6.i686 (base)'


解法:  

rpm -e --nodeps libffi
And it uninstalled the offending libffi package. Then
yum install libffi-devel

2015年1月6日 星期二

[Ruby] class_eval and instance_eval 使用

class_eval 用來定義 Class 的 instance method.
instance_eval 用來定義該對象的 singleton_method.

class Person end Person.class_eval do def say_hello "Hello!" end end jimmy = Person.new jimmy.say_hello # "Hello!" class Person end Person.instance_eval do def human? true end end Person.human? # true class P end old_p = P.new P.class_eval do def pp p 'method pp' end end new_p = P.new old_p.pp # 'method pp' new_p.pp # 'method pp' old_p.class_eval do def old_pp p 'method old_pp' end end old_p.old_pp # 'method old_pp' new_p.old_pp # NoMethodError: undefined method 'old_pp' class P end obj_p = P.new P.instance_eval do def pp p 'method pp' end end P.pp # 'method pp' obj_p.pp # NoMethodError: undefined method 'pp' obj_p.instance_eval do def obj_p p 'method obj_p' end end obj_p.obj_p # 'method obj_p' P.obj_p # NoMethodError: undefined method 'obj_pp' obj_p.class_eval do def class_p p 'class_p' end end obj_p.class_p # 'class_p' P.class_p # NoMethodError: undefined method 'class_p' P.new.class_p # NoMethodError: undefined method 'class_p'

還可以這樣用
class Monk end Monk.instance_eval("def zen; 42; end", __FILE__, __LINE__) Monk.zen # 42
更詳細的資訊:

2014年12月12日 星期五

Ruby 測試 @@ 與 @ 變數 在 instance method 與 class method 的差異.

來測試一下, @@變數與 @變數分別在 instance method 與 class method 當中的變化.

class Foo @@cc = 0 def self.inc @c = @c || 0 @c += 1 @@cc += 1 p "@c=#{@c}, @@c=#{@@cc}" end def dec @c = @c || 0 @c -= 1 @@cc-= 1 p "@c=#{@c}, @@c=#{@@cc}" end end

執行結果:

Foo.inc 
=>"@c=1, @@c=1"

Foo.inc 
=>"@c=2, @@c=2"

foo = Foo.new
foo.dec
=>"@c=-1, @@c=1"

Foo.inc 
=>"@c=3, @@c=2"

foo.dec
=>"@c=-2, @@c=1"

以上結果~  @變數在 instance method 與 class method 是不同的.
但 @@變數是相同的. 

2014年12月10日 星期三

Ruby Object Tree

Object在最頂端的一棵樹。比如說,基本庫中的重要的類的繼承關係樹


2014年10月2日 星期四

Ruby 中 class 與 module 的差異.

來源: http://stackoverflow.com/questions/151505/difference-between-a-class-and-a-module

想像一下~  module 就像是 library , 可以被其他 classs include or extend .


╔═══════════════╦═══════════════════════════╦═════════════════════════════════╗
                class                      module                          
╠═══════════════╬═══════════════════════════╬═════════════════════════════════╣
 instantiation  can be instantiated        can *not* be instantiated       
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 usage          object creation            mixin facility. provide         
                                             a namespace.                  
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 superclass     module                     object                          
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 consists of    methods, constants,        methods, constants,             
                  and variables              and classes                   
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 methods        class methods,             module methods,                 
                  instance methods           instance methods              
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 inheritance    inherits behavior and can  No inheritance                  
                  be base for inheritance                                  
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 inclusion      cannot be included         can be included in classes and  
                                             modules by using the include  
                                             command (includes all         
                                             instance methods as instance  
                                             methods in class/module)      
╟───────────────╫───────────────────────────╫─────────────────────────────────╢
 extension      can not extend with        module can extend instance by   
                  extend command             using extend command (extends 
                  (only with inheritance)    given instance with singleton 
                                             methods from module)          
╚═══════════════╩═══════════════════════════╩═════════════════════════════════╝

2014年9月24日 星期三

rails respond_to 與 method_missing 使用.

來源: http://blog.enriquez.me/2010/2/21/dont-forget-about-respond-to-when-implementing-method-missing/



class Proxy def initialize(subject) @subject = subject end def method_missing(method) @subject.send(method) end end proxy = Proxy.new(Time) proxy.respond_to?(:now) # => false proxy.now # => Fri Feb 05 00:34:53 -0500 2010

更好實現Proxy 的方法.
class Proxy def initialize(subject) @subject = subject end def method_missing(method) if @subject.respond_to?(method) @subject.send(method) else super(method) end end def respond_to?(method, include_private = false) super || @subject.respond_to?(method, include_private) end end proxy = Proxy.new(Time) proxy.respond_to?(:now) # => true proxy.now # => Fri Feb 05 00:34:53 -0500 2010

2014年9月19日 星期五

[Ruby] module 內的用法.


一些module 常看到的用法:

class_variable_get 和 class_variable_set 這兩個方法, 就是取得 class_variable 的method,
因為在module 被 其他 class extend 後, 這method 就起作用了.

另外還有 class_eval 的用法. 

def self.included(base) base.send(:include, ActiveModel::Naming) base.send(:include, ActiveModel::Conversion) base.send(:include, ActiveModel::Dirty) base.extend ClassMethods end module ClassMethods class_variable_get(:@@attributes).each do |attr| class_eval <<-EVAL @@all_attributes << "#{attr}".to_sym define_method "#{attr}" do @#{attr} end define_method "#{attr}?" do #{attr} ? true : false end # writable attributes with dirty support define_method "#{attr}=" do |value| return if value == @#{attr} #{attr}_will_change! @#{attr} = value end EVAL end end

這邊可以看到 instance_eval 的用法:
def self.included(base) base.extend ClassMethods end def ClassMethods def has_many(klass_sym) prefix = "Objects::" klass_name = prefix + klass_sym.to_s.classify instance_eval do define_method "#{klass_sym}" do klass = klass_name.constantize klass.where("#{self.remote_name}Id = '#{self.id}'") end end end end

[Ruby] STDIN、STDOUT、STDERR和$stdin、$stdout、$stderr

STDIN、STDOUT、STDERR 都是 IO class 不能更動.
$stdin、$stdout、$stderr 是可以更動的.

$stdout 與 STDOUT 一開始都是輸出到螢幕. 

$stdout = open('output_file','w')
#將會輸出到 output_file 檔案. 

$stdout = STDOUT
#又會回到螢幕上.



# std.rb $stdout.reopen("out.txt", "w") $stderr.reopen("err.txt", "w") puts 'normal output' warn 'something to stderr' 

執行結果:
$ ls
std.rb
$ ruby std.rb
$ ls
std.rb err.txt out.txt
$ cat err.txt
something to stderr
$ cat out.txt
normal output


參考資訊:Link

2014年9月12日 星期五

手動安裝 ruby 版本, 要使用 ln 去 連結.

手動安裝1.9.1 and gem 1.3.5

來源
Install Ruby 1.8 (MRI)

apt-get -y install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 irb1.8 libreadline-ruby1.8 libruby1.8 libopenssl-ruby
ln -s /usr/bin/ruby1.8 /usr/bin/ruby
ln -s /usr/bin/rdoc1.8 /usr/bin/rdoc
ln -s /usr/bin/irb1.8 /usr/bin/irb
ln -s /usr/bin/ri1.8 /usr/bin/ri

Install RubyGems (from source)

curl http://rubyforge.org/frs/download.php/60718/rubygems-1.3.5.tgz | tar -xzv
cd rubygems-1.3.5 && ruby setup.rb install
cd .. && rm -rf rubygems-1.3.5
ln -s /usr/bin/gem1.8 /usr/local/bin/gem
gem sources -a http://gems.github.com # add Github as a gem source, you won't

2014年6月18日 星期三

[BenchMark] Rails array and hash 速度

測試一下ruby 的array 與 hash 的速度.

環境
$ uname -mrs
Linux 2.6.32-220.4.2.el6.x86_64 x86_64
Ruby version
ruby 1.8.7 (2012-02-08 MBARI 8/0x6770 on patchlevel 358) [x86_64-linux], MBARI 0x6770, Ruby Enterprise Edition 2012.02


require 'benchmark' Document = Struct.new(:id,:a,:b,:c) documents_a = [] documents_h = {} 1.upto(10_000) do |n| d = Document.new(n) documents_a << d documents_h[d.id] = true end searchlist = Array.new(1000){ rand(10_000)+1 } Benchmark.bm(10) do |x| x.report('array_any?'){searchlist.each{|el| documents_a.any?{|d| d.id == el}} } x.report('array_include?'){searchlist.each{|el| documents_a.include?(el)} } x.report('hash_has_key?'){searchlist.each{|el| documents_h.has_key?(el)} } x.report('hash'){searchlist.each{|el| documents_h[el] } } end 


結果(當array 與 hash 資料有 10,000筆時):

                            user            system      total                 real
array_any?          5.350000    0.000000   5.350000      ( 5.367080)
array_include?    0.890000    0.000000   0.890000      ( 0.887109)
hash_has_key?   0.000000    0.000000   0.000000     ( 0.000420)
hash                    0.000000    0.000000   0.000000     ( 0.002201)


結果(當array 與 hash 資料有 100,000筆時):

                           user             system        total                real
array_any?         5.970000     0.000000    5.970000     (  5.979810)
array_include?   10.650000    0.000000   10.650000    ( 10.656045)
hash_has_key?   0.000000    0.000000    0.000000     (  0.000545)
hash                    0.000000    0.000000     0.000000    (  0.000968)

看起來用 hash 是最快的, 但是array 的include? 在資料筆數大的時候, 居然慢比any?還慢.
相關來源:
http://stackoverflow.com/questions/5551168/performance-of-arrays-and-hashes-in-ruby

2013年6月13日 星期四

[Ruby On Rails] 技巧小筆記

Ruby 1.8 的字串其實只是 byte 的集合,如果你需要對 UTF-8 字串做一些函式操作,
Rails 提供了 mb_chars 來包裝以獲得正確的結果,來源:http://ihower.tw/rails2/
例如: "中文".size # 6 "中文".mb_chars.size # 2

1.取得Gem full path: 
rails c
Gem.loaded_specs['rails'].full_gem_path 

2.過濾html tag in controller  
  string_with_html = '123'
  方法一: HTML::FullSanitizer.new.sanitize(string_with_html)
  方法二: include ActionView::Helpers::SanitizeHelper 

          strip_tags(string_with_html)


Use self.class class Foo def self.some_class_method puts self end def some_instance_method self.class.some_class_method end end print "Class method: " Foo.some_class_method print "Instance method: " Foo.new.some_instance_method

Show included_modules  
a.new.included_modules

Find source location
a.method(:method_name).source_location

記錄console的 sql log Link
ActiveRecord::Base.logger = Logger.new File.open('log/development.log', 'a')

2012年10月26日 星期五

[Ruby]Using select, reject, collect, inject , detect and flatten.

for a = [1,2,3,4] for n in a puts n end

結果:
1
2
3
4
=> [1, 2, 3, 4]

each a.each do |n| puts n end 
結果:
1
2
3
4
=> [1, 2, 3, 4]

select a = [1,2,3,4] a.select {|n| n > 2}
結果:
=> [ 3, 4]

reject a = [1,2,3,4] a.reject {|n| n > 2}
結果:
=> [ 1, 2]

collect a = [1,2,3,4] a.collect {|n| n*n}
結果:
=> [1, 4, 9, 16]

inject a = [1,2,3,4] a.inject {|acc,n| acc + n}
結果:
=> 10

inject a = [1,2,3,4] a.inject(15) {|acc,n| acc + n}
結果:
=> 25

inject a = [1,2,3,4] a.inject([]) {|acc,n| acc << n}
結果:
=> [2, 4, 6, 8]

detect a = [1,2,3,4] a.detect {|n| n == 3}
結果:
=> 3

flatten a = [1,[2,2,[3,4],5],[6,7]] p a.flatten #=> [1, 2, 2, 3, 4, 5, 6, 7] a.flatten! #=> [1, 2, 2, 3, 4, 5, 6, 7]
結果:
=> 3

參考來源:

http://www.namaraii.com/rubytips/?%C7%DB%CE%F3

2012年8月30日 星期四

[Ruby] Ruby的頭號Gem:Rake

文章來源:http://blog.csdn.net/smilewater/article/details/1683808

Rake簡介

RakeMakeAnt
Rake的意思是Ruby Make,一個用ruby開發的代碼構建工具。Rake的英文意思是耙子,一種很樸實的勞動工具。真的是很貼切,Rake正是一個功能強大、勤勤懇懇的勞動工具。
Rake會經常跟C/C++領域的makeJava世界的Ant進行對照,事實上,它們有很多相似的地方。我們先來看一下makeant的歷史。
make的出現是為瞭解決批量編譯的問題。對於一個小型的項目來說,用一個腳本文件或者批處理命令來進行批量編譯就已經足夠好。但是對於大型的項目來說,僅僅為了少數幾個文件的改變就全部重新進行一次編譯無疑是耗時且不必要的。而且,在大型的項目中,往往會有很複雜的依賴關係。
Make的出現就是為瞭解決這兩個問題,make有兩個優點:
  1. Make瞭解自上次Make運行以來哪些文件發生了變化,它會僅僅編譯那些發生變化的文件。
  2. Make會跟蹤文件之間的依賴性,如果文件A依賴於文件B,那麼如果兩者都沒有編譯時,Make會首先編譯文件B
Ant算是一個Java世界的make,它要比make年輕許多(想想make是出現在1972年吧),它除了支持批量編譯之外,還支持單元測試、JavaDoc等任務。因此,AntJava世界中比Make更加流行。
但是,為什麼Ruby需要Rake
Ruby代碼不需要編譯,為什麼需要Rake?其實,與其說Rake是一個代碼構建工具,不如說Rake是一個任務管理工具,通過Rake我們可以得到兩個好處:
  1. 以任務的方式創建和運行腳本
當然,你可以用腳本來創建每一個你希望自動運行的任務。但是,對於大型的應用來說,你幾乎總是需要為數據庫遷移(比如Railsdb:migrate任務)、清空緩存、或者代碼維護等等編寫腳本。對於每一項任務,你可能都需要寫若干腳本,這會讓你的管理變得複雜。那麼,把它們用任務的方式整理到一起,會讓管理變得輕鬆很多。
  1. 追蹤和管理任務之間的依賴
Rake還提供了輕鬆管理任務之間依賴的方式。比如,"migrate"任務和"schemadump"任務都依賴於 "connect_to_database"任務,那麼在"migrate"任務調用之前,"connect_to_database"任務都會被執行。
在哪裡可以獲得Rake
Rake的主頁是在http://rake.rubyforge.org/,在這裡你可以獲得Rake的簡單介紹,API以及一些有用文檔的鏈接。可以在http://rubyforge.org/frs/?group_id=50獲得最新版的Rake,在作者寫作時,最新版本是0.7.3

Rake腳本編寫

一個簡單腳本

Rake的腳本相當簡單,下面用一個例子進行說明。假設你是一個勤勞的家庭型程序員,在週末你打算為你的家人做一些貢獻。所以你為自己制定了三個任務:買菜、做飯和洗衣服。打開你的文本編輯器,創建一個名叫rakefile的文件(Rake會在當前路徑下尋找名叫RakefilerakefileRakeFile.rbrakefile.rbrake文件),並輸入如下內容:
desc "任務1 -- 買菜"
task :purchaseVegetables do
puts "到沃爾瑪去買菜。"
end

desc "任務2 -- 做飯"
task :cook do
puts "做一頓香噴噴的飯菜。"
end

desc "任務3 -- 洗衣服"
task :laundry do
puts "把所有衣服扔進洗衣機。"
end
打開命令行工具,進入這個文件所在目錄,然後運行下面的命令,大致應該類似如下結果:
D:/work/ruby_works/ruby_book>rake purchaseVegetables
(in D:/work/ruby_works/ruby_book)
到沃爾瑪去買菜。

D:/work/ruby_works/ruby_book>rake cook
(in D:/work/ruby_works/ruby_book)
做一頓香噴噴的飯菜。

D:/work/ruby_works/ruby_book>rake laundry
(in D:/work/ruby_works/ruby_book)
把所有衣服扔進洗衣機。


分析
很簡單,也很易讀,對吧。這個文件一共定義了3個任務,descRake定義的方法,表示對下面定義任務的描述。這個描述會在使用Rake --tasks(或者Rake -T,為懶人準備的快捷方式)命令時輸出在屏幕上。
D:/work/ruby_works/ruby_book>rake --tasks
(in D:/work/ruby_works/ruby_book)
rake cook #
任務2 -- 做飯
rake laundry #
任務3 -- 洗衣服
rake purchaseVegetables #
任務1 -- 買菜


下面的語句定義了purchaseVegetables這個任務,taskRake最重要的方法。它的方法定義是:task(args, &block)。任務體是一個block,本例中只是簡單輸出你所要做的工作。需要注意的是代碼
puts "到沃爾瑪去買菜。"
完全是一個普通的Ruby語句,putsRuby中進行輸出的一般性方法,可以看出,Rake任務可以完全使用Ruby的能力,這使得它非常強大。

加入依賴關係

很顯然,在我們定義的任務中,做飯是依賴於買菜的(我相信大多數程序員在週末的冰箱裡除了可樂沒有別的)。那麼,我們需要在我們的任務定義中加入這個依賴關係,修改後的文件如下:
desc "任務1 -- 買菜"
task :purchaseVegetables do
puts "
到沃爾瑪去買菜。"
end

desc "
任務2 -- 做飯"
task :cook => :purchaseVegetables do
puts "
做一頓香噴噴的飯菜。"
end

desc "
任務3 -- 洗衣服"
task :laundry do
puts "
把所有衣服扔進洗衣機。"
end


再次運行做飯任務,你會得到如下結果:
D:/work/ruby_works/ruby_book>rake cook
(in D:/work/ruby_works/ruby_book)
到沃爾瑪去買菜。
做一頓香噴噴的飯菜。


是的,你當然需要先買菜,誰讓你是一個冰箱空空如野的程序員呢。

命名空間

跟任何編程語言類似,當你的rake文件很多時,當你有很多任務的時候,你需要關注它們的命名衝突問題,命名空間(namespace)就是一個自然的解決方案。你可以為上面的三個任務定義一個叫做home的命名空間。
namespace :home do
desc "
任務1 -- 買菜"
task :purchaseVegetables do
puts "
到沃爾瑪去買菜。"
end
……
end


再次運行rake --tasks,你會得到如下的結果:
D:/work/ruby_works/ruby_book >rake --tasks
(in D:/work/ruby_works/ruby_book)
rake home:cook #
任務2 -- 做飯
rake home:laundry #
任務3 -- 洗衣服
rake home:purchaseVegetables #
任務1 -- 買菜


你現在需要使用rake home:cook才能啟動做飯這個任務了。當然,你可以在你的rakefile中使用多個命名空間,對任務進行分類。

在一個任務中調用另外一個任務

當任務眾多的時候,你很可能需要在一個任務中調用另外一個任務,假設我們把今天所有要做的工作定義為一個任務:today。在這個任務中,有兩個任務需要被調用,一個是做飯,一個是洗衣服。當然,由於做飯依賴於買菜,我們還是需要買菜的(這一步是逃不過去的,呵呵)。在文件的頂部定義一個today的任務:
desc "今天的任務"
task :today do
Rake::Task["home:cook"].invoke
Rake::Task["home:laundry"].invoke
end

namespace :home do
……
end


可以看出,調用其它任務的方式很簡單,只需要調用Rake::Task["task_name"].invoke 方法就可以了。在命令行中啟動rake today,可以得到:
D:/work/ruby_works/ruby_book >rake today
(in D:/work/ruby_works/ruby_book)
到沃爾瑪去買菜。
做一頓香噴噴的飯菜。
把所有衣服扔進洗衣機。


默認任務

可以為Rake增加一個默認任務,這樣可以簡單地用Rake命令來觸發這個默認任務,在上面的rakefile中,我們可以用如下方式把"today"任務作為默認任務。
task :default => [:today]
然後調用直接在命令行中調用rake,可以得到跟調用rake today同樣的輸出結果。
這就是我們簡單的一個Rake任務定義,下面是完整的修改後的rakefile
task :default => [:today]

desc "
今天的任務"
task :today do
Rake::Task["home:cook"].invoke
Rake::Task["home:laundry"].invoke
end

namespace :home do

desc "
任務1 -- 買菜"
task :purchaseVegetables do
puts "
到沃爾瑪去買菜。"
end

desc "
任務2 -- 做飯"
task :cook => :purchaseVegetables do
puts "
做一頓香噴噴的飯菜。"
end

desc "
任務3 -- 洗衣服"
task :laundry do
puts "
把所有衣服扔進洗衣機。"
end
end


Rails中的Rake任務

Rails預定義了大量的Rake任務,在Rails應用的開發過程中,你想必已經在大量使用它們了。在Rails中,所有的Rake任務都放在rails目錄的lib/tasks目錄下(在作者的環境下是c:/ruby/lib/ruby/gems/1.8/gems/rails-1.1.4/lib/tasks/),所有的rake任務都以.rake作為後綴名,這些以.rake結尾的文件會被自動加載到你的環境中。你可以到一個已有的Rails工程根目錄下鍵入rake --tasks,可以看到很多的rake任務已經為你整裝待發了。
Rails中,最常使用的Rake任務之一是進行數據庫的遷移(migration)。數據庫遷移程序允許你使用Ruby腳本來定義數據庫模式,而db:migrate就是進行這個工作的rake任務。下面我們來分析這個rake任務。
db:migrate任務
db:migrate任務存放在lib/tasks/databases.rake文件中。這個文件中定義了所有與數據庫操作相關的任務,我們僅僅抽出db:migrate的定義:
namespace :db do
desc "Migrate the database through scripts in db/migrate. Target specific version with VERSION=x"
task :migrate => :environment do
ActiveRecord::Migrator.migrate("db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
end
……
end


分析
首先是命名空間的聲明,migrate任務的命名空間是db。這也就是我們用db:migrate來引用它的原因。
下面是一個描述,說明該任務的功能是把定義在db/migrate目錄下(相對於你的Rails應用程序的根目錄)的遷移腳本遷移到數據庫中,如果不指定VERSION的話,默認是最新版本,否則可以恢復到一個指定的版本。
接著是任務的定義,該任務依賴於enviroment任務,這個任務在misc.rake中定義,用來加載Rails的環境,它的定義相當簡單:
task :environment do
require(File.join(RAILS_ROOT, 'config', 'environment'))
end


用來加載config/environment.rb文件,該文件會加載Rails工作所需要加載的環境。由於加載了這個環境,所以ActiveRecord對象現在可以使用,下面就是調用ActiveRecord::Migrator.migrate方法對每個db/migrate/下的腳本文件進行遷移。
最後會調用db:schema:dump任務,該任務的主要作用是產生db/schema.rb文件。該文件用來記錄不同版本的數據庫模式。這個任務的定義就在db:migrate任務下面不遠的地方,有興趣的讀者可以自行進行分析。