控制器的Gem覆盖布局不起作用

时间:2011-12-10 12:23:22

标签: ruby-on-rails ruby-on-rails-3 gem

我目前正在开发一款处理移动设备的宝石。

控制器如下所示:

class PageController < ApplicationController
  has_mobile_views

宝石的代码如下:

module MobileViewsController
  module ClassMethods
    def has_mobile_views(args={})
      class_eval do
        if request.subdomain == 'm'
          request.format = :mobile_html
          layout Proc.new { |controller| controller.request.subdomain == 'm' ? 'mobile_application' : 'application'}
      end
    end
  end
end

格式工作正常,它很好地呈现xxx.mobile_html.haml文件,但不起作用的是加载布局。它不会加载任何布局。

但另一方面,当我改变

 controller.request.subdomain == 'm' ? 'mobile_application' : 'application'

 controller.request.subdomain == 'm' ? 'xmobile_application' : 'application'

它引发了一个错误,即无法找到xmobile_application,因此它必须至少查找它。

这也不起作用:

class PageController < ApplicationController
  has_mobile_views
  layout 'mobile_application'

然而,当我将PageController更改为

class PageController < ApplicationController
  layout 'mobile_application'

正在加载和正确渲染布局。

任何人都知道这里可能出现什么问题,或者宝石中有什么要改变,以免搞砸布局?

1 个答案:

答案 0 :(得分:2)

假设你有

  • mobile_html mime类型已在config/initializers/mime-types.rb
  • 中注册
  • 您在app/views/layouts/mobile_application.mobile_html.erb
  • 中的移动布局 您的MobileViews 中包含
  • ApplicationController个模块

完成这项工作:

module MobileViewsController

  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods

    def has_mobile_views(args = {})
      before_filter Proc.new {
        request.format = :mobile_html if request.subdomain == 'm'
      }

      layout Proc.new { |c|
        c.request.subdomain == 'm' ? 'mobile_application' : 'application'
      }
    end

  end

end