Module: StripTags

Defined in:
lib/strip-tags/version.rb,
lib/strip-tags/matchers.rb,
lib/strip-tags.rb

Defined Under Namespace

Modules: Matchers

Constant Summary collapse

VERSION =
"1.1.1"
VALID_OPTIONS =
[:only, :except, :allow_empty, :regex, :if, :unless].freeze

Class Method Summary collapse

Class Method Details

.narrow(attributes, options = {}) ⇒ Object

Necessary because Rails has removed the narrowing of attributes using :only and :except on Base#attributes



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/strip-tags.rb', line 51

def self.narrow(attributes, options = {})
  if except = options[:except]
    except = Array(except).collect { |attribute| attribute.to_s }
    attributes.except(*except)
  elsif only = options[:only]
    only = Array(only).collect { |attribute| attribute.to_s }
    attributes.slice(*only)
  else
    attributes
  end
end

.strip(record_or_string, options = {}) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/strip-tags.rb', line 18

def self.strip(record_or_string, options = {})
  if record_or_string.respond_to?(:attributes)
    strip_record(record_or_string, options)
  else
    strip_string(record_or_string, options)
  end
end

.strip_record(record, options = {}) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
# File 'lib/strip-tags.rb', line 26

def self.strip_record(record, options = {})
  attributes = narrow(record.attributes, options)

  attributes.each do |attr, value|
    original_value = value
    value = strip_string(value, options)
    record[attr] = value if original_value != value
  end

  record
end

.strip_string(value, options = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
# File 'lib/strip-tags.rb', line 38

def self.strip_string(value, options = {})
  return value unless value.is_a?(String)
  return value if value.frozen?

  allow_empty = options[:allow_empty]

  value = ActionController::Base.helpers.strip_tags(value).gsub("&amp;", "&").gsub("&gt;", ">").gsub("&lt;", "<")

  (value.blank? && !allow_empty) ? nil : value
end

.validate_options(options) ⇒ Object



63
64
65
66
67
68
69
# File 'lib/strip-tags.rb', line 63

def self.validate_options(options)
  if keys = options.keys
    unless (keys - VALID_OPTIONS).empty?
      raise ArgumentError, "Options does not specify #{VALID_OPTIONS} (#{options.keys.inspect})"
    end
  end
end