Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Evaluate setting immediately if input defined #95

Merged
merged 1 commit into from Jun 22, 2020
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/dry/configurable/setting.rb
Expand Up @@ -60,6 +60,8 @@ def initialize(name, input: Undefined, default: Undefined, **options)
@input = input.equal?(Undefined) ? default : input
@default = default
@options = options

evaluate if input_defined?
end

# @api private
Expand Down
78 changes: 68 additions & 10 deletions spec/unit/dry/configurable/setting_spec.rb
Expand Up @@ -8,6 +8,52 @@
Dry::Configurable::Setting.new(:test, **options)
end

describe '#initialize' do
describe 'input evaluation' do
let(:constructor) do
# Allow constructor calls to be observed
ctx = self
-> val {
ctx.instance_variable_set :@constructor_called, true
val
}
end

before do
@constructor_called = false
end

context 'input defined' do
let(:options) do
{input: 1, constructor: constructor}
end

it 'evaluates the input' do
expect(setting).to be_evaluated
end

it 'evaluates the input through the constructor' do
expect { setting }.to change { @constructor_called }.from(false).to true
end
end

context 'input not defined' do
let(:options) do
{constructor: constructor}
end

it 'does not evaluates the input' do
expect(setting).not_to be_evaluated
end

it 'does not call the constructor' do
expect { setting }.not_to change { @constructor_called }
expect(@constructor_called).to be false
end
end
end
end

describe '#input_defined?' do
context 'no input provided' do
let(:options) do
Expand Down Expand Up @@ -73,19 +119,31 @@
end

describe '#evaluated?' do
let(:options) do
{}
end
context 'input defined' do
let(:options) do
{input: 2}
end

it 'is false for a newly created setting' do
expect(setting).not_to be_evaluated
it 'is true' do
expect(setting).to be_evaluated
end
end

it 'becomes true after accessing the value' do
expect { setting.value }
.to change { setting.evaluated? }
.from(false)
.to(true)
context 'input not defined' do
let(:options) do
{}
end

it 'is false' do
expect(setting).not_to be_evaluated
end

it 'becomes true after accessing the value' do
expect { setting.value }
.to change { setting.evaluated? }
.from(false)
.to(true)
end
end
end

Expand Down