Class: ConvertFont::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/convert_font/converter.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key, api_url, enable_cleanup = true) ⇒ Converter

Returns a new instance of Converter.



10
11
12
13
14
15
16
# File 'lib/convert_font/converter.rb', line 10

def initialize api_key, api_url, enable_cleanup = true
  @api_key = api_key
  @api_url = api_url
  @enable_cleanup = enable_cleanup

  self.set_default_request_headers
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



8
9
10
# File 'lib/convert_font/converter.rb', line 8

def api_key
  @api_key
end

#api_urlObject

Returns the value of attribute api_url.



8
9
10
# File 'lib/convert_font/converter.rb', line 8

def api_url
  @api_url
end

#enable_cleanupObject

Returns the value of attribute enable_cleanup.



8
9
10
# File 'lib/convert_font/converter.rb', line 8

def enable_cleanup
  @enable_cleanup
end

Instance Method Details

#convert(file, types, destination) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/convert_font/converter.rb', line 22

def convert file, types, destination
  destination << "/" if destination[-1] != "/"
  types.to_enum.with_index(0).each do |type, i|
    puts "Now converting: #{type}"
    response = Unirest.post @api_url, parameters: {"file" => File.new(file, "rb"), "format" => type.to_s}
    open("#{destination}temp_font_#{type.to_s}.tar.gz", "w") do |temp_file|
      temp_file.write(response.body)
    end
    extract("#{destination}temp_font_#{type.to_s}.tar.gz", destination);
    puts "#{type} converted."
  end
end

#extract(file, destination) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/convert_font/converter.rb', line 35

def extract file, destination
  destination << "/" if destination[-1] != "/"
  tar = Gem::Package::TarReader.new(Zlib::GzipReader.open(file))
  tar.rewind
  tar.each do |entry|
    if entry.file?
      names = entry.full_name.split("/")
      unless names.last.include? ".txt"
        open(destination + names.last, "wb") do |new_file|
          new_file.write(entry.read)
        end 
      end
    end
  end
  tar.close
  FileUtils.rm_rf file if @enable_cleanup
end

#set_default_request_headersObject



18
19
20
# File 'lib/convert_font/converter.rb', line 18

def set_default_request_headers
  Unirest.default_header('X-Mashape-Authorization', @api_key)
end