パイプ処理
Commons Chain を見ていて、Ruby でそれっぽく作ってみた。
クラスを組み合わせて、一連の処理を行うというもの。
中身は、プラグイン化したクラスを定義したファイルを読み込んで、
順次 execute メソッドを実行していく。
require 'yaml' module Xry class Core def initialize(config) @config = YAML.load(File.read(config)) end def load_plugin(dir) Dir::glob("#{dir}/*rb") {|file| File::open(file, "r") {|fd| eval(fd.read) } } end def execute list = [] @config.each {|m| f = nil code = %Q{f = #{self.class}::#{m['module']}.new\n} eval(code) list << f } context = {} list.each {|c| ctx = nil code = %Q{ctx = c.execute(context)\n} eval(code) puts "return: #{ctx.class}" } puts "Output:" context.each {|k, v| puts "#{k} -> #{v}" } end end end xry = Xry::Core.new("sample.conf") xry.load_plugin("./plugin") xry.execute
- コンフィグ
- module: Foo
- module: Bar
- module: Baz
- Foo.rb
class Foo def initialize end def execute(context) puts "Here is Foo class" context.each {|k, v| puts "#{k} -> #{v}" } context[:foo] = "finished" return context end end
- Bar.rb
class Bar def initialize end def execute(context) puts "Here is Bar class" context.each {|k, v| puts "#{k} -> #{v}" } context[:bar] = "finished" return context end end
- Baz.rb
class Baz def initialize end def execute(context) puts "Here is Baz class" context.each {|k, v| puts "#{k} -> #{v}" } context[:baz] = "finished" return context end end