Class: Object

Inherits:
BasicObject
Defined in:
lib/functional/behavior.rb

Instance Method Summary collapse

Instance Method Details

#behaves_as?(name, abend = false) ⇒ Boolean

Note:

Will return true if the object implements the required methods. The object’s class hierarchy does not necessarily have to include a corresponding #behavior call.

Does the object implement the given #behavior_info?

Parameters:

  • name (Symbol)

    name of the #behavior_info to verify behavior against.

  • abend (Boolean) (defaults to: false)

    raise an exception when true and the there are unimplemented methods

Returns:

  • (Boolean)

    whether or not the required public methods are implemented



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/functional/behavior.rb', line 97

def behaves_as?(name, abend = false)

  name = name.to_sym
  bi = $__behavior_info__[name]
  return false if bi.nil?

  validator = proc do |obj, method, arity|
    (obj.respond_to?(method) && arity == :any) || obj.method(method).arity == arity
  end

  if self.is_a?(Class) || self.is_a?(Module)
    bi = bi.select{|method, arity| method.to_s =~ /^self_/ }
  end

  bi.each do |method, arity|
    begin
      func = method.to_s
      obj = self

      if (self.is_a?(Class) || self.is_a?(Module)) && func =~ /^self_/
        func = func.gsub(/^self_/, '')
      elsif method =~ /^self_/
        func = func.gsub(/^self_/, '')
        obj = self.class
      end

      valid = validator.call(obj, func, arity)
      raise NameError if abend && ! valid
      return valid unless valid
    rescue NameError
      if abend
        func = "#{method.to_s.gsub(/^self_/, 'self.')}/#{arity.to_s.gsub(/^any$/, ':any')}"
        raise BehaviorError.new("undefined callback function ##{func} in #{self} (behavior '#{name}')")
      else
        return false
      end
    end
  end

  return true
end