Class: ReVIEW::Book::Index

Inherits:
Object show all
Includes:
Enumerable
Defined in:
lib/review/book/index.rb,
lib/review/book/index/item.rb

Defined Under Namespace

Classes: Item

Instance Method Summary collapse

Constructor Details

#initializeIndex

Returns a new instance of Index.



26
27
28
29
30
# File 'lib/review/book/index.rb', line 26

def initialize
  @index = {}
  @logger = ReVIEW.logger
  @image_finder = nil
end

Instance Method Details

#[](id) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/review/book/index.rb', line 46

def [](id)
  @index.fetch(id)
rescue StandardError
  index_keys = @index.keys.map { |i| i.split('|').last }.flatten # unfold all ids
  if index_keys.each_with_object(Hash.new(0)) { |i, h| h[i] += 1 }. # number of occurrences
     select { |k, v| k == id && v > 1 }.present? # detect duplicated
    raise KeyError, "key '#{id}' is ambiguous for #{self.class}"
  end

  @index.each_value do |item|
    if item.id.split('|').include?(id)
      return item
    end
  end
  raise KeyError, "not found key '#{id}' for #{self.class}"
end

#add_item(item) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/review/book/index.rb', line 36

def add_item(item)
  if @index[item.id] && self.class != ReVIEW::Book::IconIndex
    @logger.warn "warning: duplicate ID: #{item.id} (#{item.inspect})"
  end
  @index[item.id] = item
  if item.class != ReVIEW::Book::Chapter
    item.index = self
  end
end

#each(&block) ⇒ Object



67
68
69
# File 'lib/review/book/index.rb', line 67

def each(&block)
  @index.values.each(&block)
end

#item_typeObject



22
23
24
# File 'lib/review/book/index.rb', line 22

def item_type
  self.class.item_type
end

#key?(id) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


71
72
73
# File 'lib/review/book/index.rb', line 71

def key?(id)
  @index.key?(id)
end

#number(id) ⇒ Object



63
64
65
# File 'lib/review/book/index.rb', line 63

def number(id)
  self[id].number.to_s
end

#sizeObject



32
33
34
# File 'lib/review/book/index.rb', line 32

def size
  @index.size
end