在没有模型对象的 Rails 4 中覆盖渲染 :json [英] Override render :json in no model object Rails 4
问题描述
我需要覆盖render json",但我不需要为模型覆盖它,在模型中我知道我可以打开 ActiveRecord::Base 并覆盖 as_json 方法.但我的问题是当我有这样的事情
class TestController <应用控制器定义索引渲染json:{字段:'是一个测试'}结尾结尾
我的问题是因为我使用了一个 gem,其中一些方法我需要返回render json",而这个 gem 没有为此集中一个方法.我认为在做 gem 的 fork 并重构它,因为我可以覆盖集中式方法,但首先我想知道是否可以覆盖渲染.
您可以在那里打开 ActionController::Base 类并覆盖渲染方法.但是,我不确定这是否是最好的主意,这取决于您遇到的实际问题,并且您没有向我们提供有关问题的太多详细信息,即您希望得到什么以及您实际得到什么.>
更新
我可能会喜欢:
class ActionController::Basedef 渲染 *args选项 = args.extract_options!如果选项[:json]\\在这里做任何你需要的事情结尾参数<<选项超级*参数结尾结尾
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.
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
这篇关于在没有模型对象的 Rails 4 中覆盖渲染 :json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!