重构“渲染格式”在多个控制器中
所以我在多个控制器中有一个视图方法,它们看起来几乎完全相同:
def show
show! do |format|
format.json do
if @text.activated?
@text.log
render_for_api :texts_all, :json => @text
else
render :nothing => true
end
end
format.pdf do
pdf = QrPdf.new(@text)
send_data pdf.render, filename: "text_#{@text.id}.pdf", type: "application/pdf"
end
end
end
模型不同,但它们都具有此方法中使用的相同属性(activated
,日志
,id
)。我还可以将 render_for_api
给定的哈希值从当前的 texts_all
、documents_all
等更改为到处都相同的哈希值。
有没有办法在多个模型中使用此代码而不需要大量重复?
我感谢每一个提示! 特别是我发现很难处理 do |format|
块。但我也不确定将代码放在哪里以及如何将其与不同类型的模型一起使用。
谢谢。
so i've got a view method in multiple controllers which mostly looks exactly the same:
def show
show! do |format|
format.json do
if @text.activated?
@text.log
render_for_api :texts_all, :json => @text
else
render :nothing => true
end
end
format.pdf do
pdf = QrPdf.new(@text)
send_data pdf.render, filename: "text_#{@text.id}.pdf", type: "application/pdf"
end
end
end
the models for this are different, but they all have the same attributes that are used in this method (activated
, log
, id
). i also could change the render_for_api
given hash from which is currently texts_all
, documents_all
etc to a hash that its everywhere the same.
is there a way to use this code in multiple models without having this enormous duplication?
i'm thankful for every hint!
especially i find it hard to deal with the do |format|
block. but also i'm not sure where to put the code and how to use it with different types of models.
thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果模型确实是通用的:
我不确定
show!
是什么,但是您可以弄清楚这部分。粗略地(未经测试):就
show_model
所在的位置而言,我倾向于将类似的东西放入基本控制器中,或者作为 mixin,但可能有更好的选择。由于我通常有一个基础控制器,因此很容易将其保留在那里。If the model is truly generic:
I'm not sure what
show!
is, but that part you can figure out. Roughly (untested):As far as where
show_model
lives, I tend to put things like that into a base controller, or as a mixin, but there may be better options. Since I usually have a base controller, it's just easy to keep it there.