Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,5 @@ Metrics/PerceivedComplexity:
Enabled: false
Metrics/AbcSize:
Enabled: false
Layout/ExtraSpacing:
AllowForAlignment: false
38 changes: 13 additions & 25 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2024-09-01 18:40:26 UTC using RuboCop version 1.66.0.
# on 2025-12-28 23:46:28 UTC using RuboCop version 1.82.1.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 2
# Offense count: 1
Lint/BinaryOperatorWithIdenticalOperands:
Exclude:
- 'spec/ruby_units/unit_spec.rb'

# Offense count: 2
# Configuration parameters: EnforcedStyle, CheckMethodNames, CheckSymbols, AllowedIdentifiers, AllowedPatterns.
# SupportedStyles: snake_case, normalcase, non_integer
# AllowedIdentifiers: capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339, x86_64
# AllowedIdentifiers: TLS1_1, TLS1_2, capture3, iso8601, rfc1123_date, rfc822, rfc2822, rfc3339, x86_64
Naming/VariableNumber:
Exclude:
- 'spec/ruby_units/unit_spec.rb'
Expand All @@ -33,7 +33,7 @@ RSpec/BeforeAfterAll:
- '**/spec/support/**/*.rb'
- 'spec/ruby_units/temperature_spec.rb'

# Offense count: 95
# Offense count: 79
# Configuration parameters: Prefixes, AllowedPatterns.
# Prefixes: when, with, without
RSpec/ContextWording:
Expand All @@ -42,7 +42,7 @@ RSpec/ContextWording:
- 'spec/ruby_units/unit_spec.rb'
- 'spec/ruby_units/utf-8/unit_spec.rb'

# Offense count: 12
# Offense count: 13
# Configuration parameters: IgnoredMetadata.
RSpec/DescribeClass:
Exclude:
Expand All @@ -53,6 +53,7 @@ RSpec/DescribeClass:
- '**/spec/views/**/*'
- 'spec/ruby_units/bugs_spec.rb'
- 'spec/ruby_units/definition_spec.rb'
- 'spec/ruby_units/initialization_spec.rb'
- 'spec/ruby_units/temperature_spec.rb'
- 'spec/ruby_units/unit_spec.rb'

Expand Down Expand Up @@ -92,11 +93,11 @@ RSpec/MultipleDescribes:
Exclude:
- 'spec/ruby_units/unit_spec.rb'

# Offense count: 10
# Offense count: 30
RSpec/MultipleExpectations:
Max: 6

# Offense count: 59
# Offense count: 60
# Configuration parameters: EnforcedStyle, IgnoreSharedExamples.
# SupportedStyles: always, named_only
RSpec/NamedSubject:
Expand Down Expand Up @@ -134,29 +135,23 @@ RSpec/RepeatedExampleGroupDescription:
- 'spec/ruby_units/unit_spec.rb'

# Offense count: 1
# Configuration parameters: Include, CustomTransform, IgnoreMethods, IgnoreMetadata.
# Include: **/*_spec.rb
# Configuration parameters: CustomTransform, IgnoreMethods, IgnoreMetadata, InflectorPath, EnforcedInflector.
# SupportedInflectors: default, active_support
RSpec/SpecFilePathFormat:
Exclude:
- '**/spec/routing/**/*'
- 'spec/ruby_units/utf-8/unit_spec.rb'

# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: EnforcedStyle.
# Configuration parameters: EnforcedStyle, EnforcedStyleForClasses, EnforcedStyleForModules.
# SupportedStyles: nested, compact
# SupportedStylesForClasses: ~, nested, compact
# SupportedStylesForModules: ~, nested, compact
Style/ClassAndModuleChildren:
Exclude:
- 'lib/ruby_units/definition.rb'

# Offense count: 1
# Configuration parameters: AllowedConstants.
Style/Documentation:
Exclude:
- 'spec/**/*'
- 'test/**/*'
- 'lib/ruby_units/configuration.rb'

# Offense count: 5
# This cop supports unsafe autocorrection (--autocorrect-all).
Style/GlobalStdStream:
Expand All @@ -169,13 +164,6 @@ Style/OpenStructUse:
Exclude:
- 'Guardfile'

# Offense count: 1
# Configuration parameters: AllowedMethods.
# AllowedMethods: respond_to_missing?
Style/OptionalBooleanParameter:
Exclude:
- 'lib/ruby_units/date.rb'

# Offense count: 1
# This cop supports unsafe autocorrection (--autocorrect-all).
# Configuration parameters: AllowSend.
Expand Down
4 changes: 2 additions & 2 deletions Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,9 @@ GEM
rubocop-ast (>= 1.48.0, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 2.4.0, < 4.0)
rubocop-ast (1.48.0)
rubocop-ast (1.49.0)
parser (>= 3.3.7.2)
prism (~> 1.4)
prism (~> 1.7)
rubocop-rake (0.7.1)
lint_roller (~> 1.1)
rubocop (>= 1.72.1)
Expand Down
4 changes: 2 additions & 2 deletions Guardfile
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ guard :rspec, cmd: "bundle exec rspec" do
rspec.spec_helper = "spec/spec_helper.rb"

watch(%r{^spec/.+_spec\.rb$})
watch(%r{^lib/(.+)\.rb$}) { |m| rspec.spec.call(m[1]) }
watch(rspec.spec_helper) { rspec.spec_dir }
watch(%r{^lib/(.+)\.rb$}) { |m| rspec.spec.call(m[1]) }
watch(rspec.spec_helper) { rspec.spec_dir }
end
62 changes: 31 additions & 31 deletions lib/ruby_units/unit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@
self.unit_values = {}
@unit_regex = nil
@unit_match_regex = nil
UNITY = "<1>"
UNITY_ARRAY = [UNITY].freeze
UNITY = "<1>"
UNITY_ARRAY = [UNITY].freeze

SIGN_REGEX = /(?:[+-])?/ # +, -, or nothing

Expand All @@ -75,36 +75,36 @@
# and 'inches', but they aren't defined at the point in the code where we
# need this regex.
FEET_INCH_UNITS_REGEX = /(?:'|ft|feet)\s*(?<inches>#{RATIONAL_NUMBER}|#{SCI_NUMBER})\s*(?:"|in|inch(?:es)?)/
FEET_INCH_REGEX = /(?<feet>#{INTEGER_REGEX})\s*#{FEET_INCH_UNITS_REGEX}/
FEET_INCH_REGEX = /(?<feet>#{INTEGER_REGEX})\s*#{FEET_INCH_UNITS_REGEX}/
# ideally we would like to generate this regex from the alias for a 'pound'
# and 'ounce', but they aren't defined at the point in the code where we
# need this regex.
LBS_OZ_UNIT_REGEX = /(?:#|lbs?|pounds?|pound-mass)+[\s,]*(?<oz>#{RATIONAL_NUMBER}|#{UNSIGNED_INTEGER_REGEX})\s*(?:ozs?|ounces?)/
LBS_OZ_REGEX = /(?<pounds>#{INTEGER_REGEX})\s*#{LBS_OZ_UNIT_REGEX}/
LBS_OZ_UNIT_REGEX = /(?:#|lbs?|pounds?|pound-mass)+[\s,]*(?<oz>#{RATIONAL_NUMBER}|#{UNSIGNED_INTEGER_REGEX})\s*(?:ozs?|ounces?)/
LBS_OZ_REGEX = /(?<pounds>#{INTEGER_REGEX})\s*#{LBS_OZ_UNIT_REGEX}/
# ideally we would like to generate this regex from the alias for a 'stone'
# and 'pound', but they aren't defined at the point in the code where we
# need this regex. also note that the plural of 'stone' is still 'stone',
# but we accept 'stones' anyway.
STONE_LB_UNIT_REGEX = /(?:sts?|stones?)+[\s,]*(?<pounds>#{RATIONAL_NUMBER}|#{UNSIGNED_INTEGER_REGEX})\s*(?:#|lbs?|pounds?|pound-mass)*/
STONE_LB_REGEX = /(?<stone>#{INTEGER_REGEX})\s*#{STONE_LB_UNIT_REGEX}/
STONE_LB_REGEX = /(?<stone>#{INTEGER_REGEX})\s*#{STONE_LB_UNIT_REGEX}/
# Time formats: 12:34:56,78, (hh:mm:ss,msec) etc.
TIME_REGEX = /(?<hour>\d+):(?<min>\d+):?(?:(?<sec>\d+))?(?:[.](?<msec>\d+))?/
TIME_REGEX = /(?<hour>\d+):(?<min>\d+):?(?:(?<sec>\d+))?(?:[.](?<msec>\d+))?/
# Complex numbers: 1+2i, 1.0+2.0i, -1-1i, etc.
COMPLEX_NUMBER = /(?<real>#{SCI_NUMBER})?(?<imaginary>#{SCI_NUMBER})i\b/
COMPLEX_NUMBER = /(?<real>#{SCI_NUMBER})?(?<imaginary>#{SCI_NUMBER})i\b/
# Any Complex, Rational, or scientific number
ANY_NUMBER = /(#{COMPLEX_NUMBER}|#{RATIONAL_NUMBER}|#{SCI_NUMBER})/
ANY_NUMBER_REGEX = /(?:#{ANY_NUMBER})?\s?([^-\d.].*)?/
NUMBER_REGEX = /(?<scalar>#{SCI_NUMBER}*)\s*(?<unit>.+)?/ # a number followed by a unit
UNIT_STRING_REGEX = %r{#{SCI_NUMBER}*\s*([^/]*)/*(.+)*}
TOP_REGEX = /(?<unit_part>[^ *]+)(?:\^|\*\*)(?<exponent>[\d-]+)/
BOTTOM_REGEX = /(?<unit_part>[^* ]+)(?:\^|\*\*)(?<exponent>\d+)/
NUMBER_UNIT_REGEX = /#{SCI_NUMBER}?(.*)/
COMPLEX_REGEX = /#{COMPLEX_NUMBER}\s?(?<unit>.+)?/
RATIONAL_REGEX = /#{RATIONAL_NUMBER}\s?(?<unit>.+)?/
KELVIN = ["<kelvin>"].freeze
FAHRENHEIT = ["<fahrenheit>"].freeze
RANKINE = ["<rankine>"].freeze
CELSIUS = ["<celsius>"].freeze
ANY_NUMBER = /(#{COMPLEX_NUMBER}|#{RATIONAL_NUMBER}|#{SCI_NUMBER})/
ANY_NUMBER_REGEX = /(?:#{ANY_NUMBER})?\s?([^-\d.].*)?/
NUMBER_REGEX = /(?<scalar>#{SCI_NUMBER}*)\s*(?<unit>.+)?/ # a number followed by a unit
UNIT_STRING_REGEX = %r{#{SCI_NUMBER}*\s*([^/]*)/*(.+)*}
TOP_REGEX = /(?<unit_part>[^ *]+)(?:\^|\*\*)(?<exponent>[\d-]+)/
BOTTOM_REGEX = /(?<unit_part>[^* ]+)(?:\^|\*\*)(?<exponent>\d+)/
NUMBER_UNIT_REGEX = /#{SCI_NUMBER}?(.*)/
COMPLEX_REGEX = /#{COMPLEX_NUMBER}\s?(?<unit>.+)?/
RATIONAL_REGEX = /#{RATIONAL_NUMBER}\s?(?<unit>.+)?/
KELVIN = ["<kelvin>"].freeze
FAHRENHEIT = ["<fahrenheit>"].freeze
RANKINE = ["<rankine>"].freeze
CELSIUS = ["<celsius>"].freeze

# Temperature conversion constants
CELSIUS_OFFSET_TO_KELVIN = 273.15 # offset to convert Celsius to Kelvin
Expand Down Expand Up @@ -379,24 +379,24 @@
# @param [String] string
# @return [Array(Numeric, String)] consisting of [number, "unit"]
def self.parse_into_numbers_and_units(string)
num, unit = string.scan(ANY_NUMBER_REGEX).first

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.

[
case num
when NilClass # This happens when no number is passed and we are parsing a pure unit string
1
when COMPLEX_NUMBER
num.to_c
when RATIONAL_NUMBER
# We use this method instead of relying on `to_r` because it does not
# handle improper fractions correctly.
sign = Regexp.last_match(1) == "-" ? -1 : 1
whole_part = Regexp.last_match(2).to_i
fractional_part = Rational(Regexp.last_match(3).to_i, Regexp.last_match(4).to_i)
sign * (whole_part + fractional_part)
else
num.to_f
end,

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
unit.to_s.strip
]
end
Expand Down Expand Up @@ -1229,9 +1229,9 @@

target_num = target.numerator
target_den = target.denominator
source_numerator_values = to_scalar.call(@numerator)
source_numerator_values = to_scalar.call(@numerator)
source_denominator_values = to_scalar.call(@denominator)
target_numerator_values = to_scalar.call(target_num)
target_numerator_values = to_scalar.call(target_num)
target_denominator_values = to_scalar.call(target_den)
# @type [Rational, Numeric]
scalar_is_integer = @scalar.is_a?(Integer)
Expand Down Expand Up @@ -1295,10 +1295,10 @@
def units(with_prefix: true, format: nil)
return "" if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY

output_numerator = ["1"]
output_numerator = ["1"]
output_denominator = []
num = @numerator.clone.compact
den = @denominator.clone.compact
num = @numerator.clone.compact
den = @denominator.clone.compact

process_unit_array = lambda do |unit_array|
definitions = unit_array.map { unit_class.definition(_1) }
Expand Down Expand Up @@ -1605,11 +1605,11 @@
def update_base_scalar
if base?
@base_scalar = @scalar
@signature = unit_signature
@signature = unit_signature
else
base = to_base
base = to_base
@base_scalar = base.scalar
@signature = base.signature
@signature = base.signature
end
end

Expand Down Expand Up @@ -2061,7 +2061,7 @@

unit_string.gsub!(/[%'"#]/, "%" => "percent", "'" => "feet", '"' => "inch", "#" => "pound")
if unit_string.start_with?(COMPLEX_NUMBER)
match = unit_string.match(COMPLEX_REGEX)

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
real_str, imaginary_str, unit_s = match.values_at(:real, :imaginary, :unit)
real = Float(real_str) if real_str
imaginary = Float(imaginary_str)
Expand All @@ -2076,7 +2076,7 @@
end

if unit_string.start_with?(RATIONAL_NUMBER)
match = unit_string.match(RATIONAL_REGEX)

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
numerator_string, denominator_string, proper_string, unit_s = match.values_at(:numerator, :denominator, :proper, :unit)
numerator = Integer(numerator_string)
denominator = Integer(denominator_string)
Expand All @@ -2103,7 +2103,7 @@

if unit
copy(unit)
@scalar *= mult
@scalar *= mult
@base_scalar *= mult
return self
end
Expand All @@ -2118,7 +2118,7 @@
# ... and then strip the remaining brackets for x*y*z
unit_string.gsub!(/[<>]/, "")

if (match = unit_string.match(TIME_REGEX))

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
hours, minutes, seconds, milliseconds = match.values_at(:hour, :min, :sec, :msec)
raise ArgumentError, "Invalid Duration" if [hours, minutes, seconds, milliseconds].all?(&:nil?)

Expand All @@ -2129,7 +2129,7 @@
end

# feet -- 6'5"
if (match = unit_string.match(FEET_INCH_REGEX))

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9'' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9'' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9'' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9'9/' and with many repetitions of '9'.
feet_str, inches = match.values_at(:feet, :inches)
feet = Integer(feet_str)
return copy(if feet.negative?
Expand All @@ -2140,7 +2140,7 @@
end

# weight -- 8 lbs 12 oz
if (match = unit_string.match(LBS_OZ_REGEX))

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9#' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9#' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9#9/' and with many repetitions of '9'.
pounds_str, oz = match.values_at(:pounds, :oz)
pounds = Integer(pounds_str)
return copy(if pounds.negative?
Expand All @@ -2151,7 +2151,7 @@
end

# stone -- 3 stone 5, 2 stone, 14 stone 3 pounds, etc.
if (match = unit_string.match(STONE_LB_REGEX))

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on a
library input
may run slow on strings with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9st' and with many repetitions of '9'.
This
regular expression
that depends on a
library input
may run slow on strings starting with '9st' and with many repetitions of '9'.
stone_str, pounds = match.values_at(:stone, :pounds)
stone = Integer(stone_str)
return copy(if stone.negative?
Expand Down Expand Up @@ -2199,7 +2199,7 @@

@scalar /= bottom_scalar

@numerator ||= UNITY_ARRAY
@numerator ||= UNITY_ARRAY
@denominator ||= UNITY_ARRAY
@numerator = top.scan(unit_match_regex).delete_if(&:empty?).compact if top
@denominator = bottom.scan(unit_match_regex).delete_if(&:empty?).compact if bottom
Expand Down
Loading