Class: BetterRecord::Encoder

Inherits:
Object
  • Object
show all
Defined in:
lib/better_record/encoder.rb

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ Encoder

Returns a new instance of Encoder.



5
6
7
# File 'lib/better_record/encoder.rb', line 5

def initialize(str)
  @str = str
end

Instance Method Details

#find_encodingObject



15
16
17
18
19
20
21
22
23
# File 'lib/better_record/encoder.rb', line 15

def find_encoding
  puts 'utf-8' if is_utf8?
  return 'utf-8' if is_utf8?
  puts 'iso-8859-1' if is_iso8859?
  return 'iso-8859-1' if is_iso8859?
  puts 'Windows-1252' if is_windows?
  return 'Windows-1252' if is_windows?
  raise ArgumentError.new "Invalid Encoding"
end

#is_encoding?(encoding_check) ⇒ Boolean

Returns:



37
38
39
40
41
42
43
44
45
46
# File 'lib/better_record/encoder.rb', line 37

def is_encoding?(encoding_check)
  case @str.encoding
  when encoding_check
    @str.valid_encoding?
  when Encoding::ASCII_8BIT, Encoding::US_ASCII
    @str.dup.force_encoding(encoding_check).valid_encoding?
  else
    false
  end
end

#is_iso8859?Boolean

Returns:



29
30
31
# File 'lib/better_record/encoder.rb', line 29

def is_iso8859?
  is_encoding?(Encoding::ISO_8859_1)
end

#is_utf8?Boolean

Returns:



25
26
27
# File 'lib/better_record/encoder.rb', line 25

def is_utf8?
  is_encoding?(Encoding::UTF_8)
end

#is_windows?(str) ⇒ Boolean

Returns:



33
34
35
# File 'lib/better_record/encoder.rb', line 33

def is_windows?(str)
  is_encoding?(Encoding::Windows_1252)
end

#to_utf8Object



9
10
11
12
13
# File 'lib/better_record/encoder.rb', line 9

def to_utf8
  return @str if is_utf8?
  encoding = find_encoding
  @str.force_encoding(encoding).encode('utf-8', invalid: :replace, undef: :replace)
end