module Schoolkeep::Scribble

Attributes

stub[RW]

Public Class Methods

register_models() click to toggle source
# File lib/schoolkeep/scribble.rb, line 57
def register_models
  if stub
    models.each do |class_name, args|
      begin
        constantize(class_name)
      rescue NameError
        Object.const_set(class_name, Class.new(OpenStruct))
      end
    end
  end

  models.each do |class_name, args|
    register_model(class_name, *args)
  end
end

Private Class Methods

constantize(camel_cased_word) click to toggle source
# File lib/schoolkeep/scribble.rb, line 112
def constantize(camel_cased_word)
  names = camel_cased_word.split('::')

  # Trigger a builtin NameError exception including the ill-formed constant in the message.
  Object.const_get(camel_cased_word) if names.empty?

  # Remove the first blank element in case of '::ClassName' notation.
  names.shift if names.size > 1 && names.first.empty?

  names.inject(Object) do |constant, name|
    if constant == Object
      constant.const_get(name)
    else
      candidate = constant.const_get(name)
      next candidate if constant.const_defined?(name, false)
      next candidate unless Object.const_defined?(name)

      # Go down the ancestors to check it it's owned
      # directly before we reach Object or the end of ancestors.
      constant = constant.ancestors.inject do |const, ancestor|
        break const    if ancestor == Object
        break ancestor if ancestor.const_defined?(name, false)
        const
      end

      # owner is in Object, so raise
      constant.const_get(name, false)
    end
  end
end
models() click to toggle source
# File lib/schoolkeep/scribble.rb, line 104
def models
  @models ||= {}
end
register(class_name, boolean: true, &block) click to toggle source
# File lib/schoolkeep/scribble.rb, line 108
def register(class_name, boolean: true, &block)
  models[class_name.to_s] = [boolean, block]
end
register_model(class_name, boolean, block) click to toggle source
# File lib/schoolkeep/scribble.rb, line 75
def register_model(class_name, boolean, block)
  ::Scribble::Registry.instance.class_names.delete_if do |klass, name|
    name == class_name
  end

  ::Scribble::Registry.instance.methods.reject! do |method|
    method.receiver_class.name == class_name
  end

  klass = constantize(class_name)

  ::Scribble::Registry.for klass do
    name class_name
    to_boolean { boolean }

    # Logical operators
    method :or,  Object, cast: 'to_boolean'
    method :and, Object, cast: 'to_boolean'

    # Equality
    method :equals,  klass, as: '=='
    method :differs, klass, as: '!='
    method :equals,  Object, returns: false
    method :differs, Object, returns: true
  end

  ::Scribble::Registry.for klass, &block
end