How do I dynamically check to see if a remote font

2019-09-11 22:38发布

问题:

I am using these Devicon font icons for various programming languages.

They don't have every icon, but they have most.

What I want to do is to have a default icon I use for the languages that this font library does not support.

These are their instructions:

<!-- in your header -->
<link rel="stylesheet" href="https://cdn.rawgit.com/konpa/devicon/master/devicon.min.css">

<!-- in your body -->
<i class="devicon-ruby-plain"></i>

So in my view, I have this:

        <div class="vote-icon">
          <i class="devicon-<%= question.language %>-plain"></i>
        </div>

Where question.language is a user-submitted language on their question.

Right now, when this generates a non-existent icon it just leaves a blank space there.

But I am not quite sure how to check to see if the icon exists, before replacing it with a default.

Thoughts?

回答1:

So the only way for me to actually do this is to parse the list of icons available from Devicons.

So I manually created a list in an array in a helper method and then did the nil checks in there.

So it looks like this:

  def language_icon(language)
    devicons = ["amazonwebservices", "android", "angularjs", "apache", "appcelerator", "apple", "atom", "backbonejs",
      "bitbucket", "bootstrap", "bower", "c", "chrome", "codeigniter", "coffeescript", "confluence", "cplusplus", "csharp",
      "css3", "d3js", "debian", "django", "docker", "doctrine", "dot-net", "drupal", "erlang", "firefox", "foundation", "gimp",
      "git", "github", "gitlab", "go", "grunt", "gulp", "heroku", "html5", "ie10", "illustrator", "inkscape", "java", "javascript",
      "jeet", "jetbrains", "jquery", "krakenjs", "laravel", "less", "linux", "meteor", "mongodb", "moodle", "mysql", "nginx",
      "nodejs", "nodewebkit", "orale", "photoshop", "php", "phpstorm", "postgresql", "python", "rails", "react", "redhat", "redis",
      "ruby", "safari", "sass", "sourcetree", "ssh", "symfony", "travis", "trello", "ubuntu", "vim", "windows8", "wordpress", "yii", "zend"]

    if devicons.include?(language)
      content_tag(:i, "", class: "devicon-#{language}-plain")
    else
      content_tag(:i, "", class: "fa fa-diamond")
    end
  end

That works like a charm.

I hope this helps someone else!



回答2:

try this

require 'open-uri'
=> true
f = open("https://cdn.rawgit.com/konpa/devicon/master/devicon.min.css").read
...load entire css file ...

then you make a search

@icon = f["devicon-css3-plain"]

if @icon is nil it mean that icon no longer exist

in you case

 @icon = f[question.language]