class Habitat

Defined in:

habitat.cr
habitat/errors.cr
habitat/settings_helpers.cr
habitat/temp_config.cr
habitat/version.cr

Constant Summary

TYPES_WITH_HABITAT = [] of Nil
VERSION = "0.4.8"

Class Method Summary

Macro Summary

Class Method Detail

def self.raise_if_missing_settings! #

Raises an error when a required setting is missing.

Raises a Habitat::MissingSettingError if a required setting hasn't been set. We recommend that you call it at the very end of your program.

class YourClass
  Habitat.create do
    # ...
  end
end

YourClass.configure do |settings|
  # ...
end

# ...your main program ends here.

Habitat.raise_if_missing_settings!

[View source]
def self.raise_validation_error(message : String) #

Raise the message passed in.


[View source]

Macro Detail

macro create #

Embed settings in a Class or Module.

A class or module can call Habitat.create with a block of setting calls that will declare the types (and optionally default values) of our settings.

class MyServer
  Habitat.create do
    setting port : Int32
    setting debug_errors : Bool = true
  end
end

create adds a .configure class method that takes a block where we can use the settings setters.

MyServer.configure do
  settings.port = 80
  settings.debug_errors = false
end

create also adds class and instance settings methods to the embedding class/module, which we'll use to get the values of our settings.

MyServer.configure do |settings|
  settings.port = 80
end

MyServer.settings.port # 80

# In an instance method
class MyServer
  def what_is_the_port
    settings.port # 80
  end
end

The settings assigned to a parent class will be inherited by its children classes.

class CustomServer < MyServer; end

MyServer.configure do |settings|
  settings.port = 3000
end

CustomServer.settings.port # 3000

Assigning a value to a setting of incompatible type will result in an error at compile time.

MyServer.configure do |settings|
  settings.port = "80" # Compile-time error! An Int32 was expected
end

Each setting can take an optional validation argument to ensure the setting value matches a specific format.

class MyMachine
  Habitat.create do
    setting pin : String, validation: :pin_format
  end

  def self.pin_format(value : String)
    value.match(/^\d{4}/) || Habitat.raise_validation_error("Your PIN must be exactly 4 digits")
  end
end

Even though the type is correct, this will now raise an error because the format doesn't match

MyMachine.configure do |settings|
  settings.pin = "abcd"
end

[View source]
macro extend #

Extend an existing Habitat config with additional settings. Can be used if a shard sets a config, and and you need additional properties to extend the shard.

class IoT
  Habitat.create do
    setting name : String
  end
end

class IoT
  Habitat.extend do
    setting uuid : UUID
  end
end

IoT.configure do |settings|
  settings.name = "plug"
  settings.uuid = UUID.random
end

[View source]