Class: FaviconGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Defined in:
lib/generators/favicon_generator.rb

Constant Summary collapse

API_KEY =
'04641dc33598f5463c2f1ff49dd9e4a617559f4b'
PATH_UNIQUE_KEY =
'/Dfv87ZbNh2'

Instance Method Summary collapse

Instance Method Details

#generate_faviconObject


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/generators/favicon_generator.rb', line 15

def generate_favicon
  if File.exist?('config/favicon.yml') && defined?(Rails.application.config_for)
    req = Rails.application.config_for(:favicon)
  else
    req = JSON.parse File.read('config/favicon.json')
  end

  req['api_key'] = API_KEY

  req['files_location'] = Hash.new
  req['files_location']['type'] = 'path'
  req['files_location']['path'] = PATH_UNIQUE_KEY

  master_pic = File.expand_path(".") + '/' + req['master_picture']
  req['master_picture'] = Hash.new
  req['master_picture']['type'] = 'inline'
  req['master_picture']['content'] = Base64.encode64(File.binread(master_pic))

  uri = URI.parse("https://realfavicongenerator.net/api/favicon")
  timeout = options[:timeout]
  resp = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https", read_timeout: timeout) do |http|
    request = Net::HTTP::Post.new uri
    request.body = { favicon_generation: req }.to_json
    request["Content-Type"] = "application/json"
    begin
      JSON.parse(http.request(request).body)
    rescue Net::ReadTimeout
      raise RuntimeError.new("Operation timed out after #{timeout} seconds, pass a `-t` option for a longer timeout")
    end
  end

  zip = resp['favicon_generation_result']['favicon']['package_url']
  FileUtils.mkdir_p('app/assets/images/favicon')

  Dir.mktmpdir 'rfg' do |tmp_dir|
    download_package zip, tmp_dir
    Dir["#{tmp_dir}/*.*"].each do |file|
      content = File.binread(file)
      new_ext = ''
      if File.extname(file) == '.json' or File.extname(file) == '.xml' or File.extname(file) == '.webmanifest'
        content = replace_url_by_asset_path content
        new_ext = '.erb'
      end
      create_file "app/assets/images/favicon/#{File.basename file}#{new_ext}", content
    end
  end

  create_file "app/views/application/_favicon.html.erb",
    replace_url_by_asset_path(resp['favicon_generation_result']['favicon']['html_code'])

    create_file "config/initializers/web_app_manifest.rb",
      File.read(File.dirname(__FILE__) + '/web_app_manifest_initializer.txt')
end