Permalink
Browse files

Add possibility to associate an encoding when converting to a String

  • Loading branch information...
1 parent 5324f2d commit 961ceb100dfbb865a9fbfe549c5dcc4f823dde7a @emboss committed May 2, 2012
Showing with 10 additions and 4 deletions.
  1. +3 −2 lib/bytestring.rb
  2. +7 −2 spec/bytestring_spec.rb
View
@@ -106,8 +106,9 @@ def concat(other)
end
alias :<< :concat
- def to_s
- String.new(@inner)
+ def to_s(encoding=nil)
+ s = String.new(@inner)
+ encoding ? s.force_encoding(encoding) : s
end
def to_hex
@@ -241,18 +241,23 @@
end
describe "#to_s" do
- context "returns a String with Encoding::BINARY" do
+ context "returns a String with Encoding::BINARY when given no arguments" do
context "when created from a default String" do
it { string.to_s.encoding.should == Encoding::BINARY }
end
context "when created from a String with an associated encoding" do
- it "is agnostic of String encodings and works on the raw bytes" do
+ it "is agnostic of String encodings and works on the raw bytes when given no arguments" do
s = ByteString.new(utf8).to_s
s.encoding.should == Encoding::BINARY
s.should == "\xc3\xa4"
end
end
+
+ context "when given an encoding, it associates it with the string returned" do
+ it { string.to_s(Encoding::UTF_8).encoding.should == Encoding::UTF_8 }
+ it { ByteString.new(utf8).to_s(Encoding::UTF_8).encoding.should == Encoding::UTF_8 }
+ end
end
end

0 comments on commit 961ceb1

Please sign in to comment.