class Stannum::Messages::DefaultStrategy
Strategy to generate error messages from gem configuration.
Constants
- DEFAULT_LOAD_PATHS
The default directories from which to load configured error messages.
Attributes
@return [String] The locale used to load and scope configured messages.
Public Class Methods
@return [Array<String>] The directories from which to load configured
error messages.
# File lib/stannum/messages/default_strategy.rb, line 17 def self.load_paths @load_paths ||= DEFAULT_LOAD_PATHS.dup end
@param configuration [Hash{Symbol, Object}] The configured messages. @param load_paths
[Array<String>] The directories from which to load
configured error messages.
@param locale [String] The locale used to load and scope configured
messages.
# File lib/stannum/messages/default_strategy.rb, line 26 def initialize(configuration: nil, load_paths: nil, locale: 'en') @load_paths = Array(load_paths) unless load_paths.nil? @locale = locale @configuration = configuration end
Public Instance Methods
@param error_type [String] The qualified path to the configured error
message.
@param options [Hash] Additional properties to interpolate or to pass to
the message proc.
# File lib/stannum/messages/default_strategy.rb, line 39 def call(error_type, **options) unless error_type.is_a?(String) || error_type.is_a?(Symbol) raise ArgumentError, 'error type must be a String or Symbol' end message = generate_message(error_type, options) interpolate_message(message, options) end
@return [Array<String>] The directories from which to load configured
error messages.
# File lib/stannum/messages/default_strategy.rb, line 51 def load_paths @load_paths || self.class.load_paths end
Reloads the configuration from the configured load_path.
This can be useful when the load_path is updated after creating the strategy, such as in an initializer for another gem.
@return [DefaultStrategy] the strategy.
# File lib/stannum/messages/default_strategy.rb, line 61 def reload_configuration! @configuration = load_configuration self end
Private Instance Methods
# File lib/stannum/messages/default_strategy.rb, line 69 def configuration @configuration ||= load_configuration end
# File lib/stannum/messages/default_strategy.rb, line 73 def generate_message(error_type, options) path = error_type.to_s.split('.').map(&:intern) path.unshift(locale.intern) message = configuration.dig(*path) return message if message.is_a?(String) return message.call(error_type, options) if message.is_a?(Proc) return "no message defined for #{error_type.inspect}" if message.nil? "configuration is a namespace at #{error_type}" end
# File lib/stannum/messages/default_strategy.rb, line 88 def interpolate_message(message, options) message.gsub(/%{\w+}/) do |match| key = match[2..-2].intern options.fetch(key, match) end end
# File lib/stannum/messages/default_strategy.rb, line 96 def load_configuration Stannum::Messages::DefaultLoader .new( file_paths: load_paths, locale: locale ) .call end