Sha256: d53c416b1fdd5be83fc0a0a58b826fca36cedc3317c75616e2d88ab6219c0d07

Contents?: true

Size: 797 Bytes

Versions: 4

Compression:

Stored size: 797 Bytes

Contents

require 'yaml'

# This module provides the class methods that render a structure
# static, where records are sourced from a YAML file.
class Structure
  module Static
    include Enumerable

    def self.extended(base)
      base.key(:_id, Integer)
    end

    # The data file path.
    attr :data_path

    # Returns all records.
    def all
      @all ||= YAML.load_file(data_path).map do |hsh|
        hsh['_id'] ||= hsh.delete('id') || hsh.delete('ID') || incr_id
        new(hsh)
      end
    end

    # Yields each record to given block.
    def each(&block)
      all.each { |item| block.call(item) }
    end

    # Finds a record by its ID.
    def find(id)
      super() { |item| item._id == id }
    end

    private

    def incr_id
      @id_cnt = @id_cnt.to_i + 1
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
structure-0.18.0 lib/structure/static.rb
structure-0.17.3 lib/structure/static.rb
structure-0.17.2 lib/structure/static.rb
structure-0.17.1 lib/structure/static.rb