Class: SmartImage::RatioCalculator

Inherits:
Object
  • Object
show all
Defined in:
lib/smart_image/ratio_calculator.rb

Defined Under Namespace

Classes: Size

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RatioCalculator

Create a new RatioCalculator object with the given options



4
5
6
# File 'lib/smart_image/ratio_calculator.rb', line 4

def initialize(options = {})
  @options = options
end

Instance Method Details

#size(options = {}) ⇒ Object

Calculate the resulting size given a particular set of contraints



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/smart_image/ratio_calculator.rb', line 9

def size(options = {})
  opts = @options.merge(options)

  source = Size.new opts[:source_width], opts[:source_height]
  bounds = Size.new opts[:dest_width],   opts[:dest_height]

  # Calculate what the width would be if we matched the dest height
  naive_width = bounds.height * source.aspect_ratio

  # If it fits, use it!
  if naive_width <= bounds.width
    width  = naive_width
    height = naive_width / source.aspect_ratio
  # Otherwise, the height must fit
  else
    height = bounds.width / source.aspect_ratio
    width  = height * source.aspect_ratio
  end

  return Size.new(width, height)
end