Sha256: 6b0a40dcd15edb6a0b43c53fb4498cb9847b27774f9b927f540e9af81462d1ff

Contents?: true

Size: 1.8 KB

Versions: 2

Compression:

Stored size: 1.8 KB

Contents

module RuleBook
    module ClassMethods
        # make the 'rule' method private so it cannot be accessed
        # outside of the class the follows_rules method was called in
        private
            def rule(match, &block)
                raise(ArgumentError, "block not given") unless block_given?
                raise(TypeError, "match must be of type Regexp") unless match.class == Regexp
                
                Rule.new(self, match, block)
            end
    end
    
    module InstanceMethods
        def method_missing(meth, *args)
            matched_rules = []
            Rule.list_for(self.class).each do |rule|
                match = meth.to_s.match(rule.match)
                if match.nil?
                    next
                else
                    matched_rules << rule
                end
            end
            
            if matched_rules.empty?
                super
            else
                matched_rules.each do |rule|
                    blk = rule.block
                    match = meth.to_s.match(rule.match)
                    instance_exec(match, &blk)
                end
            end
        end
    end
    
    class Rule
        class << self
            # Rule.list looks better than Rule.rules
            def list; @rules ||= {}; end
            # Rule.for() looks better than Rule.list[]
            def list_for(parent); list[parent]; end
        end
        
        attr :match, :block
        def initialize(parent, match, block)
            @match, @block = match, block
            Rule.list[parent] ||= []
            Rule.list[parent] << self
        end
    end
end

class Module
    def follows_rules
        extend RuleBook::ClassMethods
        include RuleBook::InstanceMethods
    end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rulebook-0.0.2 lib/rulebook.rb
rulebook-0.0.1 rulebook.rb