Last active
April 18, 2020 06:56
-
-
Save amolpujari/35ba058a473a9a8c2f7210b9d3fdbf49 to your computer and use it in GitHub Desktop.
rails 5 application record text sanitizer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module TextSanitizer | |
extend ActiveSupport::Concern | |
SKIP_COLUMNS = %w{encrypted_password confirmation_token current_sign_in_ip expires_at image image_url last_sign_in_ip refresh_token} | |
included do | |
include ::SanitizerHelper | |
extend ::SanitizerHelper | |
before_validation :__sanitize_text_and_string | |
end | |
def __sanitize_text_and_string | |
__sanitize_text | |
__sanitize_string | |
end | |
def __sanitize_text | |
_columns = self.class.text_columns | |
if is_a? User | |
_columns -= ::TextSanitizer::SKIP_COLUMNS | |
end | |
_columns.each do |attr| | |
next unless self.send "will_save_change_to_#{attr}?" | |
sanitized_text = sanitize self.send(attr) | |
self.send "#{attr}=", sanitized_text | |
end | |
end | |
def __sanitize_string | |
_columns = self.class.string_columns | |
if is_a? User | |
_columns -= ::TextSanitizer::SKIP_COLUMNS | |
end | |
_columns.each do |attr| | |
next unless self.send "will_save_change_to_#{attr}?" | |
sanitized_text = sanitize self.send(attr) | |
sanitized_string = sanitized_text.gsub(/\s+/, " ").strip if sanitized_text | |
sanitized_string = nil if sanitized_string.blank? | |
self.send "#{attr}=", sanitized_string | |
end | |
end | |
module ClassMethods | |
def text_columns | |
@__text_columns ||= self.columns_hash.map{ |k,v| k if v.type == :text }.compact | |
end | |
def string_columns | |
@__text_columns ||= self.columns_hash.map{ |k,v| k if v.type == :string }.compact | |
end | |
end | |
end | |
ApplicationRecord.send :include, ::TextSanitizer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment