select_layout 实现 Ruby 元编程
如何实现“select_layout”方法,以便我可以将此代码转换
class Cpu::ContextsController < Cpu::ApplicationController
layout :select_layout
private
def has_resource?
true # dummy
end
def select_layout
has_resource? ? 'cpu/context' : 'cpu/account'
end
end
为
class Cpu::ContextsController < Cpu::ApplicationController
select_layout do
has_resource? ? 'cpu/context' : 'cpu/account'
end
end
更新:下面的解决方案足够好;)
before_filter do
self.class.send(:layout, has_resource? ? 'cpu/context' : 'cpu/account')
end
How to implement "select_layout" method so that I can transform this code:
class Cpu::ContextsController < Cpu::ApplicationController
layout :select_layout
private
def has_resource?
true # dummy
end
def select_layout
has_resource? ? 'cpu/context' : 'cpu/account'
end
end
into
class Cpu::ContextsController < Cpu::ApplicationController
select_layout do
has_resource? ? 'cpu/context' : 'cpu/account'
end
end
UPDATE: solution below is good enough ;)
before_filter do
self.class.send(:layout, has_resource? ? 'cpu/context' : 'cpu/account')
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 render ..., :layout =>有资源吗? ? "cpu/context" : "cpu/account" 如果您想动态更改布局,
layout
是一个类方法,用于指定方法集的布局。Use
render ..., :layout => has_resource? ? "cpu/context" : "cpu/account"
if you want to change layout on the fly,layout
is a class method and used to specify layout for the set of methods.它找不到 has_resource,因为 has_resource 被定义为实例方法,而 select_layout 方法被定义为类方法。
It can't find has_resource, because has_resource is defined as an instance method and the select_layout method is defined as a class-method.