我需要重写“render json”,但我不需要为模型重写它,在模型中我知道我可以打开 ActiveRecord::Base 并重写 as_json 方法。但我的问题是当我遇到这样的事情时
class TestController < ApplicationController
def index
render json: { field: 'is a test' }
end
end
我的问题是因为我使用了一个 gem,其中一些方法我需要返回“render json”,而这个 gem 没有为此集中一个方法。我认为在做 gem 的分支并重构它,因为我可以覆盖集中式方法,但首先我想知道是否有可能覆盖渲染。
最佳答案
您可以打开 ActionController::Base 类并在那里覆盖渲染方法。但是我不确定这是否是最好的主意,这取决于您遇到的实际问题,并且您没有向我们提供有关问题的太多详细信息,即您希望得到什么以及实际得到什么。
更新
我可能会选择这样的东西:
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
关于ruby-on-rails - 覆盖渲染 :json in no model object Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19997061/