2011-04-07 35 views
0

我目前正在寫一個小程序,該手錶目錄,並添加視頻文件轉換隊列。我已經能夠實現(使用resque)。簡單的紅寶石插件/擴展架構

但是添加到轉換隊列之前,我想觸發基於文件的具體行動。

如:

  • 下降根據文件名
  • 重命名文件
  • 複製(不添加到隊列)的特定文件的某些文件

因此,我要運行一對夫婦在添加之前發生的幫助者。我希望他們以特定的順序執行,並且我希望它可以很容易地添加其他幫助程序。

我想了想,然後看起來像這樣的方式:

每一個助手是一個Ruby類的一套方法:

  • 運行(執行助手)
  • NEW_NAME(返回新的文件名,如果它改變)以下助手來運行並防止增加了 隊列
  • 停止(防止)

所有傭工應存放在一個目錄下,並將按字母順序(EXT/00_helper1.rb,EXT/01_helper2.rb ...)運行。

僞代碼是這樣的:

filename = <parameter> 
stop = false 

for each file in ext/*.rb 
obj = asClass(file).new_instance(filename) 
obj.run 
if (obj.new_name) filename = obj.new_name 
if (obj.stop) 
    stop = true 
    break 
end 
end 

if not stop add_to_queue(filename) 

所以我的問題是:

是有一種優雅的紅寶石的方式?

回答

0

關閉我的頭頂,我可以說,一個可行的辦法是將有每個文件追加到PROC /λ對象的全局陣列。所以,一個輔助文件的一個例子是:

$helpers << Proc.new do |filename| 
    case filename 
    when /.foo$/ then :stop 
    when /.bar$/ then filename.sub(/.bar$/, '.baz') # and presumably rename the actual file as well ... 
    end 
end 

然後你的主要文件將是這樣的:

$helpers = [] 

filename = <parameter> 
stop = false 

Dir.new(<helperdir>).entries.each do |name| 
    require name 
    result = $helpers.last.call(name) 
    if result == :stop 
    stop = true 
    break 
    end 
    # using respond_to? :to_s would probably be better, but in this example :stop would match this criteria as well as strings 
    filename = result if result.is_a? String 
end 

我沒有測試過任何這一點,但我希望你可以得到一般理念。我也不知道你對Ruby的流利程度如何,所以如果你不明白我使用的語法,請說明一下。

+0

是的,我明白了。不過,我不知道這是否是線程安全的。當多個線程同時啓動轉換時,寫入全局變量聽起來不是一個好主意。 – leifg 2011-04-26 22:38:14