Class: Dry::Validation::Messages::Abstract

Inherits:
Object
  • Object
show all
Extended by:
Configurable
Defined in:
lib/dry/validation/messages/abstract.rb

Direct Known Subclasses

I18n, Namespaced, YAML

Constant Summary collapse

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAbstract

Returns a new instance of Abstract.



44
45
46
# File 'lib/dry/validation/messages/abstract.rb', line 44

def initialize
  @config = self.class.config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



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

def config
  @config
end

Class Method Details

.cacheObject



38
39
40
# File 'lib/dry/validation/messages/abstract.rb', line 38

def self.cache
  @cache ||= ThreadSafe::Cache.new { |h, k| h[k] = ThreadSafe::Cache.new }
end

Instance Method Details

#cacheObject



92
93
94
# File 'lib/dry/validation/messages/abstract.rb', line 92

def cache
  self.class.cache[self]
end

#call(*args) ⇒ Object Also known as: []



53
54
55
56
57
58
# File 'lib/dry/validation/messages/abstract.rb', line 53

def call(*args)
  cache.fetch_or_store(args.hash) do
    path, opts = lookup(*args)
    get(path, opts) if path
  end
end

#lookup(predicate, options = {}) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/dry/validation/messages/abstract.rb', line 61

def lookup(predicate, options = {})
  tokens = options.merge(
    root: root,
    predicate: predicate,
    arg_type: config.arg_types[options[:arg_type]],
    val_type: config.val_types[options[:val_type]]
  )

  tokens[:rule] = predicate unless tokens.key?(:rule)

  opts = options.reject { |k, _| config.lookup_options.include?(k) }

  path = lookup_paths(tokens).detect do |key|
    key?(key, opts) && get(key, opts).is_a?(String)
  end

  [path, opts]
end

#lookup_paths(tokens) ⇒ Object



80
81
82
# File 'lib/dry/validation/messages/abstract.rb', line 80

def lookup_paths(tokens)
  config.lookup_paths.map { |path| path % tokens }
end

#namespaced(namespace) ⇒ Object



84
85
86
# File 'lib/dry/validation/messages/abstract.rb', line 84

def namespaced(namespace)
  Messages::Namespaced.new(namespace, self)
end

#rootObject



88
89
90
# File 'lib/dry/validation/messages/abstract.rb', line 88

def root
  config.root
end

#rule(name, options = {}) ⇒ Object



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

def rule(name, options = {})
  path = "%{locale}.rules.#{name}"
  get(path, options) if key?(path, options)
end