lib/pupa/models/model.rb in pupa-0.2.2 vs lib/pupa/models/model.rb in pupa-0.2.3

- old
+ new

@@ -4,14 +4,10 @@ require 'active_support/callbacks' require 'active_support/core_ext/object/try' require 'json-schema' -require 'pupa/refinements/json-schema' - -JSON::Validator.cache_schemas = true - module Pupa # Adds methods expected by Pupa processors. module Model extend ActiveSupport::Concern @@ -20,10 +16,11 @@ include Concerns::IndifferentAccess define_callbacks :create, :save class_attribute :json_schema + class_attribute :validator class_attribute :properties class_attribute :foreign_keys class_attribute :foreign_objects self.properties = Set.new @@ -86,10 +83,15 @@ elsif Pathname.new(value).absolute? JSON.load(File.read(value)) else JSON.load(File.read(File.expand_path(File.join('..', '..', '..', 'schemas', "#{value}.json"), __dir__))) end + + self.validator = JSON::Validator.new(self.json_schema, {}, { + clear_cache: false, + parse_data: false, + }) end end # @param [Hash] properties the object's properties def initialize(properties = {}) @@ -167,10 +169,13 @@ # Validates the object against the schema. # # @raises [JSON::Schema::ValidationError] if the object is invalid def validate! if self.class.json_schema - JSON::Validator.validate!(self.class.json_schema, stringify_keys(to_h(persist: true))) + self.class.validator.instance_variable_set('@errors', []) + self.class.validator.instance_variable_set('@data', stringify_keys(to_h(persist: true))) + self.class.validator.validate + true end end # Returns the object as a hash. #