我安装了gem:https://github.com/benmanns/tinypng
在我班上:
has_attached_file :photo <...>
before_save :tiny_png_preprocessor
private
def tiny_png_preprocessor
image_file = File.open(self.photo.path)
client = TinyPNG::Client.new("#{tiny_png_api_key}") # tinypng api key
image = client.shrink(image_file.read)
image.input # => {"size"=>1234}
image.output # => {"depth"=>8, "size"=>567, "ratio"=>0.459, "url"=>"http://tinypng.org/api/shrink/out/example.png"}
temp_file = image.to_file # => #<File:/tmp/tinypng20120910-5552-aturxh.png>
self.photo = temp_file
end
我希望rake paperclip:refresh class=Photo
在回形针保存后预处理所有照片。我怎样才能做到这一点?
在rake任务后的我的控制台中:
rake aborted!
ArgumentError: wrong number of arguments (1 for 0)
/mtfck/new_tamir/app/models/photo.rb:30:in 'initialize'
/mtfck/new_tamir/app/models/photo.rb:30:in 'new'
/mtfck/new_tamir/app/models/photo.rb:30:in 'tiny_png_preprocessor'
答案 0 :(得分:0)
它&#39;您的before_save
失败,tiny_png_api_key
失败nil
TinyPNG::Client.new(nil)
ArgumentError: wrong number of arguments (1 for 0)
from (irb):2:in `initialize'
from (irb):2:in `new'
from (irb):2
from /Users/ankitgupta/.rvm/rubies/ruby
答案 1 :(得分:0)
解决
require 'net/https'
require 'uri'
has_attached_file :photo, :styles => { large: '471x589',
medium: '381x476',
small: '284x355',
thumb: '227x284'},
:default_url => '/images/:style/missing.png'
after_save :tiny_png_preprocessor
private
def tiny_png_preprocessor
key = '%%%API_KEY%%%'
arr = [:large, :medium, :small, :thumb, :original]
arr.each do |style|
input = self.photo.path(style)
output = input
uri = URI.parse('https://api.tinypng.com/shrink')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request.basic_auth('api', key)
response = http.request(request, File.binread(input))
if response.code == '201'
File.binwrite(output, http.get(response['location']).body)
else
puts 'Compression failed'
end
end