From 1411805f5e9e7e68510ce3cdef06b5be6d77ff4c Mon Sep 17 00:00:00 2001 From: Guillaume Hain Date: Thu, 13 May 2021 22:14:39 +0200 Subject: [PATCH] Code review --- lib/no_brainer/document/association/belongs_to.rb | 14 +++++++++----- lib/no_brainer/document/association/has_many.rb | 4 ++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/lib/no_brainer/document/association/belongs_to.rb b/lib/no_brainer/document/association/belongs_to.rb index 5c3d064df..cbbc0ec88 100644 --- a/lib/no_brainer/document/association/belongs_to.rb +++ b/lib/no_brainer/document/association/belongs_to.rb @@ -17,7 +17,7 @@ def foreign_key def foreign_type return nil unless options[:polymorphic] - options[:foreign_type].try(:to_sym) || (target_name && :"#{target_name}_type") + options[:foreign_type].try(:to_sym) || (:"#{target_name}_type") end def primary_key @@ -42,8 +42,11 @@ def primary_key def target_model(target_class = nil) return if options[:polymorphic] && target_class.nil? - model_name = options[:class_name] || target_name.to_s.camelize - model_name = target_class if options[:polymorphic] + model_name = if options[:polymorphic] + target_class + else + options[:class_name] || target_name.to_s.camelize + end get_model_by_name(model_name) end @@ -121,9 +124,10 @@ def polymorphic_read return target if loaded? target_class = owner.read_attribute(foreign_type) + fk = owner.read_attribute(foreign_key) - if fk = owner.read_attribute(foreign_key) - preload(base_criteria(target_class)&.where(primary_key => fk)&.first) + if target_class && fk + preload(base_criteria(target_class).where(primary_key => fk).first) end end diff --git a/lib/no_brainer/document/association/has_many.rb b/lib/no_brainer/document/association/has_many.rb index df0fb2293..ef9e397bd 100644 --- a/lib/no_brainer/document/association/has_many.rb +++ b/lib/no_brainer/document/association/has_many.rb @@ -49,13 +49,13 @@ def hook if options[:scope] raise ":scope must be passed a lambda like this: `:scope => ->{ where(...) }'" unless options[:scope].is_a?(Proc) - raise ':dependent and :scope cannot be used together' if options[:dependent] + raise ":dependent and :scope cannot be used together" if options[:dependent] end if options[:dependent] unless [:destroy, :delete, :nullify, :restrict, nil].include?(options[:dependent]) raise "Invalid dependent option: `#{options[:dependent].inspect}'. " \ - 'Valid options are: :destroy, :delete, :nullify, or :restrict' + "Valid options are: :destroy, :delete, :nullify, or :restrict" end add_callback_for(:before_destroy) end