Move sanitize helper to ActiveSupport?

48 views
Skip to first unread message

Mark Reginald James

unread,
Aug 31, 2006, 2:37:18 AM8/31/06
to Ruby on Rails: Core
I wanted to make an ActiveRecord mod that added a "sanitize_html"
function that caused the attributes listed as its parameters to be
automatically stripped of dangerous HTML segments through use of
ActionView::Helpers::TextHelper.sanitize.

It was a bit messy to get working because I had to pull part of
ActionPack into ActiveRecord, and also avoid a clash with the AR
sanitize method (used for database quoting).

To make it much easier to call sanitize in AR I would suggest it be
moved to an ActiveSupport class, and from there made available as a
ActionView helper. I think storing these attributes in sanitized form
is a good alternative to sanitizing on every display.

Perhaps the same should be done for
ActionView::Helpers::TextHelper.strip_tags.

Code for sanitize_html:

class ActiveRecord::Base
def self.sanitize_html(*attrs)
unless ActiveRecord::Base.const_defined?('Sanitization')
require_gem 'actionpack'
ActiveRecord::Base.class_eval <<-EOF
class Sanitization
extend(ActionView::Helpers::TextHelper)
end
EOF
end
before_validation "#{attrs.inspect}.each {|attr| self[attr] =
ActiveRecord::Base::Sanitization.sanitize(self[attr])}"
end
end

Jarkko Laine

unread,
Aug 31, 2006, 3:29:20 AM8/31/06
to rubyonra...@googlegroups.com

On 31.8.2006, at 9.37, Mark Reginald James wrote:

>
> I wanted to make an ActiveRecord mod that added a "sanitize_html"
> function that caused the attributes listed as its parameters to be
> automatically stripped of dangerous HTML segments through use of
> ActionView::Helpers::TextHelper.sanitize.
>
> It was a bit messy to get working because I had to pull part of
> ActionPack into ActiveRecord, and also avoid a clash with the AR
> sanitize method (used for database quoting).
>
> To make it much easier to call sanitize in AR I would suggest it be
> moved to an ActiveSupport class, and from there made available as a
> ActionView helper. I think storing these attributes in sanitized form
> is a good alternative to sanitizing on every display.
>
> Perhaps the same should be done for
> ActionView::Helpers::TextHelper.strip_tags.

Agreed, as well as for textilize and many others. I don't think any
real production app does the textilize process when rendering pages.
Now the helper needs to be hacked (or duplicated) to AR on every app.

//jarkko

--
Jarkko Laine
http://jlaine.net
http://odesign.fi

Reply all
Reply to author
Forward
0 new messages