 |
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.
|
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. :)