Class: Dry::Validation::Messages::YAML

Inherits:
Abstract
  • Object
show all
Defined in:
lib/dry/validation/messages/yaml.rb

Constant Summary

Constants inherited from Abstract

Abstract::DEFAULT_PATH

Instance Attribute Summary collapse

Attributes inherited from Abstract

#config

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Abstract

cache, #cache, #call, #hash, #lookup, #lookup_paths, #namespaced, #root, #rule

Constructor Details

#initialize(data) ⇒ YAML

Returns a new instance of YAML.



31
32
33
34
# File 'lib/dry/validation/messages/yaml.rb', line 31

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

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



11
12
13
# File 'lib/dry/validation/messages/yaml.rb', line 11

def data
  @data
end

Class Method Details

.flat_hash(h, f = [], g = {}) ⇒ Object



25
26
27
28
29
# File 'lib/dry/validation/messages/yaml.rb', line 25

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

.load(paths = config.paths) ⇒ Object



17
18
19
# File 'lib/dry/validation/messages/yaml.rb', line 17

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

.load_file(path) ⇒ Object



21
22
23
# File 'lib/dry/validation/messages/yaml.rb', line 21

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

Instance Method Details

#get(key, options = {}) ⇒ Object



36
37
38
# File 'lib/dry/validation/messages/yaml.rb', line 36

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

#key?(key, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/dry/validation/messages/yaml.rb', line 40

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

#merge(overrides) ⇒ Object



44
45
46
47
48
49
50
# File 'lib/dry/validation/messages/yaml.rb', line 44

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