Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert ActiveSupport::SafeBuffer to String?

Tags:

ruby

I want to get String object out of ActiveSupport::SafeBuffer. Method to_s returns the same type ActiveSupport::SafeBuffer. Only to_sym.to_s returns String, but this is more of a hack. Here's my console playing:

irb(main):008:0> s = ActiveSupport::SafeBuffer.new("asdf")
# => "asdf"
irb(main):009:0> s.class
# => ActiveSupport::SafeBuffer
irb(main):010:0> s.to_s.class
# => ActiveSupport::SafeBuffer
irb(main):011:0> s.to_sym.to_s
# => "asdf"
irb(main):012:0> s.to_sym.to_s.class
# => String
like image 709
eagor Avatar asked Mar 27 '13 08:03

eagor


2 Answers

There's actually a method for this: String#to_str

buf = ActiveSupport::SafeBuffer.new("asdf")

str = buf.to_str #=> "asdf"
str.class        #=> String

String#to_str works exactly like String#to_s: it returns the receiver, converting it to String if necessary. But unlike the overridden ActiveSupport::SafeBuffer#to_s there's no ActiveSupport::SafeBuffer#to_str so the original method is called.


Note that ActiveSupport::SafeBuffer is a subclass of String:

s = ActiveSupport::SafeBuffer.new("asdf")
s.is_a? String
# => true

So there's often no need to convert it at all.

like image 63
Stefan Avatar answered Oct 20 '22 15:10

Stefan


interpolate it as a string:

irb(main):001:0> "#{ActiveSupport::SafeBuffer.new("asdf")}".class
=> String
like image 21
phoet Avatar answered Oct 20 '22 15:10

phoet