carlosbrando (owner)

Revisions

gist: 58884 Download_button fork
public
Public Clone URL: git://gist.github.com/58884.git
Embed All Files: show embed
snippet.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
class MessagesBuilder
  def initialize
    @description = nil
    @failure = nil
  end
 
  def description(arg = nil, &block)
    @description = arg || block
  end
 
  def failure(arg = nil, &block)
    @failure = arg || block
  end
 
  def get(message)
    instance_variable_get("@#{message}")
  end
end
 
class MatcherBase
  # Creates a class level instance variable reader in MatcherBase.
  #
  class << self;
    attr_reader :messages_builder;
  end
 
  # Initialize our message_build class level instance variable in every
  # class that inherit from us.
  #
  def self.inherited(base)
    base.class_eval do
      @messages_builder = MessagesBuilder.new
    end
  end
 
  def self.messages
    yield @messages_builder
  end
 
  def description
    show_message(:description)
  end
 
  def failure
    show_message(:failure)
  end
 
  protected
    def show_message(type)
      message = self.class.messages_builder.get(type)
 
      if message.is_a? Proc
        message.call
      elsif message
        message
      else
        "No message for this matcher! :/"
      end
    end
end
 
class MyMatcher < MatcherBase
  messages do |msg|
    msg.description { "ah #{@legal}" }
  end
 
  def initialize
    @legal = 'não'
  end
end
 
class CoolMatcher < MatcherBase
  messages do |msg|
    msg.failure { "ah #{@legal}!!!" }
  end
 
  def initialize
    @legal = 'sim'
  end
end
 
puts MyMatcher.new.description
puts CoolMatcher.new.failure