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

Add temp_config helper #17

Merged
merged 1 commit into from Feb 2, 2018
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
12 changes: 12 additions & 0 deletions spec/habitat_spec.cr
Expand Up @@ -47,6 +47,18 @@ describe Habitat do
FakeServer.settings.nilable_with_default.should be_nil
end

it "can set and reset config using a block" do
setup_server(port: 3000)

FakeServer.temp_config(port: 4000, this_can_be_nil: "string!") do
FakeServer.settings.port.should eq 4000
FakeServer.settings.this_can_be_nil.should eq "string!"
end

FakeServer.settings.port.should eq 3000
FakeServer.settings.this_can_be_nil.should be_nil
end

it "can check for missing settings" do
setup_server

Expand Down
14 changes: 14 additions & 0 deletions src/habitat.cr
Expand Up @@ -36,6 +36,7 @@ class Habitat

macro create
include Habitat::SettingHelpers
include Habitat::TempConfig
Habitat.track(\{{ @type }})

REQUIRED_SETTINGS = [] of TypeDeclaration
Expand All @@ -58,6 +59,19 @@ class Habitat
{{ yield }}
end

module TempConfig
macro temp_config(**settings_with_values)
{% for setting_name, setting_value in settings_with_values %}
original_{{ setting_name }} = {{ @type.name }}.settings.{{setting_name}}
{{ @type.name }}.settings.{{ setting_name }} = {{ setting_value }}
{% end %}
{{ yield }}
{% for setting_name, _unused in settings_with_values %}
{{ @type.name }}.settings.{{ setting_name }} = original_{{ setting_name }}
{% end %}
end
end

module SettingHelpers
macro setting(decl)
{% if decl.type.is_a?(Union) && decl.type.types.map(&.id).includes?(Nil.id) %}
Expand Down