Class: SwissKnife::SmushIt
- Inherits:
-
Object
- Object
- SwissKnife::SmushIt
- Defined in:
- lib/swiss_knife/smusher_it.rb
Constant Summary collapse
- ENDPOINT =
URI.parse("http://ws1.adq.ac4.yahoo.com/ysmush.it/ws.php")
- CONTENT_TYPE =
{ ".png" => "image/png", ".gif" => "image/gif", ".jpg" => "image/jpeg", ".jpeg" => "image/jpeg" }
- HOOKS =
{}
Class Method Summary collapse
- .compress(filepath) ⇒ Object
- .convert(from, to) ⇒ Object
- .convert_directory(source) ⇒ Object
- .on(hook, &block) ⇒ Object
Class Method Details
.compress(filepath) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/swiss_knife/smusher_it.rb', line 24 def self.compress(filepath) http = Net::HTTP.new(ENDPOINT.host, ENDPOINT.port) request = Net::HTTP::Post.new(ENDPOINT.request_uri) file_contents = File.read(filepath) boundary = Digest::SHA1.hexdigest(file_contents) request["Content-Type"] = "multipart/form-data, boundary=#{boundary}" request.body = [].tap do |body| body << "--#{boundary}" body << %[Content-Disposition: form-data; name="files[]"; filename="#{File.basename(filepath)}"] body << %[Content-Type: #{CONTENT_TYPE[File.extname(filepath).downcase]}\r\n] body << file_contents body << "--#{boundary}--\r\n" end.join("\r\n") response = http.request(request) return nil unless response.code == "200" JSON.load(response.body).tap do |info| HOOKS[:complete].each {|block| block[filepath, info]} end end |
.convert(from, to) ⇒ Object
46 47 48 49 50 |
# File 'lib/swiss_knife/smusher_it.rb', line 46 def self.convert(from, to) info = compress(from) return if info["error"] File.open(to, "wb+") {|file| file << open(info["dest"]).read } end |
.convert_directory(source) ⇒ Object
52 53 54 55 56 57 |
# File 'lib/swiss_knife/smusher_it.rb', line 52 def self.convert_directory(source) Dir["#{source}/**/*.{png,gif,jpg,jpeg}"].each do |filepath| p "converting #{filepath}" convert filepath, filepath end end |