lib/humanize_fraction/humanizer.rb in humanize_fraction-0.1.1 vs lib/humanize_fraction/humanizer.rb in humanize_fraction-0.1.2
- old
+ new
@@ -1,28 +1,17 @@
module HumanizeFraction
class Humanizer
- # From: https://github.com/thechrisoshow/fractional/blob/master/lib/fractional.rb
- SINGLE_FRACTION = /\A\s*(\-?\d+)\/(\-?\d+)\s*\z/
- MIXED_FRACTION = /\A\s*(\-?\d*)\s+(\d+)\/(\d+)\s*\z/
-
# Numbers that should be prefixed with `a` instead of `an` even though they
# start with a vowel.
NUMBERS_STARTING_WITH_SILENT_VOWEL = [
"one",
]
attr_reader :numerator, :denominator, :whole_part
+ sig [{numerator: Integer, denominator: Integer, whole_part: [NilClass, Integer]}],
def initialize(numerator:, denominator:, whole_part: nil)
- [numerator, denominator].each do |number|
- if !number.is_a?(Integer)
- raise ArgumentError, "Expected Integers for numerator/denominator but got #{number.class.name}"
- end
- end
- if !whole_part.nil? && !whole_part.is_a?(Integer)
- raise ArgumentError, "Expected Integer or NilClass for whole_part but got #{whole_part.class.name}"
- end
@whole_part = whole_part
@numerator = numerator
@denominator = denominator
end
@@ -33,23 +22,14 @@
words << humanize_numerator(humanized_denominator, shorthand: shorthand)
words << humanized_denominator
words.join(" ")
end
+ sig_self [String, Hash],
def self.from_string(string, options = {})
- if !string.is_a?(String)
- raise ArgumentError, "Expected String but got #{string.class.name}"
- end
- if string_is_mixed_fraction?(string)
- whole, numerator, denominator = string.scan(MIXED_FRACTION).flatten.map(&:to_i)
- new(whole_part: whole, numerator: numerator, denominator: denominator, **options)
- elsif string_is_single_fraction?(string)
- numerator, denominator = string.split("/").map(&:to_i)
- new(numerator: numerator, denominator: denominator, **options)
- else
- raise ArgumentError, "Unable to extract fraction from string #{string}"
- end
+ parser = FractionStringParser.new(string)
+ new(**parser.fraction_components, **options)
end
private
def humanize_whole_part
@@ -97,16 +77,8 @@
!NUMBERS_STARTING_WITH_SILENT_VOWEL.include?(humanized_number)
"an"
else
"a"
end
- end
-
- def self.string_is_mixed_fraction?(value)
- value&.match(MIXED_FRACTION)
- end
-
- def self.string_is_single_fraction?(value)
- value&.match(SINGLE_FRACTION)
end
end
end