class Curio

A mixin to define enumerable maps

Version

Constants

ConstraintError
VERSION

Public Class Methods

new(key, type = String, opts = { }.freeze) click to toggle source

Initialize a collection object with given key and type

:key will be used to determine which method to call on items to get their unique identifier when adding them to the collection.

:type will be used to determine how to coerce the input when calling methods on the collection.

@param [Symbol] key @param [Class] type

@return [undefined]

@api private

# File lib/curio.rb, line 31
def initialize(key, type = String, opts = { }.freeze)
  @key = key
  @type = type
  @hooks = []

  add_auto_increment_hook if opts[:auto_increment]

  define_key_method
  define_coerce_key_method
  define_hooks_method

  freeze
end

Private Instance Methods

add_auto_increment_hook() click to toggle source

Add auto increment hook.

This adds a hook that sets the item key to the next integer based on the collection count if no item key is available.

@return [undefined]

@api private

# File lib/curio.rb, line 70
def add_auto_increment_hook
  unless @type == Integer
    fail ConstraintError,
         'auto-increment requires a key type of Integer'
  end

  @hooks << lambda do |collection, item|
    return unless item.send(collection.key_method).nil?
    item.send(:"#{collection.key_method}=", collection.count + 1)
  end
end
define_coerce_key_method() click to toggle source

Define coerce_key based on @type

@return [undefined]

@api private

# File lib/curio.rb, line 111
def define_coerce_key_method
  type = @type
  define_method :coerce_key do |value|
    case type.to_s
    when 'String'  then value.to_s
    when 'Symbol'  then :"#{value}"
    when 'Integer' then value.to_i
    else value
    end
  end
end
define_hooks_method() click to toggle source

Define hooks based on @hooks

@return [Array]

@api private

# File lib/curio.rb, line 87
def define_hooks_method
  hooks = @hooks
  define_method :hooks do
    hooks
  end
end
define_key_method() click to toggle source

Define key_method based on @key

@return [undefined]

@api private

# File lib/curio.rb, line 99
def define_key_method
  key = @key
  define_method :key_method do
    key
  end
end
included(descendant) click to toggle source

Hook called when module is included

@param [Class|Module] descendant

@return [undefined]

@api private

Calls superclass method
# File lib/curio.rb, line 53
def included(descendant)
  super

  descendant.module_eval do
    include Enumerable
    include Methods
  end
end