16

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
1
  • What are you trying to do? SafeBuffer is a string already.
    – matt
    Mar 27, 2013 at 8:55

3 Answers 3

43

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.

6
  • this is totally true, there should not be a need to create safe buffers.
    – phoet
    Mar 27, 2013 at 12:19
  • 1
    I needed to do this when something was returning a SafeBuffer in my tests, because CGI.unescapeHTML will break horribly (with 'can't dup NilClass') if it is a SafeBuffer and not a plain string.
    – Tyler Rick
    Dec 20, 2013 at 5:04
  • Thanks for the update! I had never seen String#to_str before. (I had been using Stringe.new(safe_buffer), which also works.)
    – Tyler Rick
    Dec 23, 2013 at 17:11
  • This should be the selected answer. Thanks.
    – hmans
    Jan 26, 2014 at 16:38
  • Alternative, you could use to_param
    – Ja͢ck
    May 7, 2021 at 4:58
11

interpolate it as a string:

irb(main):001:0> "#{ActiveSupport::SafeBuffer.new("asdf")}".class
=> String
1
  • Thank you! Works best in my case, where sometimes I get nil: "#{nil}" results in empty string, whereas String.new(nil) gives an error
    – eagor
    Mar 27, 2013 at 9:42
0

I don't have enough reputation to comment, but I have to supplement that sometimes it's necessary to convert ActiveSupport::SafeBuffer to String.

I met this problem when applying gsub on an ActiveSupport::SafeBuffer object.

s = ActiveSupport::SafeBuffer.new("asdf")
s.gsub(/a/) { puts $1.present? }

$1 would be always nil. You must convert s to String first

s = ActiveSupport::SafeBuffer.new("asdf")
s.to_str.gsub(/a/) { puts $1.present? }

This will return right answer. Even s.to_s is not useful here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.