Ruby Mixins 和实例变量
是否有将参数传递给混合方法的最佳实践方法?
使用 mixin 的类可以设置混合方法期望的实例变量,或者可以将所有必要的参数作为参数传递给混合方法。
背景是我们有一个 Rails 控制器来发布内容 - 但其他控制器甚至模型都需要能够“充当发布者”,所以我将控制器方法分解为一个模块,我将其混合为需要。
例如,这里是来自 Rails 控制器的代码,它需要“充当发布者”,并且它调用混合方法 Question_xhtml()...
def preview
@person = Person.find params[:id]
@group = Group.find params[:parent_id]
@div = Division.find params[:div_id]
@format = 'xhtml'
@current_login = current_login
xhtml = person_xhtml() # CALL TO MIXED-IN METHOD
render :layout => false
end
最终 Question_xhtml 需要所有这些东西!这种方法是否合理,还是最好做
def preview
person = Person.find params[:id]
group = Group.find params[:parent_id]
div = Division.find params[:div_id]
format = 'xhtml'
xhtml = person_xhtml(person, group, div, format) # CALL TO MIXED-IN METHOD
render :layout => false
end
……或其他事情?
Is there a best practice way to pass params to mixed-in methods?
The class using the mixin could set up instance variables which mixed-in methods expect, or it could pass all necessary params as arguments to mixed-in methods.
The background to this is that we have a Rails controller which does publishing of content - but other controllers and even Models need to be able to "act as publshers" so I'm factoring the controllers methods into a Module which I'll mixin as needed.
Here, for example, is code from a Rails Controller which needs to "act as publisher" and it calls a mixed-in method question_xhtml()...
def preview
@person = Person.find params[:id]
@group = Group.find params[:parent_id]
@div = Division.find params[:div_id]
@format = 'xhtml'
@current_login = current_login
xhtml = person_xhtml() # CALL TO MIXED-IN METHOD
render :layout => false
end
Ultimately question_xhtml needs all that stuff! Is this approach reasonable, or would it be better to do
def preview
person = Person.find params[:id]
group = Group.find params[:parent_id]
div = Division.find params[:div_id]
format = 'xhtml'
xhtml = person_xhtml(person, group, div, format) # CALL TO MIXED-IN METHOD
render :layout => false
end
...or something else?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你应该能够做到:
如果你使用脚本/生成插件 act_as_publisher。
I think you should be able to do:
if you used script/generate plugin act_as_publisher.