I am working with a custom renderer, and I used some copy paste from another site. I can’t seem to figure out what this piece is doing right here.
"#{options[:callback]}(#{data})"
Here is the piece of code in full context.
ActionController.add_renderer :as3 do |data, options|
data = ActiveSupport::JSON.encode(data) unless data.respond_to?(:to_str)
data = "#{options[:callback]}(#{data})" unless options[:callback].blank?
self.content_type ||= Mime::JSON
self.response_body = data
end
It’s simple string interpolation. It will produce a string like this, where
callbackis the value ofoptions[:callback], andvalueis whatever is in the variabledata.In Ruby, double-quoted strings support interpolation via
#{}syntax. That is, if you have a variablexcontaining the value3, the string"The value of x is #{x}"will be evaluated to"The value of x is 3". Inside a#{}you can have any arbitrarily complex Ruby expression, including array/hash indexing. So, the first part of the string,"#{options[:callback]}"is simply substituting the value ofoptions[:callback]into the string.The next part, the
()is simply raw string data, not executable code. Inside the(), you have a second#{}substitution ofdata. It might be clearer if you replace the two variable substituions withxandy:The above will evaluate to the string
"3(4)"