开发者

select_layout implementation Ruby meta programming

开发者 https://www.devze.com 2023-03-14 07:14 出处:网络
How to implement \"select_layout\" method so that I can transform this code: class Cpu::ContextsController < Cpu::ApplicationController

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::ContextsControlle开发者_运维问答r < 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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消