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.



3
4
5
# File 'lib/better_record/encoder.rb', line 3

def initialize(str)
  @str = str
end

Instance Method Details

#find_encodingObject



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

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:

  • (Boolean)


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

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:

  • (Boolean)


27
28
29
# File 'lib/better_record/encoder.rb', line 27

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

#is_utf8?Boolean

Returns:

  • (Boolean)


23
24
25
# File 'lib/better_record/encoder.rb', line 23

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

#is_windows?(str) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/better_record/encoder.rb', line 31

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

#to_utf8Object



7
8
9
10
11
# File 'lib/better_record/encoder.rb', line 7

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