rulebook 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (2) hide show
  1. data/rulebook.rb +60 -0
  2. metadata +55 -0
data/rulebook.rb ADDED
@@ -0,0 +1,60 @@
1
+ module RuleBook
2
+ module ClassMethods
3
+ # make the 'rule' method private so it cannot be accessed
4
+ # outside of the class the follows_rules method was called in
5
+ private
6
+ def rule(match, &block)
7
+ raise(ArgumentError, "block not given") unless block_given?
8
+ raise(TypeError, "match must be of type Regexp") unless match.class == Regexp
9
+
10
+ Rule.new(self, match, block)
11
+ end
12
+ end
13
+
14
+ module InstanceMethods
15
+ def method_missing(meth, *args)
16
+ matched_rules = []
17
+ Rule.list_for(self.class).each do |rule|
18
+ match = meth.to_s.match(rule.match)
19
+ if match.nil?
20
+ next
21
+ else
22
+ matched_rules << rule
23
+ end
24
+ end
25
+
26
+ if matched_rules.empty?
27
+ super
28
+ else
29
+ matched_rules.each do |rule|
30
+ blk = rule.block
31
+ match = meth.to_s.match(rule.match)
32
+ instance_exec(match, &blk)
33
+ end
34
+ end
35
+ end
36
+ end
37
+
38
+ class Rule
39
+ class << self
40
+ # Rule.list looks better than Rule.rules
41
+ def list; @rules ||= {}; end
42
+ # Rule.for() looks better than Rule.list[]
43
+ def list_for(parent); list[parent]; end
44
+ end
45
+
46
+ attr :match, :block
47
+ def initialize(parent, match, block)
48
+ @match, @block = match, block
49
+ Rule.list[parent] ||= []
50
+ Rule.list[parent] << self
51
+ end
52
+ end
53
+ end
54
+
55
+ class Module
56
+ def follows_rules
57
+ extend RuleBook::ClassMethods
58
+ include RuleBook::InstanceMethods
59
+ end
60
+ end
metadata ADDED
@@ -0,0 +1,55 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rulebook
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - c00lryguy
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+
12
+ date: 2010-04-02 00:00:00 -04:00
13
+ default_executable:
14
+ dependencies: []
15
+
16
+ description: Apply rules to classes for defining dynamic methods
17
+ email:
18
+ executables: []
19
+
20
+ extensions: []
21
+
22
+ extra_rdoc_files: []
23
+
24
+ files:
25
+ - rulebook.rb
26
+ has_rdoc: true
27
+ homepage:
28
+ licenses: []
29
+
30
+ post_install_message:
31
+ rdoc_options: []
32
+
33
+ require_paths:
34
+ - lib
35
+ required_ruby_version: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - ">="
38
+ - !ruby/object:Gem::Version
39
+ version: "0"
40
+ version:
41
+ required_rubygems_version: !ruby/object:Gem::Requirement
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ version: "0"
46
+ version:
47
+ requirements: []
48
+
49
+ rubyforge_project:
50
+ rubygems_version: 1.3.5
51
+ signing_key:
52
+ specification_version: 3
53
+ summary: Make your classes follow the rules
54
+ test_files: []
55
+