Skip to content

Commit 3f1ba88

Browse files
committed
Refine and test component-local config
1 parent 01d3984 commit 3f1ba88

File tree

3 files changed

+29
-4
lines changed

3 files changed

+29
-4
lines changed

lib/view_component/component_local_config.rb

+14-4
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,31 @@
33
module ViewComponent
44
module ComponentLocalConfig
55
class Configuration
6-
def initialize
7-
@config = ActiveSupport::OrderedOptions[
6+
def self.defaults
7+
ActiveSupport::Configurable::Configuration[
88
strip_trailing_whitespace: false
99
]
1010
end
1111

12+
def initialize(config = defaults)
13+
@config = config
14+
end
15+
1216
delegate_missing_to :@config
1317

1418
def inheritable_copy
15-
new.instance_variable_set(:@config, @config.inheritable_copy)
19+
self.class.new(@config.inheritable_copy)
1620
end
21+
22+
private
23+
24+
delegate :defaults, to: :class
1725
end
1826

1927
extend ActiveSupport::Concern
2028

2129
included do
30+
# :nocov:
2231
def configuration
2332
@_configuration ||= self.class.configuration.inheritable_copy
2433
end
@@ -29,6 +38,7 @@ def inherited(child)
2938
child.instance_variable_set(:@_configuration, nil)
3039
super
3140
end
41+
# :nocov:
3242
end
3343

3444
class_methods do
@@ -37,7 +47,7 @@ def configuration
3747
superclass.configuration.inheritable_copy
3848
else
3949
# create a new "anonymous" class that will host the compiled reader methods
40-
Class.new(ActiveSupport::Configurable::Configuration).new
50+
ViewComponent::ComponentLocalConfig::Configuration.new
4151
end
4252
end
4353

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# frozen_string_literal: true
2+
3+
class ConfigurableComponent < ViewComponent::Base
4+
configure do |config|
5+
config.strip_trailing_whitespace = true
6+
end
7+
end

test/sandbox/test/base_test.rb

+8
Original file line numberDiff line numberDiff line change
@@ -146,4 +146,12 @@ def test_no_method_error_does_not_reference_missing_helper
146146
MESSAGE
147147
assert !exception_message_regex.match?(exception.message)
148148
end
149+
150+
def test_component_local_config_is_inheritable
151+
assert_equal false, ViewComponent::Base.configuration.strip_trailing_whitespace
152+
# This component doesn't call configure, so it should inherit the defaults.
153+
# assert_equal false, AnotherComponent.configuration.strip_trailing_whitespace
154+
# This component overrides the defaults.
155+
assert_equal true, ConfigurableComponent.configuration.strip_trailing_whitespace
156+
end
149157
end

0 commit comments

Comments
 (0)