Class: ZenAndMusashi::Store
- Inherits:
-
Object
- Object
- ZenAndMusashi::Store
- Defined in:
- lib/zen_and_musashi/store.rb
Constant Summary collapse
- DB_DIR =
File.join(Dir.home, '.config', 'zen-and-musashi')
- DB_PATH =
File.join(DB_DIR, 'quotes.db')
Instance Method Summary collapse
- #add(mode, text) ⇒ Object
- #all(mode) ⇒ Object
- #clear(mode) ⇒ Object
- #count(mode) ⇒ Object
-
#initialize ⇒ Store
constructor
A new instance of Store.
- #random(mode) ⇒ Object
- #remove(mode, id) ⇒ Object
- #seed(data) ⇒ Object
Constructor Details
Instance Method Details
#add(mode, text) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/zen_and_musashi/store.rb', line 29 def add(mode, text) @pstore.transaction do mode_key = mode.to_s quotes = @pstore[mode_key] || [] # 重複チェック raise "That quote already exists in #{mode} mode." if quotes.any? { |q| q[:text].casecmp(text).zero? } # 文字数制限チェック(200文字) raise 'Quote is too long. Maximum 200 characters.' if text.length > 200 new_id = (quotes.map { |q| q[:id] }.max || 0) + 1 quotes << { id: new_id, text: text, type: 'composed' } @pstore[mode_key] = quotes new_id end end |
#all(mode) ⇒ Object
16 17 18 19 20 |
# File 'lib/zen_and_musashi/store.rb', line 16 def all(mode) @pstore.transaction(true) do @pstore[mode.to_s] || [] end end |
#clear(mode) ⇒ Object
85 86 87 88 89 |
# File 'lib/zen_and_musashi/store.rb', line 85 def clear(mode) @pstore.transaction do @pstore[mode.to_s] = [] end end |
#count(mode) ⇒ Object
63 64 65 |
# File 'lib/zen_and_musashi/store.rb', line 63 def count(mode) all(mode).length end |
#random(mode) ⇒ Object
22 23 24 25 26 27 |
# File 'lib/zen_and_musashi/store.rb', line 22 def random(mode) quotes = all(mode) return nil if quotes.empty? quotes.sample end |
#remove(mode, id) ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/zen_and_musashi/store.rb', line 48 def remove(mode, id) @pstore.transaction do mode_key = mode.to_s quotes = @pstore[mode_key] || [] idx = quotes.index { |q| q[:id] == id } raise "Quote ID #{id} not found in #{mode} mode." unless idx quotes.delete_at(idx) @pstore[mode_key] = quotes true end end |
#seed(data) ⇒ Object
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
# File 'lib/zen_and_musashi/store.rb', line 67 def seed(data) @pstore.transaction do data.each do |mode_key, quotes_array| existing = @pstore[mode_key.to_s] || [] quotes_array.each do |quote_hash| # 重複チェック next if existing.any? { |q| q[:text].casecmp(quote_hash[:text]).zero? } new_id = (existing.map { |q| q[:id] }.max || 0) + 1 existing << { id: new_id, text: quote_hash[:text], type: quote_hash[:type] || 'composed' } end @pstore[mode_key.to_s] = existing end end end |