Skip to content

Instantly share code, notes, and snippets.

@fnando
Last active December 5, 2021 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fnando/f72a15f5fc9bdbc2932c19963153bb42 to your computer and use it in GitHub Desktop.
Save fnando/f72a15f5fc9bdbc2932c19963153bb42 to your computer and use it in GitHub Desktop.
Simplistic approach to calculate image aspect ratio
# frozen_string_literal: true
class AspectRatio
attr_reader :width, :height
def initialize(width, height)
@width = width
@height = height
end
def aspect_ratio
@aspect_ratio ||= Rational(width, height).to_s.tr("/", ":")
end
def orientation
@orientation ||= width >= height ? :landscape : :portrait
end
def portrait?
orientation == :portrait
end
def landscape?
!portrait?
end
end
def AspectRatio(width, height) # rubocop:disable Naming/MethodName
AspectRatio.new(width, height)
end
if $PROGRAM_NAME == __FILE__
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "minitest-utils"
end
require "minitest"
require "minitest/autorun"
require "minitest/utils"
class AspectRatioTest < Minitest::Test
[
[1920, 1080, "16:9", :landscape],
[3840, 2160, "16:9", :landscape],
[2160, 3840, "9:16", :portrait],
[500, 500, "1:1", :landscape],
[600, 400, "3:2", :landscape],
[400, 600, "2:3", :portrait]
].each do |(width, height, aspect_ratio, orientation)|
test "detects #{width}x#{height} as #{aspect_ratio}" do
info = AspectRatio(width, height)
assert_equal aspect_ratio, info.aspect_ratio
assert_equal orientation, info.orientation
end
end
test "detects portrait aspect ratio" do
assert AspectRatio(1080, 1920).portrait?
refute AspectRatio(1080, 1920).landscape?
end
test "detects landscape aspect ratio" do
assert AspectRatio(1920, 1080).landscape?
refute AspectRatio(1920, 1080).portrait?
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment