Search code examples
ruby-on-railsrubypry

How replicate rails console output style in runner script?


When running User.first in the rails console I will get a beautiful output, something like:

beautiful output in rails console

I assume this is taken care of by pry. How can I get the same output styling when using the runner? Consider a file tinker.rb

u = User.first
puts u

and running it like: rails r './tinker.rb. While it will output something, it is not as polished as in the console:

#<User:0x00007fc6518acec8>

How can I make it exactly the same?


Solution

  • This formatting is a result of PrettyPrint module - PP:

    u = User.first
    pp u #=> Which is basically a shortcut for: PP.pp(u)
    

    Note however, that by default this will not generate a colourful output. Pry additionally process the formatted string through another gem - coderay, which is responsible for ruby syntax highlighting. If you want to print in colour, then:

    u = User.first
    Pry::ColorPrinter.pp(u)