Class: AbaNumbers::Database

Inherits:
Object
  • Object
show all
Defined in:
lib/aba_numbers/database.rb

Defined Under Namespace

Classes: Row

Constant Summary collapse

FEDERAL_URL =
'https://www.fededirectory.frb.org/fpddir.txt'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url = nil, path = nil) ⇒ Database

Returns a new instance of Database.



70
71
72
73
# File 'lib/aba_numbers/database.rb', line 70

def initialize(url = nil, path = nil)
  @url  = url || FEDERAL_URL
  @path = path || File.join(AbaNumbers::DB_PATH, 'fpddir.txt')
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



66
67
68
# File 'lib/aba_numbers/database.rb', line 66

def path
  @path
end

#urlObject (readonly)

Returns the value of attribute url.



66
67
68
# File 'lib/aba_numbers/database.rb', line 66

def url
  @url
end

Instance Method Details

#[](aba_number) ⇒ Object



115
116
117
# File 'lib/aba_numbers/database.rb', line 115

def [](aba_number)
  data[aba_number.to_s]
end

#dataObject



107
108
109
110
111
112
113
# File 'lib/aba_numbers/database.rb', line 107

def data
  if @data.nil?
    @data = {}
    reload
  end
  @data
end

#file?Boolean

Returns:

  • (Boolean)


75
76
77
# File 'lib/aba_numbers/database.rb', line 75

def file?
  File.file? path
end

#get_file_from_urlObject



83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/aba_numbers/database.rb', line 83

def get_file_from_url
  uri   = URI url
  https = Net::HTTP.new uri.host, uri.port

  if uri.scheme == 'https'
    https.use_ssl     = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE
  end

  res = https.request_get uri.request_uri
  File.open(path, 'w') { |f| f.puts res.body }
end

#line_countObject



79
80
81
# File 'lib/aba_numbers/database.rb', line 79

def line_count
  File.foreach(path).inject(0) { |c, _| c+1 }
end

#needs_getting_file?Boolean

Returns:

  • (Boolean)


119
120
121
# File 'lib/aba_numbers/database.rb', line 119

def needs_getting_file?
  !file? || line_count == 0
end

#read_local_fileObject



96
97
98
99
100
101
102
103
104
105
# File 'lib/aba_numbers/database.rb', line 96

def read_local_file
  data.clear
  File.open(path).each_line do |line|
    line.strip!
    unless line.empty?
      row                  = Row.new line
      data[row.aba_number] = row
    end
  end
end

#reloadObject



123
124
125
126
127
# File 'lib/aba_numbers/database.rb', line 123

def reload
  get_file_from_url if needs_getting_file?
  read_local_file
  @loaded = true
end