class MailProvider::SourceManager

Attributes

directory[R]
path[R]
total[R]

Public Class Methods

new(path = nil, directory = nil) click to toggle source
# File lib/mail_provider/source_manager.rb, line 7
def initialize(path = nil, directory = nil)
  @path = path || File.join(MailProvider::ROOT_DIR, 'sources.txt')
  @directory = directory || File.join(MailProvider::ROOT_DIR, 'sources')
  @missing = unavailable_sources
end

Public Instance Methods

run(refresh: false) click to toggle source
# File lib/mail_provider/source_manager.rb, line 13
def run(refresh: false)
  @missing = refresh ? sources : unavailable_sources
  download
  save

  sources # fetch sources again to update total count
end

Protected Instance Methods

download() click to toggle source
# File lib/mail_provider/source_manager.rb, line 23
def download
  return if @missing.empty?

  @missing.each do |key, url|
    puts "-> Downloading source: #{url}"
    body = Faraday.get(url).body
    File.open(File.join(@directory, "#{key}.txt"), 'w') { |f| f.puts body }
  end
end
save() click to toggle source
# File lib/mail_provider/source_manager.rb, line 33
def save
  return if @missing.empty?

  data = MailProvider::Parser.parse available_sources
  puts "-> free: #{data[:free].count}, disposable: #{data[:disposable].count}"
  MailProvider::Trie.create :free, data[:free], directory: @directory
  MailProvider::Trie.create :disposable, data[:disposable], directory: @directory
end

Private Instance Methods

available_sources() click to toggle source
# File lib/mail_provider/source_manager.rb, line 51
def available_sources
  files = Dir.glob(File.join(@directory, '*.txt'))
  files = files.select { |f| File.readable?(f) }
  files.map { |file| [File.basename(file, '.txt'), file] }.to_h
end
sources() click to toggle source
# File lib/mail_provider/source_manager.rb, line 44
def sources
  urls = File.readlines(@path).map(&:strip).reject { |line| line =~ /\A\#/ }
  data = urls.map { |url| [Digest::MD5.hexdigest(url), url] }.to_h
  @total = data.count
  data
end
unavailable_sources() click to toggle source
# File lib/mail_provider/source_manager.rb, line 57
def unavailable_sources
  available = available_sources
  sources.reject { |key, _| available.key?(key) }
end