For user inputed data I am taking the approach of sanitizing it before saving to strip out any html or anything malicious (i.e. tags).
I have a before_validation callback:
before_validation :sanitize_fields
def sanitize_fields
full_sanitizer = Rails::Html::FullSanitizer.new
white_list = Rails::Html::WhiteListSanitizer.new
# Only text allowed
self.fname = full_sanitizer.sanitize(self.fname)
self.lname = full_sanitizer.sanitize(self.lname)
self.company = full_sanitizer.sanitize(self.company)
# Some HTML Allowed
self.description = white_list.sanitize(self.description)
end
The problem I am encountering is that when saving something like "Smith & Company" as the name it is stored in the DB as Smith & Company. Not an issue per se, but then it also displays as Smith & Company in the edit view of the form, which seems funny and confusing to the end user.
Is there a better way than the approach I am taking? This "smells" wrong to me.
Thanks!
If you are confident the data is sanitized, you can declare it html_safe in the views to avoid it showing up as &; it will render exactly as provided.
This of course begs the question: rather than jump through hoops to pre-sanitize and then tell the view that it has been sanitized, why not just allow the view to sanitize strings like it does by default? If you render the string "<tag>some_stuff</tag>" in a view, it will escape it for you. Are you concerned about the unsanitized string appearing elsewhere other than in a view that you control?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With