[英]simple ruby plugin/extension architecture
我當前正在編寫一個小程序,該程序監視目錄並將視頻文件添加到轉換隊列中。 我已經能夠做到這一點(使用resque)。
但是在將添加到轉換隊列之前,我想基於文件名觸發特定操作。
例如:
因此,在添加之前,我想運行幾個助手。 我希望它們以一定順序執行,並且我希望添加其他幫助程序變得容易。
我的思考方式如下所示:
每個助手都是一個帶有一組方法的Ruby類:
所有幫助程序都應存儲在一個目錄中,並將按字母順序運行(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)
所以我的問題是:
有沒有優雅的紅寶石方式?
我可以說,一種可能的方法是擁有每個文件都附加到的Proc / lambda對象的全局數組。 因此,幫助文件的示例為:
$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方面的流利程度,所以如果您不理解我使用的語法,請這么說。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.