Skip to content

Commit

Permalink
Inheritance (sub class from Unit) no longer works
Browse files Browse the repository at this point in the history
Fixes #339
  • Loading branch information
olbrich committed Jan 31, 2024
1 parent bb198f8 commit 33a1ec5
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ Style/FormatString:
Enabled: false
Style/DateTime:
Enabled: false
Metrics/ClassLength:
Enabled: false
3 changes: 2 additions & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ GEM
PLATFORMS
arm64-darwin-21
arm64-darwin-22
arm64-darwin-23
java
universal-java-11
universal-java-18
Expand Down Expand Up @@ -203,4 +204,4 @@ DEPENDENCIES
yard

BUNDLED WITH
2.4.19
2.5.3
13 changes: 12 additions & 1 deletion lib/ruby_units/unit.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
require 'date'
module RubyUnits
# Copyright 2006-2023
# Copyright 2006-2024
# @author Kevin C. Olbrich, Ph.D.
# @see https://github.com/olbrich/ruby-units
#
Expand Down Expand Up @@ -165,6 +165,17 @@ class << self

# Class Methods

# Callback triggered when a subclass is created. This properly sets up the internal variables, and copies
# definitions from the parent class.
#
# @param [Class] subclass
def self.inherited(subclass)
super
subclass.definitions = definitions.dup
subclass.instance_variable_set(:@kinds, @kinds.dup)
subclass.setup
end

# setup internal arrays and hashes
# @return [Boolean]
def self.setup
Expand Down
31 changes: 31 additions & 0 deletions spec/ruby_units/subclass_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
RSpec.describe 'Subclass' do
subject(:subclass) { Class.new(RubyUnits::Unit) }

it 'can be subclassed' do
expect(subclass).to be < RubyUnits::Unit
end

it 'can be instantiated' do
expect(subclass.new('1 m')).to be_a(RubyUnits::Unit)
end

it 'compares to the parent class' do
expect(subclass.new('1 m')).to eq(RubyUnits::Unit.new('1 m'))
end

it 'can be added to another subclass instance' do
expect(subclass.new('1 m') + subclass.new('1 m')).to eq(RubyUnits::Unit.new('2 m'))
end

it 'returns a subclass object when added to another instance of a subclass' do
expect(subclass.new('1 m') + subclass.new('1 m')).to be_an_instance_of(subclass)
end

it 'returns an instance of the parent class when added to another instance of a subclass' do
expect(RubyUnits::Unit.new('1 m') + subclass.new('1 m')).to be_an_instance_of(RubyUnits::Unit)
end

it 'returns an instance of the subclass when added to an instance of the parent class' do
expect(subclass.new('1 m') + RubyUnits::Unit.new('1 m')).to be_an_instance_of(subclass)
end
end

0 comments on commit 33a1ec5

Please sign in to comment.