2010-11-02 108 views
9

我寫我自己的發電機,從控制檯其推出這樣如何從代碼調用生成器?

rails generate ead_document TechnicalOpinion --document_type_id=1 

它創建模型和遷移。我想從我的控制器執行生成器而不使用ruby系統命令。有沒有辦法做到這一點?

回答

15

解似乎是相當簡單:

該代碼在控制器

Rails::Generators.invoke("ead_document", [@document_type.table_name.classify, "--document_type_id=#{@document_type.id}"]) 

是相同的,因爲這控制檯

rails generate ead_document TechnicalOpinion --document_type_id=1 
+3

您能否提出一個關於API的新問題,而不是回答一個問題?這樣我們就可以搜索到問題和答案。 – 2010-11-02 21:01:05

0

在紅寶石有執行系統命令幾種不同的方式

string = `ls` 
# runs command and returns its STDOUT as a string 
string = %x{ls} 
# ditto, alternative syntax 

system "ls" 
# runs command and returns its exit status; its STDOUT gets output to our STDOUT 

print `ls` 
#The same, but with back quotes 

exec "ls" 
# replace current process with another 

# call system command and read output asynchronously 
io = IO.popen('ls') 
# ... later 
io.each {|line| puts line} 
+2

我知道我可以通過執行命令行腳本來做到這一點。我想從ruby代碼中獲得這個。 Generator是一個類,所以我想創建這個類的實例並調用一些方法。 – 2010-11-02 20:12:00