问题
I need override "render json" but I don't need override this for models, in models I know that I can open up ActiveRecord::Base and overriding as_json method. But my problem is when I have something like this
class TestController < ApplicationController
def index
render json: { field: 'is a test' }
end
end
My problem is because I use a gem in which some methods I need to return "render json" and this gem not has centralized a method for this. I think in do fork of the gem and refactor this for I can overriding centralized method, but first I want to know if is possible overriding the render.
回答1:
You can open ActionController::Base class and override render method there. However I am not sure whether this is the best idea, it depends on actual trouble you are having and you didn't give us too much details about the problem, i.e. what would you expect to get and what you are actually getting.
UPDATE
I would probably go with sth like:
class ActionController::Base
def render *args
options = args.extract_options!
if options[:json]
\\ do whatever you need here
end
args << options
super *args
end
end
来源:https://stackoverflow.com/questions/19997061/override-render-json-in-no-model-object-rails-4