Override render :json in no model object Rails 4

为君一笑 提交于 2019-12-12 14:25:59

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!