Class: IchigoIchie::Store
- Inherits:
-
Object
- Object
- IchigoIchie::Store
- Defined in:
- lib/ichigo_ichie/store.rb
Constant Summary collapse
- DB_DIR =
File.join(Dir.home, '.config', 'ichigo-ichie')
- DB_PATH =
File.join(DB_DIR, 'quotes.db')
Instance Method Summary collapse
- #add(text) ⇒ Object
- #all ⇒ Object
- #count ⇒ Object
- #get(index) ⇒ Object
-
#initialize ⇒ Store
constructor
A new instance of Store.
- #remove(id) ⇒ Object
- #seed(quotes_array) ⇒ Object
Constructor Details
Instance Method Details
#add(text) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/ichigo_ichie/store.rb', line 33 def add(text) @pstore.transaction do quotes = @pstore['quotes'] || [] raise 'That quote already exists.' if quotes.any? { |q| q[:text].casecmp(text).zero? } 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 } @pstore['quotes'] = quotes new_id end end |
#all ⇒ Object
16 17 18 19 20 |
# File 'lib/ichigo_ichie/store.rb', line 16 def all @pstore.transaction(true) do @pstore['quotes'] || [] end end |
#count ⇒ Object
22 23 24 |
# File 'lib/ichigo_ichie/store.rb', line 22 def count all.length end |
#get(index) ⇒ Object
26 27 28 29 30 31 |
# File 'lib/ichigo_ichie/store.rb', line 26 def get(index) quotes = all return nil if quotes.empty? quotes[index % quotes.length] end |
#remove(id) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/ichigo_ichie/store.rb', line 49 def remove(id) @pstore.transaction do quotes = @pstore['quotes'] || [] idx = quotes.index { |q| q[:id] == id } raise "Quote ID #{id} not found." unless idx quotes.delete_at(idx) @pstore['quotes'] = quotes true end end |
#seed(quotes_array) ⇒ Object
61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/ichigo_ichie/store.rb', line 61 def seed(quotes_array) @pstore.transaction do existing = @pstore['quotes'] || [] quotes_array.each do |text| next if existing.any? { |q| q[:text].casecmp(text).zero? } new_id = (existing.map { |q| q[:id] }.max || 0) + 1 existing << { id: new_id, text: text } end @pstore['quotes'] = existing end end |