lib/tram/policy.rb in tram-policy-0.2.3 vs lib/tram/policy.rb in tram-policy-0.2.4

- old
+ new

@@ -8,69 +8,24 @@ require_relative "policy/validation_error" require_relative "policy/inflector" require_relative "policy/error" require_relative "policy/errors" require_relative "policy/validator" + require_relative "policy/dsl" extend Dry::Initializer + extend DSL - class << self - # @!method validate(name, opts) - # Registers a validator - # - # @param [#to_sym, nil] name (nil) - # @option opts [Boolean] :stop_on_failure - # @return [self] - # - def validate(name = nil, **opts, &block) - local << Validator.new(scope, name, block, opts) - self - end - - # Policy constructor/validator (alias for [.new]) - # - # @param [Object] *args - # @return [Tram::Policy] - # - def [](*args) - new(*args) - end - - # Translation scope for a policy - # - # @return [Array<String>] - # - def scope - @scope ||= ["tram-policy", *Inflector.underscore(name)] - end - - # List of validators defined by a policy per se - # - # @return [Array<Proc>] - # - def local - @local ||= [] - end - - # List of all applicable validators from both the policy and its parent - # - # @return [Array<Proc>] - # - def all - (((self == Tram::Policy) ? [] : superclass.send(:all)) + local).uniq - end - end - # Translates a message in the scope of current policy # # @param [#to_s] message # @param [Hash<Symbol, Object>] options # @return [String] # - def t(message, options = {}) + def t(message, **options) return message.to_s unless message.is_a? Symbol - I18n.t message, options.merge(scope: @__scope__) + I18n.t message, scope: self.class.scope, **options end # Collection of validation errors # # @return [Tram::Policy::Errors] @@ -114,23 +69,25 @@ # # => #<UserPolicy["name" => "Andy"]> # # @return [String] # def inspect - "#<#{self.class.name}[#{@__options__}]>" + "#<#{self.class.name}[#{__attributes__}]>" end private def initialize(*) super - @__options__ = self.class.dry_initializer.attributes(self) - - self.class.send(:all).each do |validator| + self.class.validators.each do |validator| size = errors.count validator.check(self) break if (errors.count > size) && validator.stop_on_failure end + end + + def __attributes__ + @__attributes__ ||= self.class.dry_initializer.attributes(self) end end end