I'm using the as_json method heavily in a couple of models 开发者_开发问答I have in a project I'm working on, and what I'm trying to do is to display those attributes on the fly ONLY if they are not nil/Null ... does anyone have any idea how to go about this?
You can override as_json
:
# clean_to_json.rb
module CleanToJson
def as_json(options = nil)
super(options).tap do |json|
json.delete_if{|k,v| v.nil?}.as_json unless options.try(:delete, :null)
end
end
end
# foo.rb
class Foo < ActiveRecord::Base
include CleanToJson
end
Usage:
@foo.as_json # Only present attributes
@foo.as_json(:null => true) # All attributes (former behavior)
精彩评论