Module: Stupidedi::Versions::Common::ElementTypes::Operators::Binary

Included in:
FixnumVal::NonEmpty, FloatVal::NonEmpty
Defined in:
lib/stupidedi/versions/common/element_types/operators.rb

Instance Method Summary collapse

Instance Method Details

#binary_operators(*ops)



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
# File 'lib/stupidedi/versions/common/element_types/operators.rb', line 24

def binary_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
          copy(:value => value.#{op}(other.#{coerce}, &block))
        rescue NoMethodError
          begin
            me, he = other.coerce(self)
            copy(:value => me.#{op}(he, &block).#{coerce})
          rescue NoMethodError
            raise TypeError,
              "cannot coerce \#{other.class} to \#{self.class}"
          end
        end
      end
    RUBY
  end
end