Skip to content

Commit

Permalink
Look for favicons in assets directory
Browse files Browse the repository at this point in the history
  • Loading branch information
daz committed Nov 7, 2014
1 parent 49048e7 commit 9793675
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 18 deletions.
4 changes: 3 additions & 1 deletion lib/app.rb
@@ -1,6 +1,8 @@
require 'pathname'

class App
attr_reader :path

def initialize(path)
@path = path
end
Expand All @@ -19,6 +21,6 @@ def dead?
end

def favicon
Favicon.new(@path).source
Favicon.new(self)
end
end
44 changes: 28 additions & 16 deletions lib/favicon.rb
@@ -1,21 +1,25 @@
require 'base64'

class Favicon
def initialize(app_root)
locate(app_root)
SEARCH_PATHS = %w(app/assets/images app/assets assets public/images public)
EXTENSIONS = %w(png gif ico)
DEFAULT_PATH = '/default_favicon.png'

def initialize(app)
@app = app
locate
end

def source
def url
if exists?
"data:#{mime_type};base64,#{data}"
data_uri
else
'/default_favicon.png'
DEFAULT_PATH
end
end

# Base 64 encoding of the favicon
def data
Base64.encode64(File.open(@path, 'r').read).gsub(/\n/, '')
def data_uri
"data:#{mime_type};base64,#{data}"
end

# Mime type of favicon
Expand All @@ -24,18 +28,26 @@ def mime_type
Rack::Mime.mime_type(File.extname(@path))
end

# Returns true unless we can't find a favicon or if favicon file is empty
def exists?
File.size?(@path).to_i != 0
!!@path
end

private

# Look in [app path]/public/ for a favicon file
def locate(app_root)
%w[png gif ico].each do |ext|
@path = File.join(app_root, 'public', "favicon.#{ext}")
break if exists?
# Look in `SEARCH_PATHS` for a non-empty favicon file with extension in `EXTENSIONS`
def locate
return if @app.dead?
files = EXTENSIONS.map { |ext| "favicon.#{ext}"}
paths = SEARCH_PATHS.product(files).map { |path| File.join(@app.path, path[0], path[1]) }
paths.each do |path|
next if File.size?(path).to_i == 0
@path = path
break
end
end

# Base 64 encoding of the favicon
def data
Base64.encode64(File.open(@path, 'r').read).gsub(/\n/, '')
end
end
end
2 changes: 1 addition & 1 deletion views/layout.html.erb
Expand Up @@ -11,7 +11,7 @@
<% @apps.each do |app| %>
<li>
<a<%= ' class="dead"' if app.dead? %> href="<%= app.url %>">
<img class="favicon" src="<%= app.favicon %>" width="16" height="16">
<img class="favicon" src="<%= app.favicon.url %>" width="16" height="16">
<%= app.name %>
</a>
</li>
Expand Down

0 comments on commit 9793675

Please sign in to comment.