Skip to content

Commit

Permalink
Add support for subclass inheritance in helper
Browse files Browse the repository at this point in the history
  • Loading branch information
javierav committed Nov 18, 2024
1 parent f34a069 commit 98e768b
Show file tree
Hide file tree
Showing 4 changed files with 25 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
## Unreleased
- 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))

## 1.0.0 (2024-11-13)
- Add support for slots ([#15](https://github.com/avo-hq/class_variants/pull/15))
Expand Down
16 changes: 8 additions & 8 deletions lib/class_variants/helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,22 @@ module ClassVariants
module Helper
module ClassMethods
def class_variants(...)
@_class_variants_instance = ClassVariants.build(...)
end

def _class_variants_instance
@_class_variants_instance
singleton_class.instance_variable_get(:@_class_variants_instance).merge(...)
end
end

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|
subclass.singleton_class.instance_variable_set(
:@_class_variants_instance, base.singleton_class.instance_variable_get(:@_class_variants_instance).dup
)
end
end

def class_variants(...)
raise "You must configure class_variants in class definition" unless self.class._class_variants_instance

self.class._class_variants_instance.render(...)
self.class.singleton_class.instance_variable_get(:@_class_variants_instance).render(...)
end
end
end
8 changes: 8 additions & 0 deletions lib/class_variants/instance.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ def initialize(...)
merge(...)
end

def dup
self.class.new.tap do |copy|
copy.instance_variable_set(:@bases, @bases.dup)
copy.instance_variable_set(:@variants, @variants.dup)
copy.instance_variable_set(:@defaults, @defaults.dup)
end
end

def merge(**options, &block)
raise ArgumentError, "Use of hash config and code block is not supported" if !options.empty? && block_given?

Expand Down
8 changes: 8 additions & 0 deletions test/helper_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,15 @@ class DemoClass
class_variants base: "rounded border"
end

class Subclass < DemoClass
class_variants base: "bg-black"
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
end
end

0 comments on commit 98e768b

Please sign in to comment.