2010-09-11 24 views
10

我正在使用Sinatra,並且我想要設置一些Rails具有的便利的Rake任務,特別是rake db:seed如何使我的Sinantra應用程序/環境下運行Rake任務?

我第一遍是這樣的:

namespace :db do 
    desc 'Load the seed data from db/seeds.rb' 
    task :seed do 
    seed_file = File.join(File.dirname(__FILE__), 'db', 'seeds.rb') 
    system("racksh < #{seed_file}") 
    end 
end 

racksh是寶石模仿Rails的控制檯。所以我只是直接將種子文件中的代碼提供給它。它可以工作,但顯然不理想。我想要做的是創造一個環境,任務,允許命令到Sinanta應用程序/環境下運行,就像這樣:

task :environment do 
    # what goes here? 
end 

task :seed => :environment do 
    seed_file = File.join(File.dirname(__FILE__), 'db', 'seeds.rb') 
    load(seed_file) if File.exist?(seed_file) 
end 

但我想不通的是如何設置環境所以rake任務可以在它下面運行。任何幫助將非常感激。

回答

10

我已經設置了一個末日使用Rakefile一種滑軌式的環境:

task :environment do 
    require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__)) 
end 

你就必須在config/environment.rb一些含有您需要正確啓動您的應用程序是什麼。這可能是這樣的:

require "rubygems" 
require "bundler" 
Bundler.setup 

require 'sinatra' 

在一個單獨的文件中把這種設置可避免塞滿您的Rakefile,可用於通過config.ru如果你用它來啓動你的末日應用程序,:

require File.expand_path(File.join(*%w[ config environment ]), File.dirname(__FILE__)) 

run Sinatra::Application