Module: CarrierWave::TinyPNG

Defined in:
lib/carrierwave/tinypng.rb,
lib/carrierwave/tinypng.rb,
lib/carrierwave/tinypng/version.rb

Defined Under Namespace

Classes: Configuration, Railtie

Constant Summary collapse

VERSION =
'0.0.2'

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.configurationObject



12
13
14
# File 'lib/carrierwave/tinypng.rb', line 12

def self.configuration
  @configuration ||= CarrierWave::TinyPNG::Configuration.new
end

.configure {|configuration| ... } ⇒ Object

Yields:



8
9
10
# File 'lib/carrierwave/tinypng.rb', line 8

def self.configure
  yield configuration
end

Instance Method Details

#tinypngObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/carrierwave/tinypng.rb', line 20

def tinypng
  cache_stored_file! if !cached?

  key = CarrierWave::TinyPNG.configuration.key
  input = current_path
  output = current_path

  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))
  json = JSON.parse(response.body, :symbolize_names => true) || {}
  if response.code == '201'
    File.binwrite(output, http.get(response['location']).body)
  else
    raise CarrierWave::ProcessingError,
          I18n.translate(:'errors.messages.tinypng_processing_error',
                         :error => json[:error],
                         :message => json[:message],
                         :default => I18n.translate(:'errors.messages.tinypng_processing_error',
                                                    :locale => :en))
  end
end