lib/pupa/models/model.rb in pupa-0.0.11 vs lib/pupa/models/model.rb in pupa-0.0.12

- old
+ new

@@ -15,10 +15,12 @@ module Model extend ActiveSupport::Concern included do include ActiveSupport::Callbacks + include Concerns::IndifferentAccess + define_callbacks :create, :save class_attribute :json_schema class_attribute :properties class_attribute :foreign_keys @@ -75,17 +77,18 @@ end # Sets the class' schema. # # @param [Hash,String] value a hash or a relative or absolute path + # @note `JSON::Validator#initialize_schema` runs fastest if given a hash. def schema=(value) self.json_schema = if Hash === value value elsif Pathname.new(value).absolute? - File.read(value) + JSON.load(File.read(value)) else - File.read(File.expand_path(File.join('..', '..', '..', 'schemas', "#{value}.json"), __dir__)) + JSON.load(File.read(File.expand_path(File.join('..', '..', '..', 'schemas', "#{value}.json"), __dir__))) end end end # @param [Hash] properties the object's properties @@ -164,11 +167,10 @@ # Validates the object against the schema. # # @raises [JSON::Schema::ValidationError] if the object is invalid def validate! if self.class.json_schema - # JSON::Validator#initialize_schema runs fastest if given a hash. JSON::Validator.validate!(self.class.json_schema, stringify_keys(to_h(persist: true))) end end # Returns the object as a hash. @@ -197,35 +199,8 @@ a = to_h b = other.to_h a.delete(:_id) b.delete(:_id) a == b - end - - private - - def transform_keys(object, meth) - case object - when Hash - {}.tap do |hash| - object.each do |key,value| - hash[key.send(meth)] = transform_keys(value, meth) - end - end - when Array - object.map do |value| - transform_keys(value, meth) - end - else - object - end - end - - def symbolize_keys(object) - transform_keys(object, :to_sym) - end - - def stringify_keys(object) - transform_keys(object, :to_s) end end end