class Curio
A mixin to define enumerable maps
Version
Constants
- ConstraintError
- VERSION
Public Class Methods
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.
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 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 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 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
Hook called when module is included
@param [Class|Module] descendant
@return [undefined]
@api private
# File lib/curio.rb, line 53 def included(descendant) super descendant.module_eval do include Enumerable include Methods end end