Class: Dry::Validation::Messages

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

Defined Under Namespace

Classes: Namespaced

Constant Summary collapse

DEFAULT_PATH =
Pathname(__dir__).join('../../../config/errors.yml').freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Messages

Returns a new instance of Messages.



42
43
44
# File 'lib/dry/validation/messages.rb', line 42

def initialize(data)
  @data = data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



9
10
11
# File 'lib/dry/validation/messages.rb', line 9

def data
  @data
end

Class Method Details

.defaultObject



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

def self.default
  load(DEFAULT_PATH)
end

.load(path) ⇒ Object



15
16
17
# File 'lib/dry/validation/messages.rb', line 15

def self.load(path)
  new(load_yaml(path))
end

.load_yaml(path) ⇒ Object



19
20
21
# File 'lib/dry/validation/messages.rb', line 19

def self.load_yaml(path)
  symbolize_keys(YAML.load_file(path))
end

.symbolize_keys(hash) ⇒ Object



23
24
25
26
27
# File 'lib/dry/validation/messages.rb', line 23

def self.symbolize_keys(hash)
  hash.each_with_object({}) do |(k, v), r|
    r[k.to_sym] = v.is_a?(Hash) ? symbolize_keys(v) : v
  end
end

Instance Method Details

#lookup(identifier, key, arg, &block) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
# File 'lib/dry/validation/messages.rb', line 58

def lookup(identifier, key, arg, &block)
  message = data.fetch(:attributes, {}).fetch(key, {}).fetch(identifier) do
    data.fetch(identifier, &block)
  end

  if message.is_a?(Hash)
    message.fetch(arg.class.name.downcase.to_sym, message.fetch(:default))
  else
    message
  end
end

#merge(overrides) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/dry/validation/messages.rb', line 46

def merge(overrides)
  if overrides.is_a?(Hash)
    self.class.new(data.merge(overrides))
  else
    self.class.new(data.merge(Messages.load_yaml(overrides)))
  end
end

#namespaced(namespace) ⇒ Object



54
55
56
# File 'lib/dry/validation/messages.rb', line 54

def namespaced(namespace)
  Namespaced.new(Messages.new(data[namespace]), self)
end