lib/chronicle/etl/configurable.rb in chronicle-etl-0.5.5 vs lib/chronicle/etl/configurable.rb in chronicle-etl-0.6.1

- old
+ new

@@ -1,9 +1,9 @@ # frozen_string_literal: true -require "ostruct" -require "chronic_duration" +require 'ostruct' +require 'chronic_duration' module Chronicle module ETL # A mixin that gives a class # a {Chronicle::ETL::Configurable::ClassMethods#setting} macro to define @@ -17,11 +17,11 @@ # # t = Test.new(when: '2022-02-24') # t.config.when module Configurable # An individual setting for this Configurable - Setting = Struct.new(:default, :required, :type) + Setting = Struct.new(:default, :required, :type, :description) private_constant :Setting # Collection of user-supplied options for this Configurable class Config < OpenStruct # Config values that aren't nil, as a hash @@ -60,11 +60,11 @@ setting = self.class.all_settings[name] # Do nothing with a given option if it's not a connector setting next unless setting - @config[name] = coerced_value(setting, value) + @config[name] = coerced_value(setting, name, value) end validate_config options end @@ -82,16 +82,23 @@ def validate_config missing = (self.class.all_required_settings.keys - @config.compacted_h.keys) raise Chronicle::ETL::ConnectorConfigurationError, "Missing options: #{missing}" if missing.count.positive? end - def coerced_value(setting, value) + def coerced_value(setting, name, value) setting.type ? __send__("coerce_#{setting.type}", value) : value rescue StandardError - raise(Chronicle::ETL::ConnectorConfigurationError, "Could not coerce #{value} into a #{setting.type}") + raise( + Chronicle::ETL::ConnectorConfigurationError, + "Could not convert value '#{value}' into a #{setting.type} for setting '#{name}'" + ) end + def coerce_hash(value) + value.is_a?(Hash) ? value : {} + end + def coerce_string(value) value.to_s end # TODO: think about whether to split up float, integer @@ -99,16 +106,20 @@ value.to_f end def coerce_boolean(value) if value.is_a?(String) - value.downcase == "true" + value.downcase == 'true' else value end end + def coerce_array(value) + value.is_a?(Array) ? value : [value] + end + def coerce_time(value) # parsing yml files might result in us getting Date objects # we convert to DateTime first to to ensure UTC return value.to_datetime.to_time if value.is_a?(Date) @@ -136,11 +147,11 @@ # # @example Basic usage # setting :when, type: :date, required: true # # @see ::Chronicle::ETL::Configurable - def setting(name, default: nil, required: false, type: nil) - s = Setting.new(default, required, type) + def setting(name, default: nil, required: false, type: nil, description: nil) + s = Setting.new(default, required, type, description) settings[name] = s end # Collect all settings defined on this class and its ancestors (that # have Configurable mixin included)