Module: Fractor::ConfigSchema::SchemaClassMethods

Defined in:
lib/fractor/config_schema.rb

Instance Method Summary collapse

Instance Method Details

#schema(name, **options) ⇒ Object

Define a configuration schema entry

Parameters:

  • name (Symbol)

    Configuration key name

  • options (Hash)

    Schema options (type, default, optional, description)



99
100
101
102
# File 'lib/fractor/config_schema.rb', line 99

def schema(name, **options)
  @schema_entries ||= {}
  @schema_entries[name] = SchemaEntry.new(name, **options)
end

#schema_definitionHash

Get schema as a hash (for documentation purposes)

Returns:

  • (Hash)

    Schema definition



158
159
160
161
162
163
164
165
166
167
# File 'lib/fractor/config_schema.rb', line 158

def schema_definition
  schema_entries.transform_values do |entry|
    {
      type: entry.type,
      default: entry.default,
      optional: entry.optional,
      description: entry.description,
    }
  end
end

#schema_entriesHash

Get all schema entries

Returns:

  • (Hash)

    Schema entries by name



106
107
108
# File 'lib/fractor/config_schema.rb', line 106

def schema_entries
  @schema_entries || {}
end

#schema_helpString

Generate schema help text

Returns:

  • (String)

    Help text describing all schema entries



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/fractor/config_schema.rb', line 140

def schema_help
  lines = []
  schema_entries.each_value do |entry|
    type_desc = case entry.type
                when :boolean then "boolean"
                when Class then entry.type.name
                when Array then entry.type.map(&:name).join(" | ")
                else "any"
                end
    default_desc = entry.optional ? " (default: #{entry.default.inspect})" : " (required)"
    desc = entry.description ? " - #{entry.description}" : ""
    lines << "  #{entry.name}: #{type_desc}#{default_desc}#{desc}"
  end
  lines.join("\n")
end

#validate!(config = {}) ⇒ Hash

Validate configuration against schema

Parameters:

  • config (Hash) (defaults to: {})

    Configuration to validate

Returns:

  • (Hash)

    Validated and normalized configuration

Raises:

  • (ArgumentError)

    If configuration is invalid



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
# File 'lib/fractor/config_schema.rb', line 114

def validate!(config = {})
  all_errors = []

  schema_entries.each do |name, entry|
    value = config.fetch(name, entry.default)
    errors = entry.validate(value)
    all_errors.concat(errors.map { |e| "- #{e}" })
  end

  # Check for unknown keys
  unknown_keys = config.keys - schema_entries.keys.symbolize_keys
  unknown_keys.each do |key|
    all_errors << "- Unknown configuration option: #{key}"
  end

  unless all_errors.empty?
    raise ArgumentError,
          "Invalid configuration:\n#{all_errors.join("\n")}\n\n" \
          "Valid options:\n#{schema_help}"
  end

  config
end