class GoldMine::DB

Database of fortunes.

Example:

db = DB.new(path: "/home/user/fortunes")
db.random # => random fortune

Options:

:path

The path of database.

:comments

Pass true if allow comments is needed.

:delim

The character which is used as delimiter in a database.

Attributes

options[R]
path[R]

Public Class Methods

default_options() click to toggle source
# File lib/gold_mine/db.rb, line 20
def self.default_options
  @default_options ||= {
    delim: "%"
  }
end
new(options = {}) click to toggle source
# File lib/gold_mine/db.rb, line 28
def initialize(options = {})
  @path = options.fetch(:path, GoldMine.default_db_path)
  @options = self.class.default_options.merge(options)
end

Public Instance Methods

fortunes() click to toggle source
# File lib/gold_mine/db.rb, line 37
def fortunes
  @fortunes ||= read_fortunes
end
random() click to toggle source
# File lib/gold_mine/db.rb, line 33
def random
  fortunes.sample
end

Private Instance Methods

find_fortune(index) click to toggle source
# File lib/gold_mine/db.rb, line 43
def find_fortune(index)
  read_fortunes(offset: index, size: 1).first
end
read_fortunes(options = {}) click to toggle source
# File lib/gold_mine/db.rb, line 47
def read_fortunes(options = {})
  offset = options.fetch(:offset, 0)
  max_size = options.fetch(:size, Float::INFINITY)
  fortunes, text = [], ""

  File.open(@path, "r") do |file|
    file.seek(offset)
    file.each_line do |line|
      break if fortunes.size == max_size

      if @options[:comments]
        next if line[/^#{@options[:delim]*2}/]
      end

      if line[/^#{@options[:delim]}/] || file.eof?
        text << line if file.eof?
        fortunes << Fortune.new(text) unless text.chomp.empty?
        text.clear
        next
      end

      text << line
    end
  end

  fortunes
end