Class: Storage

Inherits:
Object
  • Object
show all
Defined in:
lib/botemon/storage.rb

Overview

– Copyright© 2013 Giovanni Capuano <[email protected]>

This file is part of Botémon.

Botémon is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

Botémon is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with Botémon. If not, see <www.gnu.org/licenses/>. ++

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Storage

Returns a new instance of Storage.



23
24
25
26
27
28
# File 'lib/botemon/storage.rb', line 23

def initialize(file)
  @file = file
  @db = [].tap { |db|
    (File.exists?(file) ? JSON.load(File.read(file)) : []).each { |p| db << Smogon::Type::Pokemon.to_pokemon(p) }
  }
end

Instance Attribute Details

#dbObject

Returns the value of attribute db.



21
22
23
# File 'lib/botemon/storage.rb', line 21

def db
  @db
end

#fileObject

Returns the value of attribute file.



21
22
23
# File 'lib/botemon/storage.rb', line 21

def file
  @file
end

Instance Method Details

#add(pokemon) ⇒ Object Also known as: put



46
47
48
49
# File 'lib/botemon/storage.rb', line 46

def add(pokemon)
  return unless pokemon
  @db << pokemon unless is_cached?(pokemon.name)
end

#get(name) ⇒ Object



36
37
38
39
# File 'lib/botemon/storage.rb', line 36

def get(name)
  name = name.downcase
  @db.select { |p| p.name == name }.first
end

#get_allObject Also known as: dump



41
42
43
# File 'lib/botemon/storage.rb', line 41

def get_all
  @db
end

#is_cached?(name) ⇒ Boolean Also known as: include?

Returns:

  • (Boolean)


30
31
32
33
# File 'lib/botemon/storage.rb', line 30

def is_cached?(name)
  name = name.downcase
  @db.select { |p| p.name == name }.any?
end

#saveObject



52
53
54
55
56
57
58
59
# File 'lib/botemon/storage.rb', line 52

def save
  [].tap { |ary|
    @db.each { |p| ary << p.to_ary }
    File.open(@file, 'wb') { |f|
      f.write JSON.dump(ary)
    }
  }
end