Blog » Blog Entry

Clean your Ruby on Rails ActiveRecords automatically

November 28, 2007

Let's say you need to make your Rails app have a field for users to put stuff in. Dangerous huh? The open nature of Ruby makes it simple to cleanup:

app/model/cleaner.rb:
---------------------
module Cleaner
  def self.append_features( base )
    base.before_save do |model|
      model.html = model.html.gsub( /<(.|\n)*?>/, '' )\
        if model.respond_to?( :html )
    end
  end
end

add to config/environment.rb:
-----------------------------
require "#{RAILS_ROOT}/app/models/cleaner"
class ActiveRecord::Base
  include Cleaner
end

Now any columns named 'html' in any of your models will get cleaned of any html tags.

Tags: rubyonrails, html, strip, tags

« Gmail Crashes Firefox Oracle needed an enema »

Why a Model?

By: Rev. Dan <doktahworm at gmail dot com>

Posted: 10 months ago

Cool, useful tip! Thanks!

I'm curious as to why you put it in the Models directory as a Module vs. adding it to application.rb/ or in a helper. I've never quite understood where to put stuff like that. :)

Model Mixin

By: Greg Donald <gdonald at gmail dot com>

Posted: 10 months ago

"include Cleaner" mixes the Cleaner module into the ActiveRecord module extending the "model" part of Rails.

You could put it most anywhere I suppose but to me it's more like a model than a configuration option.

Add a comment:

Title:

Comment:

Name:

Email: