Module: ReferenceBook::Library

Defined in:
lib/reference_book/library.rb

Class Method Summary collapse

Class Method Details

.[](key) ⇒ Object



24
25
26
# File 'lib/reference_book/library.rb', line 24

def [](key)
  shelf[key]
end

.array_for(attribute) ⇒ Object Also known as: pluck



60
61
62
63
64
# File 'lib/reference_book/library.rb', line 60

def array_for(attribute)
  shelf.map do |key, book|
    book[attribute] if book.respond_to?(attribute)
  end
end

.book_keysObject



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/reference_book/library.rb', line 45

def book_keys
  return @book_keys if @book_keys
  
  if index.any?
    @book_keys = shelf.map { |k, book| book.members }.flatten.uniq
    @book_keys.delete(:title)
    @book_keys.delete(:library_key)
    @book_keys
  else
    []
  end
end

.empty!Object



29
30
31
32
33
34
# File 'lib/reference_book/library.rb', line 29

def empty!
  index.each { |key| remove_accessor_for(key) }
  @index = []
  @shelf = {}
  nil
end

.hash_for(attribute) ⇒ Object Also known as: hash_pluck



68
69
70
71
72
73
74
# File 'lib/reference_book/library.rb', line 68

def hash_for(attribute)
  Hash[
    shelf.map do |key, book|
      [key, (book[attribute] if book.respond_to?(attribute))]
    end
  ]
end

.indexObject



19
20
21
# File 'lib/reference_book/library.rb', line 19

def index
  @index ||= []
end

.rotate(with_meta = false) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
# File 'lib/reference_book/library.rb', line 105

def rotate(with_meta = false)
  hash = Hash[
    book_keys.map do |book_k|
      [book_k, hash_for(book_k)]
    end
  ]

  if with_meta
    hash[:title] = hash_for(:title)
    hash[:library_key] = hash_for(:library_key)
  end

  hash
end

.shelfObject



14
15
16
# File 'lib/reference_book/library.rb', line 14

def shelf
  @shelf ||= {}
end

.store(book) ⇒ Object



4
5
6
7
8
9
10
11
# File 'lib/reference_book/library.rb', line 4

def store(book)
  verify_library_key!(book.library_key)

  shelf[book.library_key] = book
  index << book.library_key
  define_accessor_for(book)
  book
end

.to_h(with_meta = false) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/reference_book/library.rb', line 80

def to_h(with_meta = false)
  hash = {}

  shelf.each do |key, book|
    book_h = book.to_h
    
    unless with_meta
      book_h.delete(:title)
      book_h.delete(:library_key)
    end

    missing = book_keys - book_h.keys
    missing.each do |k|
      book_h[k] = nil
    end

    hash[key] = book_h
  end

  hash
end

.verify_library_key!(key) ⇒ Object



37
38
39
40
41
# File 'lib/reference_book/library.rb', line 37

def verify_library_key!(key)
  if is_key_in_use?(key)
    raise ReferenceBook::BookDefinitionError, "the library key '#{key}' is already in use."
  end
end