First DSL With Ruby

test_event.rb
event "an event that always happens" do
    110 > @target_sales
end


setup do
    puts "Setting up sky"
    @target_sales = 100
end





main.rb
proc {
    events={}
    setups=[]
    
    send :define_method, :event do |name, &block|
       events[name] = block
    end
    
    send :define_method, :setup do  |&block|
       setups << block
    end
    
    send :define_method, :each_event do |&block|
        events.each_pair do | name, event |
            block.call name, event
        end
    end 
    
    send :define_method, :each_setup do |&block|
        setups.each do | setup|
            block.call setup
        end
    end
    
}.call


Dir.glob('*events.rb').each do |file|
    # @events={}
    # @setups=[]
    puts file
    load file
    each_event do |name, event|
        env = Object.new
        each_setup do |setup|
             env.instance_eval &setup
        end 
       
        puts "ALERT #{name}" if env.instance_eval &event
    end 
end 

猜你喜欢

转载自caerun.iteye.com/blog/2315016
DSL