2015-02-09 124 views
1

我安裝的寶石:https://github.com/benmanns/tinypng軌回形針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

解決

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 
0

它在你的before_save失敗和tiny_png_api_keynil

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 
+0

我有tiny_png_api_key。只是隱藏它。因爲我想要支付專業帳戶小小的PNG。對不起,如果它誤導了你。 – Legendary 2015-02-09 15:02:13

+0

@Legendary,我要說的是,確保你的密鑰進入。在密鑰 – AnkitG 2015-02-09 15:03:15

+0

上執行'logger.info'我有| client = TinyPNG :: Client.new('API_KEY_STRING_HERE')|沒有變數 – Legendary 2015-02-09 15:04:44