Sha256: ec99f94b89186b779d7aa25af13e998b9ab14b93afcd11e9616478b4a6d8b1be

Contents?: true

Size: 1.21 KB

Versions: 11

Compression:

Stored size: 1.21 KB

Contents

require 'yaml'
require 'pathname'

require 'dry/validation/messages/abstract'

module Dry
  module Validation
    class Messages::YAML < Messages::Abstract
      include Dry::Equalizer(:data)

      attr_reader :data

      configure do |config|
        config.root = '%{locale}.errors'.freeze
      end

      def self.load(paths = config.paths)
        new(paths.map { |path| load_file(path) }.reduce(:merge))
      end

      def self.load_file(path)
        flat_hash(YAML.load_file(path))
      end

      def self.flat_hash(h, f = [], g = {})
        return g.update(f.join('.'.freeze) => h) unless h.is_a? Hash
        h.each { |k, r| flat_hash(r, f + [k], g) }
        g
      end

      def initialize(data)
        super()
        @data = data
      end

      def get(key, options = {})
        data[key % { locale: options.fetch(:locale, :en) }]
      end

      def key?(key, options = {})
        data.key?(key % { locale: options.fetch(:locale, :en) })
      end

      def merge(overrides)
        if overrides.is_a?(Hash)
          self.class.new(data.merge(self.class.flat_hash(overrides)))
        else
          self.class.new(data.merge(Messages::YAML.load_file(overrides)))
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
dry-validation-0.9.4 lib/dry/validation/messages/yaml.rb
dry-validation-0.9.3 lib/dry/validation/messages/yaml.rb
dry-validation-0.9.2 lib/dry/validation/messages/yaml.rb
dry-validation-0.9.1 lib/dry/validation/messages/yaml.rb
dry-validation-0.9.0 lib/dry/validation/messages/yaml.rb
dry-validation-0.8.0 lib/dry/validation/messages/yaml.rb
dry-validation-0.7.4 lib/dry/validation/messages/yaml.rb
dry-validation-0.7.3 lib/dry/validation/messages/yaml.rb
dry-validation-0.7.2 lib/dry/validation/messages/yaml.rb
dry-validation-0.7.1 lib/dry/validation/messages/yaml.rb
dry-validation-0.7.0 lib/dry/validation/messages/yaml.rb