Class: Safer::Protocol::Signature

Inherits:
Object
  • Object
show all
Defined in:
lib/safer/protocol.rb

Overview

Hash of method_name => method.arity, describing a set of methods that we expect to see implemented in another class. Protocol will contain two of these objects - one describing class methods, and one describing instance methods.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table) ⇒ Signature

Create a Protocol::Signature object.



180
181
182
# File 'lib/safer/protocol.rb', line 180

def initialize(table)
  self.safer_protocol_signature__table = table
end

Class Method Details

.create(object, get_methods, get_method, &filter) ⇒ Object

Derive a Signature from an object.



222
223
224
225
226
227
228
229
230
231
232
# File 'lib/safer/protocol.rb', line 222

def self.create(object, get_methods, get_method, &filter)
  method_names = object.send(get_methods)
  method_table = Safer::Protocol._array_to_table(method_names) do
    |h, method_name|
    if filter.call(method_name)
      m = object.send(get_method, method_name)
      m.arity
    end
  end
  self.new(method_table)
end

Instance Method Details

#==(other_object) ⇒ Object

Compare two Protocol::Signature objects for content equality.



185
186
187
188
# File 'lib/safer/protocol.rb', line 185

def ==(other_object)
  self.class == other_object.class &&
    self.safer_protocol_signature__table == other_object.safer_protocol_signature__table
end

#find_violations(object, get_method) ⇒ Object

Given an object, and the name of the method for getting a named method from that object, check that the object implements this function signature.



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/safer/protocol.rb', line 194

def find_violations(object, get_method)
  report = ''
  have_error = false
  error_table = Hash.new
  self.safer_protocol_signature__table.each_pair do |name, arity|
    begin
      m = object.send(get_method, name)
      if m.arity != arity
        report += "#{get_method}(#{name}) arity #{m.arity} != desired #{arity}.\n"
        error_table[name] = m.arity
        have_error = true
      end
    rescue NameError => e
      report += "#{get_method}(#{name}) unimplemented.\n"
      error_table[name] = true
      have_error = true
    end
  end

  if have_error
    Safer::Protocol::Violation.new(error_table, report)
  else
    nil
  end
end

#selfObject

:attr_reader: table Hash object, in which the keys are the names of methods, and the value for a key is the required arity of that method.



176
# File 'lib/safer/protocol.rb', line 176

Safer::IVar.export_reader(self, :table)