Created
February 5, 2009 18:05
-
-
Save carlosbrando/58884 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment