From 1f18fc72e8397668a87071ccc7ff9e39ef47ce50 Mon Sep 17 00:00:00 2001 From: Javier Aranda Date: Thu, 24 Oct 2024 11:15:38 +0200 Subject: [PATCH] Add helper module for defining variants --- CHANGELOG.md | 1 + lib/class_variants.rb | 1 + lib/class_variants/helper.rb | 23 +++++++++++++++++++++++ test/helper_test.rb | 13 +++++++++++++ 4 files changed, 38 insertions(+) create mode 100644 lib/class_variants/helper.rb create mode 100644 test/helper_test.rb diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d99d8a..b1ae942 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## Unreleased - Add support for slots ([#15](https://github.com/avo-hq/class_variants/pull/15)) - Allow passing additional classes when render ([#17](https://github.com/avo-hq/class_variants/pull/17)) +- Add helper module for defining variants ([#18](https://github.com/avo-hq/class_variants/pull/18)) ## 0.0.8 (2024-10-24) - Deprecate usage of positional arguments ([#12](https://github.com/avo-hq/class_variants/pull/12)) diff --git a/lib/class_variants.rb b/lib/class_variants.rb index e4e3663..037268b 100644 --- a/lib/class_variants.rb +++ b/lib/class_variants.rb @@ -1,6 +1,7 @@ require "class_variants/version" require "class_variants/action_view/helpers" require "class_variants/instance" +require "class_variants/helper" require "class_variants/railtie" if defined?(Rails) module ClassVariants diff --git a/lib/class_variants/helper.rb b/lib/class_variants/helper.rb new file mode 100644 index 0000000..ae8af9e --- /dev/null +++ b/lib/class_variants/helper.rb @@ -0,0 +1,23 @@ +module ClassVariants + module Helper + module ClassMethods + def class_variants(...) + @_class_variants_instance = ClassVariants.build(...) + end + + def _class_variants_instance + @_class_variants_instance + end + end + + def self.included(base) + base.extend(ClassMethods) + 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(...) + end + end +end diff --git a/test/helper_test.rb b/test/helper_test.rb new file mode 100644 index 0000000..b099108 --- /dev/null +++ b/test/helper_test.rb @@ -0,0 +1,13 @@ +require "test_helper" + +class HelperTest < Minitest::Test + class DemoClass + include ClassVariants::Helper + + class_variants base: "rounded border" + end + + def test_call_from_instance + assert_equal "rounded border", DemoClass.new.class_variants + end +end