Module: SuperatorMixin

Defined in:
lib/superators19/macro.rb

Constant Summary collapse

BINARY_RUBY_OPERATORS =
%w"** * / % + - << >> & | ^ <=> >= <= < > === == =~"
UNARY_RUBY_OPERATORS =
%w"-@ ~@ +@"
BINARY_OPERATOR_PATTERN =
BINARY_RUBY_OPERATORS.map { |x| Regexp.escape(x) }.join "|"
UNARY_OPERATOR_PATTERN =
UNARY_RUBY_OPERATORS.map { |x| Regexp.escape(x) }.join "|"
UNARY_OPERATOR_PATTERN_WITHOUT_AT_SIGN =
UNARY_OPERATOR_PATTERN.gsub '@', ''
VALID_SUPERATOR =
/^(#{BINARY_OPERATOR_PATTERN})(#{UNARY_OPERATOR_PATTERN_WITHOUT_AT_SIGN})+$/

Instance Method Summary collapse

Instance Method Details

#defined_superatorsObject



36
37
38
# File 'lib/superators19/macro.rb', line 36

def defined_superators
  methods.grep(/^superator_definition_/).map { |m| superator_decode(m.to_s) }
end

#respond_to_superator?(sup) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/superators19/macro.rb', line 32

def respond_to_superator?(sup)
  respond_to? superator_definition_name_for(sup)
end

#superator_send(sup, operand) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/superators19/macro.rb', line 11

def superator_send(sup, operand)
  meth = method(superator_definition_name_for(sup))
  begin
    # If the user supplied a block that doesn't take any arguments, Ruby 1.9
    # objects if we try to pass it an argument
    if meth.arity.zero?
      meth.call
    else
      meth.call(operand)
    end
  rescue NoMethodError
    # Checking for respond_to_superator? is relatively slow, so only do this
    # if calling the superator didn't work out as expected
    if not respond_to_superator? sup
      raise NoMethodError, "Superator #{sup} has not been defined on #{self.class}"
    else
      raise
    end
  end
end

#undef_superator(sup) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/superators19/macro.rb', line 78

def undef_superator(sup)
  if respond_to_superator?(sup)
    real_operator = real_operator_from_superator sup
    real_operator_alias = superator_alias_for sup

    (class << self; self; end).instance_eval do
      undef_method superator_definition_name_for(sup)
      if respond_to? real_operator_alias
        alias_method real_operator, real_operator_alias if defined_superators.empty?
      else
        undef_method real_operator
      end
    end
  else
    raise NoMethodError, "undefined superator #{sup} for #{self.inspect}:#{self.class}"
  end
end