| 1 |
module AlexPayne |
|---|
| 2 |
module Acts #:nodoc: all |
|---|
| 3 |
module Sanitized |
|---|
| 4 |
def self.included(base) |
|---|
| 5 |
# Walter McGinnis, 2008-01-09 |
|---|
| 6 |
# update to work with Rails 2.0 |
|---|
| 7 |
base.extend(ActionView::Helpers::SanitizeHelper::ClassMethods) |
|---|
| 8 |
|
|---|
| 9 |
base.extend(ClassMethods) |
|---|
| 10 |
end |
|---|
| 11 |
|
|---|
| 12 |
module ClassMethods |
|---|
| 13 |
def acts_as_sanitized(options = {}) |
|---|
| 14 |
before_save :sanitize_fields |
|---|
| 15 |
|
|---|
| 16 |
write_inheritable_attribute(:acts_as_sanitized_options, { |
|---|
| 17 |
:fields => options[:fields], |
|---|
| 18 |
:strip_tags => options[:strip_tags] |
|---|
| 19 |
}) |
|---|
| 20 |
|
|---|
| 21 |
class_inheritable_reader :acts_as_sanitized_options |
|---|
| 22 |
|
|---|
| 23 |
# discover sanitizable (string and text) fields if none specified |
|---|
| 24 |
unless acts_as_sanitized_options[:fields] |
|---|
| 25 |
acts_as_sanitized_options[:fields] = [] |
|---|
| 26 |
|
|---|
| 27 |
self.columns.each do |column| |
|---|
| 28 |
if column.type == :string || column.type == :text |
|---|
| 29 |
acts_as_sanitized_options[:fields].push(column.name) |
|---|
| 30 |
end |
|---|
| 31 |
end |
|---|
| 32 |
end |
|---|
| 33 |
|
|---|
| 34 |
include AlexPayne::Acts::Sanitized::InstanceMethods |
|---|
| 35 |
end |
|---|
| 36 |
end |
|---|
| 37 |
|
|---|
| 38 |
module InstanceMethods |
|---|
| 39 |
# Walter McGinnis, 2008-01-09 |
|---|
| 40 |
# update to work with Rails 2.0 |
|---|
| 41 |
include ActionView::Helpers::SanitizeHelper |
|---|
| 42 |
def sanitize_fields |
|---|
| 43 |
if acts_as_sanitized_options[:strip_tags] == true |
|---|
| 44 |
acts_as_sanitized_options[:fields].each do |field| |
|---|
| 45 |
strip_tags_field(field) |
|---|
| 46 |
end |
|---|
| 47 |
else |
|---|
| 48 |
# Walter McGinnis, 2008-01-09 |
|---|
| 49 |
# allow for turning off sanitization on a record by record basis |
|---|
| 50 |
# for cases like a site admin adding a form |
|---|
| 51 |
# via virtual attribute on record |
|---|
| 52 |
do_not_sanitize = !self.do_not_sanitize.nil? && (self.do_not_sanitize.to_i == 1 || self.do_not_sanitize == true) ? true : false |
|---|
| 53 |
unless do_not_sanitize |
|---|
| 54 |
acts_as_sanitized_options[:fields].each do |field| |
|---|
| 55 |
sanitize_field(field) |
|---|
| 56 |
end |
|---|
| 57 |
end |
|---|
| 58 |
end |
|---|
| 59 |
end |
|---|
| 60 |
|
|---|
| 61 |
def sanitize_field(field) |
|---|
| 62 |
content = self[field.to_sym] |
|---|
| 63 |
self[field.to_sym] = sanitize(content) unless content.nil? |
|---|
| 64 |
end |
|---|
| 65 |
|
|---|
| 66 |
def strip_tags_field(field) |
|---|
| 67 |
content = self[field.to_sym] |
|---|
| 68 |
self[field.to_sym] = strip_tags(content) unless content.nil? |
|---|
| 69 |
end |
|---|
| 70 |
end |
|---|
| 71 |
end |
|---|
| 72 |
end |
|---|
| 73 |
end |
|---|