ruby 脚本在本地快速安装所有谷歌webfonts(减去IM Fell)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 脚本在本地快速安装所有谷歌webfonts(减去IM Fell)相关的知识,希望对你有一定的参考价值。
# download all the Google web fonts and install into $HOME/Library/Fonts/
require 'rubygems'
require 'curb'
require 'hpricot'
require 'yaml'
class FontLoader
attr_accessor :doc
def initialize(html)
self.doc = Hpricot html
end
def locate
(doc/'div.download li a').select do|anchor|
anchor['href']
end.map {|anchor| anchor['href'] }
end
def name
doc.at('body h2').inner_text
end
end
class FontIndexer
attr_accessor :doc
def initialize(html)
self.doc = Hpricot html
end
def locate
(doc/'#fontlist a.previewwrapper').select do|anchor|
anchor['href']
end.map {|anchor| anchor['href'] }
end
end
class FontCrawler
attr_accessor :http, :indexer, :fonts
def initialize
self.http = Curl::Easy.new("http://code.google.com/webfonts")
end
def prepare
self.http.http_get
self.indexer = FontIndexer.new(self.http.body_str)
puts "index page loaded"
self.http.reset
end
def fetch
baseurl = "http://code.google.com"
self.fonts = {}
list = self.indexer.locate.map {|absurl| baseurl + absurl }
puts "located #{list.size} fonts"
puts list.inspect
Curl::Multi.get(list, :follow_location => true) do|handle|
loader = FontLoader.new(handle.body_str)
fonts[loader.name] = loader.locate.map {|absurl| baseurl + absurl }
end
puts "#{fonts.size} fonts located saved to fontindex.yml"
# checkpoint
File.open("fontindex.yml","wb") do|f|
f << YAML.dump(fonts)
end
end
def install(fontdir)
fonts = YAML.load_file("fontindex.yml")
urls = fonts.map {|k,v| v.first }.compact
paths = []
Curl::Multi.download(urls) do|handle, path|
puts handle.header_str
filename = handle.header_str.split("\n").select{|hdr| hdr.strip.match(/Content-Disposition:/) }.first.gsub(/.*filename=/,'').gsub(/["']/,'').strip
content_type = handle.header_str.split("\n").select{|hdr| hdr.strip.match(/Content-Type:/) }.first.split(':').last.strip
if content_type == 'font/ttf'
encoding = handle.header_str.split("\n").select{|hdr| hdr.strip.match(/Content-Encoding:/) }.first.split(':').last.strip
filename += '.gz'
end
# prefix google fonts
filename = "Google-#{filename}"
puts "downloaded #{path}!"
downloaded = "#{fontdir}/#{filename}"
paths << downloaded
cmd = "/bin/mv #{path} #{downloaded}"
puts cmd.inspect
system(cmd)
end
puts "installing"
paths.each do|file|
if file.match(/.zip/)
cmd = "cd #{fontdir} && unzip '#{File.basename(file)}' && rm '#{File.basename(file)}'"
puts cmd.inspect
system(cmd)
elsif file.match(/.gz/)
cmd = "cd #{fontdir} && gzip -d '#{File.basename(file)}'"
puts cmd.inspect
system(cmd)
end
end
puts "fonts installed!"
end
def self.install(fontdir)
crawler = self.new
crawler.prepare
crawler.fetch
crawler.install(fontdir)
end
end
FontCrawler.install File.join(ENV["HOME"], "Library/Fonts")
以上是关于ruby 脚本在本地快速安装所有谷歌webfonts(减去IM Fell)的主要内容,如果未能解决你的问题,请参考以下文章