Class: RSpec::Support::EncodedString

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec/support/encoded_string.rb

Constant Summary collapse

UTF_8 =

Reduce allocations by storing constants.

"UTF-8"
US_ASCII =
"US-ASCII"
REPLACE =

In MRI 2.1 ‘invalid: :replace’ changed to also replace an invalid byte sequence see github.com/ruby/ruby/blob/v2_1_0/NEWS#L176 www.ruby-forum.com/topic/6861247 twitter.com/nalsh/status/553413844685438976

For example, given:

"\x80".force_encoding("Emacs-Mule").encode(:invalid => :replace).bytes.to_a

On MRI 2.1 or above: 63 # ‘?’ else : 128 # “x80”

Ruby’s default replacement string is:

U+FFFD ("\xEF\xBF\xBD"), for Unicode encoding forms, else
?      ("\x3F")
"?"
ENCODE_UNCONVERTABLE_BYTES =
{
  :invalid => :replace,
  :undef   => :replace,
  :replace => REPLACE
}
ENCODE_NO_CONVERTER =
{
  :invalid => :replace,
  :replace => REPLACE
}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string, encoding = nil) ⇒ EncodedString

Returns a new instance of EncodedString.



34
35
36
37
38
# File 'lib/rspec/support/encoded_string.rb', line 34

def initialize(string, encoding=nil)
  @encoding = encoding
  @source_encoding = detect_source_encoding(string)
  @string = matching_encoding(string)
end

Instance Attribute Details

#source_encodingObject (readonly)

Returns the value of attribute source_encoding.



39
40
41
# File 'lib/rspec/support/encoded_string.rb', line 39

def source_encoding
  @source_encoding
end

Class Method Details

.pick_encoding(_source_a, _source_b) ⇒ Object



145
146
147
# File 'lib/rspec/support/encoded_string.rb', line 145

def self.pick_encoding(source_a, source_b)
  Encoding.compatible?(source_a, source_b) || Encoding.default_external
end

Instance Method Details

#<<(string) ⇒ Object



46
47
48
# File 'lib/rspec/support/encoded_string.rb', line 46

def <<(string)
  @string << matching_encoding(string)
end

#split(regex_or_string) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/rspec/support/encoded_string.rb', line 51

def split(regex_or_string)
  @string.split(matching_encoding(regex_or_string))
rescue ArgumentError
  # JRuby raises an ArgumentError when splitting a source string that
  # contains invalid bytes.
  remove_invalid_bytes(@string).split regex_or_string
end

#to_sObject Also known as: to_str



64
65
66
# File 'lib/rspec/support/encoded_string.rb', line 64

def to_s
  @string
end