root/lib/acts_as_sanitized.rb

Revision 1, 1.8 kB (checked in by al..@al3x.net, 2 years ago)

initial commit

Line 
1 module AlexPayne
2   module Acts #:nodoc: all
3     module Sanitized
4       def self.included(base)
5         base.extend(ClassMethods)
6       end
7
8       module ClassMethods
9         def acts_as_sanitized(options = {})
10           before_save :sanitize_fields
11
12           write_inheritable_attribute(:acts_as_sanitized_options, {
13             :fields => options[:fields],
14             :strip_tags => options[:strip_tags]
15           })
16
17           class_inheritable_reader :acts_as_sanitized_options
18
19           # discover sanitizable (string and text) fields if none specified
20           unless acts_as_sanitized_options[:fields]
21             acts_as_sanitized_options[:fields] = []
22            
23             self.columns.each do |column|
24               if column.type == :string || column.type == :text
25                 acts_as_sanitized_options[:fields].push(column.name)
26               end
27             end
28           end
29          
30           include AlexPayne::Acts::Sanitized::InstanceMethods
31         end
32       end
33
34       module InstanceMethods
35         include ActionView::Helpers::TextHelper
36        
37         def sanitize_fields
38           if acts_as_sanitized_options[:strip_tags] == true
39             acts_as_sanitized_options[:fields].each do |field|
40               strip_tags_field(field)
41             end
42           else
43             acts_as_sanitized_options[:fields].each do |field|
44               sanitize_field(field)
45             end
46           end
47         end
48
49         def sanitize_field(field)
50           content = self[field.to_sym]
51           self[field.to_sym] = sanitize(content) unless content.nil?
52         end
53        
54         def strip_tags_field(field)
55           content = self[field.to_sym]
56           self[field.to_sym] = strip_tags(content) unless content.nil?
57         end
58       end
59     end
60   end
61 end
Note: See TracBrowser for help on using the browser.