module MiniModel::ClassMethods

Public Instance Methods

all() click to toggle source
# File lib/minimodel.rb, line 44
def all
  index.values
end
count() click to toggle source
# File lib/minimodel.rb, line 48
def count
  index.length
end
find(primary_key, &block) click to toggle source
# File lib/minimodel.rb, line 90
def find(primary_key, &block)
  index.fetch(primary_key, &block)
end
indexed_by(primary_key, options = {}) click to toggle source
# File lib/minimodel.rb, line 56
def indexed_by(primary_key, options = {})
  @primary_key = primary_key

  @auto_increment = options[:auto_increment] ? 1 : nil
end
insert(attributes) click to toggle source
# File lib/minimodel.rb, line 72
def insert(attributes)
  unless @auto_increment.nil?
    attributes[primary_key] = @auto_increment

    @auto_increment += 1
  end

  object = new(attributes)

  pkey = object.send(primary_key)

  if index.key?(pkey)
    raise DuplicateKeyError
  end

  index[pkey] = object
end
keys() click to toggle source
# File lib/minimodel.rb, line 62
def keys
  all.map(&primary_key)
end
load_from(path) click to toggle source
# File lib/minimodel.rb, line 94
def load_from(path)
  YAML.load_file(path).each do |key, attrs|
    insert symbolize_keys(attrs, primary_key => key)
  end
end
options(text_attribute) click to toggle source
# File lib/minimodel.rb, line 66
def options(text_attribute)
  all.each_with_object({}) do |model, hash|
    hash[model.read_attribute(text_attribute)] = model.read_attribute(primary_key)
  end
end
primary_key() click to toggle source
# File lib/minimodel.rb, line 52
def primary_key
  @primary_key
end

Private Instance Methods

index() click to toggle source
# File lib/minimodel.rb, line 108
def index
  @index ||= {}
end
symbolize_keys(hash, initial_value=nil) click to toggle source
# File lib/minimodel.rb, line 102
def symbolize_keys(hash, initial_value=nil)
  hash.inject(initial_value) do |tmp, (k, v)|
    tmp.merge(k.to_sym => v)
  end
end