Module: Stupidedi::Versions::Common::ElementTypes::Operators::Relational

Included in:
DateVal::Proper, FixnumVal::NonEmpty, FloatVal::NonEmpty, IdentifierVal::Valid, StringVal::Valid
Defined in:
lib/stupidedi/versions/common/element_types/operators.rb

Instance Method Summary collapse

Instance Method Details

#relational_operators(*ops)



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/stupidedi/versions/common/element_types/operators.rb', line 68

def relational_operators(*ops)
  file, line, = Stupidedi.caller

  if ops.last.is_a?(Hash)
    options = ops.pop

    case options[:coerce]
    when String, Symbol
      coerce = options[:coerce]
    else
      raise ArgumentError,
        "must pass :coerce => :method"
    end
  else
    raise ArgumentError,
      "must pass :coerce => :method"
  end

  # Note that we can't test respond_to?(coerce) because coerce is
  # often a refinement method, like #to_d, #to_time, etc. Currently
  # respond_to? returns false on refinment methods, so we just call
  # the method and assume a NoMethodError is due to coerce (hopefully
  # not some other missing method)
  ops.each do |op|
    class_eval(<<-RUBY, file, line.to_i - 1)
      def #{op}(other, &block)
        begin
          value.#{op}(other.#{coerce}, &block)
        rescue NoMethodError
          begin
            me, he = other.coerce(self)
            me.#{op}(he, &block)
          rescue NoMethodError
            raise TypeError,
              "cannot coerce \#{other.class} to \#{self.class}"
          end
        end
      end
    RUBY
  end
end