Class: ReVIEW::Book::Index

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

Defined Under Namespace

Classes: Item

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(items) ⇒ Index

Returns a new instance of Index.



47
48
49
50
51
52
53
54
55
# File 'lib/review/book/index.rb', line 47

def initialize(items)
  @items = items
  @index = {}
  items.each do |i|
    warn "warning: duplicate ID: #{i.id} (#{i})" unless @index[i.id].nil?
    @index[i.id] = i
  end
  @image_finder = nil
end

Class Method Details

.item_classObject



37
38
39
# File 'lib/review/book/index.rb', line 37

def Index.item_class
  self::Item
end

.parse(src, *args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/review/book/index.rb', line 20

def Index.parse(src, *args)
  items = []
  seq = 1
  src.grep(%r<^//#{item_type()}>) do |line|
    if id = line.slice(/\[(.*?)\]/, 1)
      items.push item_class().new(id, seq)
      seq += 1
      if id == ""
        warn "warning: no ID of #{item_type()} in #{line}"
      end
    end
  end
  new(items, *args)
end

Instance Method Details

#[](id) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/review/book/index.rb', line 57

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

  @items.each do |i|
    if i.id.split(/\|/).include?(id)
      return i
    end
  end
  raise KeyError, "not found key '#{id}' for #{self.class}"
end

#each(&block) ⇒ Object



78
79
80
# File 'lib/review/book/index.rb', line 78

def each(&block)
  @items.each(&block)
end

#has_key?(id) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/review/book/index.rb', line 82

def has_key?(id)
  return @index.has_key?(id)
end

#item_typeObject



43
44
45
# File 'lib/review/book/index.rb', line 43

def item_type
  self.class.item_type
end

#number(id) ⇒ Object



74
75
76
# File 'lib/review/book/index.rb', line 74

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