Skip to content

Commit 71c290e

Browse files
authored
Merge pull request #24 from javierav/inheritance
Add support for subclass inheritance in helper
2 parents c9f7a2f + 3f60099 commit 71c290e

File tree

4 files changed

+25
-8
lines changed

4 files changed

+25
-8
lines changed

CHANGELOG.md

+1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
## Unreleased
22
- Add support for merging ([#23](https://github.com/avo-hq/class_variants/pull/23))
3+
- Add support for subclass inheritance in helper ([#24](https://github.com/avo-hq/class_variants/pull/24))
34

45
## 1.0.0 (2024-11-13)
56
- Add support for slots ([#15](https://github.com/avo-hq/class_variants/pull/15))

lib/class_variants/helper.rb

+8-8
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,22 @@ module ClassVariants
22
module Helper
33
module ClassMethods
44
def class_variants(...)
5-
@_class_variants_instance = ClassVariants.build(...)
6-
end
7-
8-
def _class_variants_instance
9-
@_class_variants_instance
5+
singleton_class.instance_variable_get(:@_class_variants_instance).merge(...)
106
end
117
end
128

139
def self.included(base)
1410
base.extend(ClassMethods)
11+
base.singleton_class.instance_variable_set(:@_class_variants_instance, ClassVariants::Instance.new)
12+
base.define_singleton_method(:inherited) do |subclass|
13+
subclass.singleton_class.instance_variable_set(
14+
:@_class_variants_instance, base.singleton_class.instance_variable_get(:@_class_variants_instance).dup
15+
)
16+
end
1517
end
1618

1719
def class_variants(...)
18-
raise "You must configure class_variants in class definition" unless self.class._class_variants_instance
19-
20-
self.class._class_variants_instance.render(...)
20+
self.class.singleton_class.instance_variable_get(:@_class_variants_instance).render(...)
2121
end
2222
end
2323
end

lib/class_variants/instance.rb

+8
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,14 @@ def initialize(...)
88
merge(...)
99
end
1010

11+
def dup
12+
self.class.new.tap do |copy|
13+
copy.instance_variable_set(:@bases, @bases.dup)
14+
copy.instance_variable_set(:@variants, @variants.dup)
15+
copy.instance_variable_set(:@defaults, @defaults.dup)
16+
end
17+
end
18+
1119
def merge(**options, &block)
1220
raise ArgumentError, "Use of hash config and code block is not supported" if !options.empty? && block_given?
1321

test/helper_test.rb

+8
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,15 @@ class DemoClass
77
class_variants base: "rounded border"
88
end
99

10+
class Subclass < DemoClass
11+
class_variants base: "bg-black"
12+
end
13+
1014
def test_call_from_instance
1115
assert_equal "rounded border", DemoClass.new.class_variants
1216
end
17+
18+
def test_call_from_subclass
19+
assert_equal "rounded border bg-black", Subclass.new.class_variants
20+
end
1321
end

0 commit comments

Comments
 (0)