-
Notifications
You must be signed in to change notification settings - Fork 428
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add option to pretty print #195
Comments
Not all MultiJson adapters support Something like this: # config/initializers/jbuilder_pretty.rb
require "jbuilder"
class Jbuilder
alias_method :_original_target, :target!
def target!
PRETTY_RESPONSE_ENABLED ? JSON.pretty_generate(@attributes) : _original_target
end
end |
Thanks! |
In the context of an API. How might I change |
# config/initializers/jbuilder_pretty.rb
require "jbuilder"
class Jbuilder
alias_method :_original_target, :target!
def prettify_response!
@_pretty_response = true
end
def target!
@_pretty_response ? JSON.pretty_generate(@attributes) : _original_target
end
end # app/views/your-jbuilder-template.json.jbuilder
if @i_want_responses_to_be_pretty
json.prettify_response!
end
json.foo "bar" # app/controllers/your_controller.rb
def your_action
@i_want_responses_to_be_pretty = true
end |
Thanks @rwz. For those who may find their way here, this is what my finial implementation ended up looking like: # config/initializers/jbuilder_prettify.rb
require "jbuilder"
class Jbuilder
##
# Allows you to set @prettify manually in your .jbuilder files.
# Example:
# json.prettify true
# json.prettify false
#
attr_accessor :prettify
alias_method :_original_target, :target!
##
# A shortcut to enabling prettify.
# Example:
# json.prettify!
#
def prettify!
@prettify = true
end
def target!
@prettify ? ::JSON.pretty_generate(@attributes) : _original_target
end
end # app/views/api/v1/users/show.json.jbuilder
json.prettify! if %w(1 yes true).include?(params["pretty"])
json.( @user, :id, :name, :created_at, :updated_at ) |
Thanks! for some weird reason i just have to change ::MultiJson.dump(@attributes, pretty: true) |
FWIW, I just found a pretty simple solution for this. I'm using Jbuilder/MultiJson/Yajl. This initializer will default to pretty output unless you are in production. |
Alternatively, you can just stomp over Active Support's JSON-gem encoder implementation, just for development of course. Put the following in |
@MarkMurphy @rwz Thanks for putting this together years ago. It's 2018 and I just used this without a hitch! 🎉 |
It would be nice to be able to pretty print the json generated by jbuilder. The only solution I've found online to do this is pretty ugly:
The text was updated successfully, but these errors were encountered: