Module: ReplaceEntities::ArExtend

Defined in:
lib/replace_entities/ar_extend.rb

Class Method Summary collapse

Instance 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



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/replace_entities/ar_extend.rb', line 20

def self.narrow(attributes, options)
  if options.nil?
    attributes
  else
    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
      raise ArgumentError, "Options does not specify :except or :only (#{options.keys.inspect})"
    end
  end
end

Instance Method Details

#replace_entities!(options = nil) ⇒ Object

Strips ASCII control chars from attributes before they get saved



6
7
8
9
10
11
12
13
14
15
16
# File 'lib/replace_entities/ar_extend.rb', line 6

def replace_entities!(options = nil)
  before_validation do |record|
    attributes = ReplaceEntities::ArExtend.narrow(record.attributes, options)
    attributes.each do |attr, value|
      if value.is_a?(String)
        coder = HTMLEntities.new
        record[attr] = coder.decode(value)
      end
    end
  end
end