另一種方法,我在以前的作業中用於從模型中剝離HTML標籤的方法是創建一個插件。我們剝離了很多不僅僅是HTML標籤,但這裏是HTML剝離部分:
的初始化(供應商/插件/剝離器/ init.rb):
require 'active_record/stripper'
ActiveRecord::Base.class_eval do
include ActiveRecord::Stripper
end
剝離代碼(供應商/插件/stripper/lib/active_record/stripper.rb):
module ActiveRecord
module Stripper
module ClassMethods
def strip_html(*args)
opts = args.extract_options!
self.strip_html_fields = args
before_validation :strip_html
end
end
module InstanceMethods
def strip_html
self.class.strip_html_fields.each{ |field| strip_html_field(field) }
end
private
def strip_html_field(field)
clean_attribute(field, /<\/?[^>]*>/, "")
end
def clean_attribute(field, regex, replacement)
self[field].gsub!(regex, replacement) rescue nil
end
end
def self.included(receiver)
receiver.class_inheritable_accessor :strip_html_fields
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
end
然後在您的MyObject類,你可以選擇通過調用剝去領域的html:
class MyObject < ActiveRecord::Base
strip_html :first_attr, :second_attr, :etc
end
感謝邁克,這正是我的意思是,任何想法,爲什麼的lib下「的monkeypatching」文件夾沒有工作?如果你可以用這個更新答案,我相信它會被接受,我會解決這個問題。再次感謝 – 2009-02-28 16:55:07
一般來說,如果你有一個ActiveRecord :: Base的附加,你將它放在lib目錄中,並將其包含在environment.rb中。不過,我同意抽象類更好地解決你的問題。 – 2009-03-01 23:30:00