Module: Fractor::ConfigSchema::SchemaClassMethods
- Defined in:
- lib/fractor/config_schema.rb
Instance Method Summary collapse
-
#schema(name, **options) ⇒ Object
Define a configuration schema entry.
-
#schema_definition ⇒ Hash
Get schema as a hash (for documentation purposes).
-
#schema_entries ⇒ Hash
Get all schema entries.
-
#schema_help ⇒ String
Generate schema help text.
-
#validate!(config = {}) ⇒ Hash
Validate configuration against schema.
Instance Method Details
#schema(name, **options) ⇒ Object
Define a configuration schema entry
99 100 101 102 |
# File 'lib/fractor/config_schema.rb', line 99 def schema(name, **) @schema_entries ||= {} @schema_entries[name] = SchemaEntry.new(name, **) end |
#schema_definition ⇒ Hash
Get schema as a hash (for documentation purposes)
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_entries ⇒ Hash
Get all schema entries
106 107 108 |
# File 'lib/fractor/config_schema.rb', line 106 def schema_entries @schema_entries || {} end |
#schema_help ⇒ String
Generate schema help text
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
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 |