-1

I need to output (say, display in the browser) a variable value that lives inside Ruby sinatra controller :

get '/endpoint' do        
  someVariable = MyModel.All
  # print/output/dump someVariable value !
end

I've tried put, puts, print... nothing helps.

Pierre-Adrien
  • 2,836
  • 29
  • 30
  • Are you trying to "print" to the browser or the terminal? If its the browser, you need to render some kind of template where you loop over and utilize `someVariable`. If you want to see the variable value in your terminal, try `require 'pp'` and then `pp someVariable` – ghstcode May 19 '18 at 23:25
  • I remember doing it to the brower in a very simple way. Can't add any 'require' since is a foreign project. It is very annoying trying to do something very simple with more than one step. Thanks – Rodrigo Silva May 21 '18 at 01:14

1 Answers1

0

The easy method that you're looking for is simply to return a string. This string would then be displayed in your browser.

Note: puts, p, etc. print the values in the server log, and not in the browser. That can be useful as well, but apparently not what you were looking for.


Attention #1, in your case, you're returning a collection of objects. This is not a string and won't be properly understood by Sinatra, therefore you won't be able to see anything in your browser. One solution is to serialize your object before sending it to the browser:

get '/' do
  ..
  object.to_s   # or object.to_json
end 

Attention #2 (tricky one :)): an object transformed serialized through to_s or to_json might end up in this kind of format:

#<OpenStruct name="John Doe", age=44>

In that case, your browser will detect opening/closing brackets (< and >) and will attempt to interpret this as a HTML tag, and the content displayed in the browser will be empty, or only the leading # character in the given example. To avoid this, you can force the content-type of the response, so that it doesn't try and interpret the response as HTML and just display raw characters:

get '/' do
  ..
  content_type :txt
  object.to_s  # or object.to_json
end
Pierre-Adrien
  • 2,836
  • 29
  • 30