Skip to content

Instantly share code, notes, and snippets.

@calvincorreli
Created September 5, 2011 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calvincorreli/1195773 to your computer and use it in GitHub Desktop.
Save calvincorreli/1195773 to your computer and use it in GitHub Desktop.
Glyphicons rake task and helpers
link_to_glyphicon(:edit, edit_admin_product_coupon_path(@product, coupon))
glyphicon(:move, :class => 'drag_handle', :title => "Drag to reorder", :variant => :halfling)
namespace :misc do
task :glyphs => :environment do
glyphs = []
longest_name = 0
Dir.glob(File.join(Rails.root, "public/images/glyphicons/*.png")) do |path|
width, height = `identify -format "%wx%h" #{path}`.strip.split(/x/)
# glyphicons_083_random.png
# glyphicons_083_random@2x.png
# glyphicons_halflings_047_bold.png
path.match(/\/(glyphicons_(halflings_)?(\d+)_([^.@]+)(@2x)?)\.png$/)
filename, halfling, num, name, x2 = $1, $2, $3, $4, $5
name = name + "_" + (halfling.present? ? 'halfling' : x2.present? ? 'x2' : 'normal')
glyphs << { :name => name, :num => num, :width => width, :height => height, :filename => filename }
len = name.length
longest_name = len if len > longest_name
end
File.open(File.join(Rails.root, "glyphs.rb"), "w") do |f|
f.write(" GLYPHICONS = {\n")
f.write(glyphs.map {|glyph| " '#{glyph[:name]}' #{" " * (longest_name - glyph[:name].length)} => [#{'%2d' % glyph[:width]}, #{'%2d' % glyph[:height]}, '#{glyph[:filename]}']" }.join(",\n"))
f.write("\n }\n")
end
end
end
module GlyphiconsHelper
# options:
# :variant = :normal, :halfling, :x2
def glyphicon(name, options = {})
variant = (options.delete(:variant).presence || 'normal').to_s
width, height, filename = GLYPHICONS["#{name}_#{variant}"]
divisor = variant == 'normal' ? 1.5 : 1
image_tag(
"glyphicons/#{filename}.png",
options.merge(:size => "#{(width.to_f/divisor).round}x#{(height.to_f/divisor).round}", :class => ['glyphicon', options.delete(:class)].compact.join(" "))
)
end
def link_to_glyphicon(name, *args)
options = args.last.is_a?(Hash) ? args.last.dup : {}
if options[:class].present?
options[:class] += " glyphicon"
else
options[:class] = "glyphicon"
end
variant = options.delete(:variant) || :normal
args[args.length - 1] = options if args.last.is_a?(Hash)
link_to(glyphicon(name, :variant => variant), *args)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment