Skip to content

Instantly share code, notes, and snippets.

@Martin91
Created July 19, 2014 01:57
Show Gist options
  • Save Martin91/e7f3cdd2fbfb45e19bc1 to your computer and use it in GitHub Desktop.
Save Martin91/e7f3cdd2fbfb45e19bc1 to your computer and use it in GitHub Desktop.
support classed to have abilities to determine if its instances match all or any conditions
module Conditions
def self.included(base)
class << base
attr_reader :conditions_map
def condition(name, &block)
@conditions_map ||= Hash.new
@conditions_map.store(name, block)
end
def conditions
@conditions_map ||= Hash.new
@conditions_map.keys
end
end
def matches_all_conditions?
self.class.conditions.each do |condition|
return false unless self.matches?(condition)
end
true
end
def matches_any_conditions?
self.class.conditions.each do |condition|
return true if self.matches?(condition)
end
false
end
def matches?(condition)
self.class.conditions_map[condition].call(self)
end
end
end
require './conditions'
class Test
include Conditions
condition :must_length_than_five do |test|
test.size > 5
end
condition :must_respond_to_to_s do |test|
test.respond_to? :to_s
end
def size
6
end
def to_s
"Test Instance Here"
end
end
puts Test.conditions
puts "Test's conditions: [:must_length_than_five, :must_respond_to_to_s]"
test = Test.new
puts test.matches_all_conditions?
puts "Expected: test matches all conditions: true"
class Test
def size
4
end
end
puts test.matches_all_conditions?
puts "Expected: test matches all conditions: false"
puts test.matches_any_conditions?
puts "Expected: test matches any conditions: true"
class Test
undef_method :to_s
end
puts test.matches_any_conditions?
puts "Expected: test matches any conditions: false"
class TestWithoutCondition
include Conditions
end
puts TestWithoutCondition.conditions
must_length_than_five
must_respond_to_to_s
Test's conditions: [:must_length_than_five, :must_respond_to_to_s]
true
Expected: test matches all conditions: true
false
Expected: test matches all conditions: false
true
Expected: test matches any conditions: true
false
Expected: test matches any conditions: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment