Class: NotNaughty::Validation::Condition

Inherits:
Object
  • Object
show all
Defined in:
lib/not_naughty/validation.rb

Overview

Conditions for use in Validations are usually used with Validations.

Class Method Summary collapse

Class Method Details

.new(condition, positive = true) ⇒ Object

An instance of Condition accepts Symbols, UnboundMethods or anything that responds to :call.

The following examples are similiar to each other:

NotNaughty::Validation::Condition.new proc {|o| o.nil?}
NotNaughty::Validation::Condition.new :nil?
NotNaughty::Validation::Condition.new Object.instance_method(:nil?)


102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
# File 'lib/not_naughty/validation.rb', line 102

def self.new(condition, positive = true)
  instance = allocate
  instance.instance_variable_set :@condition, condition

  block = case condition
  when Symbol then positive ?
    proc { |o| o.send! @condition } :
    proc { |o| not o.send! @condition }
  when UnboundMethod then positive ?
    proc { |o| @condition.bind(o).call } :
    proc { |o| not @condition.bind(o).call }
  else positive ?
    proc { |o| @condition.call o } :
    proc { |o| not @condition.call o }
  end
  
  (class << instance; self; end).
  module_eval { define_method(:evaluate, &block) }
  
  instance
end