Sha256: 959e6fc141eeae46b4da8fe29ab328d36e9448c5313c047149871cc592204368

Contents?: true

Size: 1.15 KB

Versions: 21

Compression:

Stored size: 1.15 KB

Contents

module ClassSpecific

  def construct_class(klass, callback_args: [])
    __constructor__(klass, callback_args) { |name| __define_subclass__ name, self }
  end

  def construct_module(klass, callback_args: [])
    __constructor__(klass, callback_args) { |name| __define_submodule__ name, self }
  end

  def after_construct(&block)
    @__construct_callback__ = block
  end

  private

  def __constructor__(klass, callback_args)
    return self if !(name = __get_constant_name__(klass))
    return const_get name, false  if const_defined? name.to_sym, false

    constant = yield name
    __invoke_callback__(constant, klass, *callback_args) if @__construct_callback__
    constant
  end

  def __invoke_callback__(constant, klass, *args)
    eval_method = constant.is_a?(Class) ? :class_exec : :module_exec
    constant.send(eval_method, klass, *args, &@__construct_callback__)
  end

  def __define_subclass__(name, parent)
    parent.const_set(name, Class.new(parent))
  end

  def __define_submodule__(name, parent)
    parent.const_set(name, parent.clone)
  end

  def __get_constant_name__(constant)
    (name = constant.to_s) ? name.slice(/(?=\:\:)?\w+$/) : nil
  end

end

Version data entries

21 entries across 21 versions & 1 rubygems

Version Path
CloudSesame-1.0.1 lib/services/class_specific.rb
CloudSesame-1.0.0 lib/services/class_specific.rb
CloudSesame-0.9.4 lib/services/class_specific.rb
CloudSesame-0.9.3 lib/services/class_specific.rb
CloudSesame-0.9.2 lib/services/class_specific.rb
CloudSesame-0.9.1 lib/services/class_specific.rb
CloudSesame-0.9.0 lib/services/class_specific.rb
CloudSesame-0.8.3 lib/services/class_specific.rb
CloudSesame-0.8.2 lib/services/class_specific.rb
CloudSesame-0.8.1 lib/services/class_specific.rb
CloudSesame-0.8.0 lib/services/class_specific.rb
CloudSesame-0.7.13 lib/services/class_specific.rb
CloudSesame-0.7.12 lib/services/class_specific.rb
CloudSesame-0.7.11 lib/services/class_specific.rb
CloudSesame-0.7.10 lib/services/class_specific.rb
CloudSesame-0.7.9 lib/services/class_specific.rb
CloudSesame-0.7.8 lib/services/class_specific.rb
CloudSesame-0.7.7 lib/services/class_specific.rb
CloudSesame-0.7.5 lib/services/class_specific.rb
CloudSesame-0.7.4 lib/services/class_specific.rb