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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## Unreleased
- Fix issue with inherited hook in helper ([#33](https://github.com/avo-hq/class_variants/pull/33))

## 1.1.0 (2025-01-20)
- Add support for merging ([#23](https://github.com/avo-hq/class_variants/pull/23))
- Add support for subclass inheritance in helper ([#24](https://github.com/avo-hq/class_variants/pull/24))
Expand Down
7 changes: 5 additions & 2 deletions lib/class_variants/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@ def class_variants(...)
def self.included(base)
base.extend(ClassMethods)
base.singleton_class.instance_variable_set(:@_class_variants_instance, ClassVariants::Instance.new)
base.define_singleton_method(:inherited) do |subclass|

def base.inherited(subclass)
super if defined?(super)

subclass.singleton_class.instance_variable_set(
:@_class_variants_instance, base.singleton_class.instance_variable_get(:@_class_variants_instance).dup
:@_class_variants_instance, singleton_class.instance_variable_get(:@_class_variants_instance).dup
)
end
end
Expand Down
20 changes: 17 additions & 3 deletions test/helper_test.rb
Original file line number Diff line number Diff line change
@@ -1,21 +1,35 @@
require "test_helper"

class HelperTest < Minitest::Test
class DemoClass
class BaseClass
end

class DemoClass < BaseClass
include ClassVariants::Helper

class_variants base: "rounded border"
end

class Subclass < DemoClass
class SubClass < DemoClass
class_variants base: "bg-black"
end

def test_inherited
mock = Minitest::Mock.new
mock.expect(:call, nil, [Class])

BaseClass.stub(:inherited, mock) do
Class.new(DemoClass)
end

mock.verify
end

def test_call_from_instance
assert_equal "rounded border", DemoClass.new.class_variants
end

def test_call_from_subclass
assert_equal "rounded border bg-black", Subclass.new.class_variants
assert_equal "rounded border bg-black", SubClass.new.class_variants
end
end