Module: DumbQuotes::ArExtend

Defined in:
lib/dumb_quotes/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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/dumb_quotes/ar_extend.rb', line 29

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

#dumb_quotes!(options = nil) ⇒ Object

Strips whitespace from model fields and converts blank values to nil.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/dumb_quotes/ar_extend.rb', line 6

def dumb_quotes!(options = nil)
  before_validation do |record|
    attributes = DumbQuotes::ArExtend.narrow(record.attributes, options)
    attributes.each do |attr, value|
      if value.respond_to?(:gsub)
        # single quotes
        value = value.gsub("\xE2\x80\x98","'") # U+2018
        value = value.gsub("\xE2\x80\x99","'") # U+2019
        value = value.gsub("\xCA\xBC","'")     # U+02BC

        #  double quotes
        value = value.gsub("\xE2\x80\x9C",'"') # U+201C
        value = value.gsub("\xE2\x80\x9D",'"') # U+201D
        value = value.gsub("\xCB\xAE",'"')     # U+02EE

        record[attr] = value
      end
    end
  end
end