---
title: "First DSL With Ruby"
author: "caiwenhn2008"
date: "2016-08-02T16:23:58Z"
tags: []
categories: ["企业架构"]
slug: "first-dsl-with-ruby"
draft: false
lastmod: "2016-08-02T16:24:26Z"
id: 2315016
url: "https://caerun.iteye.com/blog/2315016"
---

test_event.rb

```java

event "an event that always happens" do
    110 > @target_sales
end


setup do
    puts "Setting up sky"
    @target_sales = 100
end



```



main.rb

```java
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 


```