Skip to content
Snippets Groups Projects
Unverified Commit 8e7766a7 authored by Sébastien Gaya's avatar Sébastien Gaya
Browse files

sanitizable refactor

parent 78371275
No related branches found
No related tags found
No related merge requests found
......@@ -6,19 +6,46 @@ module Sanitizable
before_validation :sanitize_fields
def sanitize_fields
attributes_to_sanitize = self.class.columns_hash.map { |name,value| [name, value.type] }
.to_h
.select { |attr_name, attr_type|
[:string, :text].include?(attr_type) && public_send(attr_name).present?
}
.reject { |attr_name, _|
attr_name.ends_with?('_type') # Reject polymorphic type
}
attributes_to_sanitize.each do |attr_name, attr_type|
public_send "#{attr_name}=", Osuny::Sanitizer.sanitize(public_send(attr_name), attr_type)
attributes_to_sanitize.each do |attribute_name, attribute_type|
dangerous_value = public_send attribute_name
sanitized_value = Osuny::Sanitizer.sanitize(dangerous_value, attribute_type)
public_send "#{attribute_name}=", sanitized_value
end
end
protected
# {
# "description" => :text
# }
def attributes_to_sanitize
attributes_with_type.select { |attribute_name, attribute_type|
should_sanitize?(attribute_name, attribute_type)
}
end
def should_sanitize?(attribute_name, attribute_type)
# We filter the attributes with "string" or "text" SQL type.
return false unless [:string, :text].include?(attribute_type)
# We filter the text attributes by their presence.
return false unless public_send(attribute_name).present?
# We filter the attributes which end with "_type" (polymorphic attributes)
return false if attribute_name.ends_with?('_type')
true
end
# {
# "id" => :uuid,
# "description" => :text,
# "position" => :integer,
# "target_type" => :string,
# "created_at" => :datetime,
# "updated_at" => :datetime,
# "target_id" => :uuid,
# "university_id" => :uuid
# }
def attributes_with_type
self.class.columns_hash.map { |name, value| [name, value.type] }.to_h
end
end
end
......@@ -21,9 +21,9 @@
# fk_rails_f61d27545f (university_id => universities.id)
#
class Research::Laboratory < ApplicationRecord
include Aboutable
include Sanitizable
include WithGit
include Aboutable
belongs_to :university
has_many :websites,
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment