Module: MustBe::MustOnlyEverContain

Defined in:
lib/must_be/containers.rb,
lib/must_be/containers_registered_classes.rb

Defined Under Namespace

Modules: Base

Constant Summary collapse

REGISTERED_CLASSES =
{}

Class Method Summary collapse

Class Method Details

.register(klass, &body) ⇒ Object

Creates a module from ‘body’ which includes MustOnlyEverContain::Base. The module will be mixed into an objects of type ‘klass’ when ‘must_only_ever_contain’ is called. The module should override methods of`klass’ which modify the contents of the object.

If the module has a class method ‘must_only_contain_check(object, cases, negate = false)’, then this method is used by ‘MustBe.must_only_contain’ to check the contents of ‘object’ against ‘cases’. ‘must_only_contain_check’ should call ‘MustBe#must_notify’ for any contents which do not match ‘cases’. (Or if ‘negate’ is true, then ‘MustBe#must_notify’ should be called for any contents that do match ‘cases’.)



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# File 'lib/must_be/containers.rb', line 222

def self.register(klass, &body)
  unless klass.is_a? Class
    raise ArgumentError, "invalid value for Class: #{klass.inspect}"
  end
  if REGISTERED_CLASSES[klass]
    raise ArgumentError, "handler for #{klass} previously provided"
  end
  
  REGISTERED_CLASSES[klass] = mod = Module.new
  mod.send(:include, Base)
  mod.class_eval(&body)
  
  mutator_advice = Module.new
  mod.instance_methods(false).each do |method_name|
    mutator_advice.module_eval(<<-END, __FILE__, __LINE__ + 1)
      def #{method_name}(*args, &block)
        must_check(lambda { super(*args, &block) }) do |note|
          note.prefix = nil
          call_s = Note.new(self.class, #{method_name.inspect}, args,
            block).message
          call_s.sub!(".", "#")
          note.prefix = "\#{must_only_ever_contain_prefix}\#{call_s}: "
          note
        end
      end
    END
  end
  mod.const_set(:MutatorAdvice, mutator_advice)
  mod.instance_eval do
    def extended(base)
      base.extend(const_get(:MutatorAdvice))
    end
  end
  
  mod
end

.registered_class(object) ⇒ Object



259
260
261
# File 'lib/must_be/containers.rb', line 259

def self.registered_class(object)
  REGISTERED_CLASSES[object.class]
end

.unregister(klass) ⇒ Object



263
264
265
# File 'lib/must_be/containers.rb', line 263

def self.unregister(klass)
  REGISTERED_CLASSES.delete(klass)
end