module Rootage::CollectionInterface

CollectionInterface provides the way to create item colloction modules.

@example

module NewCollection
  extend CollectionInterface
  set_item_class SomeItem

  define(:foo) do |item|
    item.desc = "Test item"
    item.process { puts "bar" }
  end
end

Attributes

table[R]

Public Class Methods

included(sub) click to toggle source
# File lib/rootage/core.rb, line 151
def self.included(sub)
  sub.instance_variable_set(:@__item_class__, @__item_class__)
  sub.instance_eval do
    @__item_class

    def set_item_class(klass)
      @__item_class__ = klass
    end

    def self.item_class
      @__item_class__ || (raise NotImplemented)
    end
  end

  def sub.extended(_sub)
    _sub.instance_variable_set(:@__item_class__, @__item_class__)
    _sub.instance_variable_set(:@table, Hash.new)
  end

  def sub.inherited(_sub)
    super
    _sub.instance_variable_set(:@__item_class__, @__item_class__)
  end
end
item_class() click to toggle source
# File lib/rootage/core.rb, line 160
def self.item_class
  @__item_class__ || (raise NotImplemented)
end

Public Instance Methods

define(item, &block) click to toggle source

Define a item in the collection. If ‘name` is a symbol, new item is defined. If `name` is item object, use it.

@param item [Symbol]

item or item name

@yieldparam item [Item]

a new item

@return [Item]

the defined item
# File lib/rootage/core.rb, line 185
def define(item, &block)
  # setup the item
  case item
  when Symbol
    _item = item_class.new
    _item.name = item
  when Item
    _item = item.copy
  else
    raise ArgumentError.new(item)
  end

  if block_given?
    block.call(_item)
  end

  # push it to item table
  if table.has_key?(_item.name)
    raise ArgumentError.new(_item.name)
  else
    table[_item.name] = _item
  end

  # define a getter method if this is a module
  if self.kind_of?(Module)
    singleton_class.send(:define_method, _item.name) {_item}
  end

  return _item
end
find_item(name) click to toggle source
# File lib/rootage/core.rb, line 216
def find_item(name)
  table[name]
end
set_item_class(klass) click to toggle source
# File lib/rootage/core.rb, line 156
def set_item_class(klass)
  @__item_class__ = klass
end

Private Instance Methods

item_class() click to toggle source

Return the item class.

# File lib/rootage/core.rb, line 223
def item_class
  if klass = (@__item_class__ || self.class.instance_variable_get(:@__item_class__))
    klass
  else
    raise CollectionError.new("Item class not found for %s." % self)
  end
end