Class: Findr::Encoder::Iconv

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(other_coding) ⇒ Iconv

Returns a new instance of Iconv.



4
5
6
# File 'lib/findr/encoder/iconv.rb', line 4

def initialize( other_coding )
  @other_coding = other_coding.split(',')
end

Class Method Details

.listObject

Returns a list of valid encodings



36
37
38
39
40
# File 'lib/findr/encoder/iconv.rb', line 36

def self.list
  return ::Iconv.list
rescue
  fail Error, "Iconv.list not supported on Ruby #{RUBY_VERSION}. Try 'iconv -l' on the command line."
end

Instance Method Details

#decode(string) ⇒ Object

Encodes given string from @other_coding to utf8.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/findr/encoder/iconv.rb', line 9

def decode( string )
  coding = nil
  coded_string = nil
  have_valid_coding = @other_coding.any? do |c|
    begin
      coded_string = ::Iconv.conv('UTF-8', c, string)
      coding = c
      true
    rescue
      false
    end
  end
  fail Error.new("No valid coding given.") unless have_valid_coding
  return [coded_string, coding.to_s.upcase]
rescue
  raise Error, "Error when decoding from '#{@other_coding}' into 'UTF-8': #{$!}"
  return
end

#encode(string, coding) ⇒ Object

Encodes given utf8 string into coding.



29
30
31
32
33
# File 'lib/findr/encoder/iconv.rb', line 29

def encode( string, coding )
  return ::Iconv.conv(coding, 'UTF-8', string)
rescue
  raise Error, "Error when encoding from 'UTF-8' into '#{coding}'."
end