【问题标题】:Rails 3.0 Mobile SiteRails 3.0 移动网站
【发布时间】:2011-12-02 16:14:10
【问题描述】:

我想知道如何创建 Rails 3.0 应用程序的移动版本。

我看到了这个帖子:Mobile version of views for Ruby on Rails

但我对 respond_to 方法感到困惑。该方法如何知道要渲染哪种格式?

我是否要在我的应用程序控制器中创建一个方法来呈现移动布局,然后为每个视图使用 respond_to 方法?

谢谢,

布赖恩

【问题讨论】:

  • 别忘了在布局文件中添加 xhtml 移动 DTD ttp://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd" rel="nofollow" target="_blank">openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">

标签: ruby-on-rails


【解决方案1】:

Ryan Bates 做了一个很棒的教程

http://railscasts.com/episodes/199-mobile-devices

【讨论】:

  • 谢谢!该教程帮助很大。
【解决方案2】:

respond_to 方法会根据当前请求的 mime 类型进行选择。

这对于常见的 mime 类型是开箱即用的,但您需要告诉您的应用程序您的自定义类型。在您的应用程序控制器中,您需要定义一个方法来调整 Rails 内部请求表示的格式。然后,将该方法作为前置过滤器调用。这是一个例子:

class ApplicationController < ActionController::Base
  before_filter :adjust_for_mobile

  def adjust_for_mobile
    request.format = :mobile if mobile_request
  end

  # You'll also need to define the mobile_request method
  # using whatever strategy you want to tell if a request
  # is from a mobile client or not
  def mobile_request
    true
  end
end

确保你已经在 config/initializers/mime_types.rb 中定义了这个新类型:

Mime::Type.register "text/html", :mobile

然后,在您的控制器中,您将能够使用“移动”格式:

class FoosController < ApplicationController
  def index
    @foos = Foo.all

    respond_to do |format|
      format.html   # index.html.erb
      format.mobile # index.mobile.erb
    end
  end
end

这确实看起来很优雅,但实际上,我发现我很少将它用于移动网站。我一直在开发的移动网站通常与“完整”网站完全不同。在这些情况下,在“移动”命名空间下定义另一组控制器是有意义的。

【讨论】:

    【解决方案3】:

    看看Rails Mobile

    我不久前开发了那个插件。该插件背后的想法是您可以通过路由器配置文件根据您的移动设备功能重定向到不同的控制器或视图。

    在 routing.rb 的末尾添加以下几行:

    MobileDispatch::Categories.add do
    
    def mobile_classifier(device)
      "_mobile"
    end
    end
    

    这些行为所有移动设备定义了一个新的子字符串,该子字符串将存储在 roging.rb 文件中每个请求的 $ 变量中。

    这样您就可以使用您的路由规则。例如 routing.rb 中的这一行:

    匹配 '/photo/:id', :to => "photo#index$", :classifier => :mobile_classifier

    对于普通用户会被解释为:

    匹配 '/photo/:id', :to => "photo#index", :classifier => :mobile_classifier

    对于移动用户来说:

    匹配 '/photo/:id', :to => "photo#index_mobile", :classifier => :mobile_classifier

    这里的强大之处在于 mobile_classifier(device) 方法,您可以根据设备对象返回不同的分类。

    假设我们修改方法,为所有 iphone 设备返回“_iphone”,为所有 android 手机返回“_android”,那么上面的路由行将被解释为:

    匹配 '/photo/:id', :to => "photo#index_iphone", :classifier => :mobile_classifier

    匹配 '/photo/:id', :to => "photo#index_android", :classifier => :mobile_classifier

    如果您将 $ 添加到每个路由的视图末尾部分(类似于我们在此处所做的),您将在控制器中为每种设备类别获得不同的方法,并为每种方法获得不同的视图名称(index_iphone.htm.htm)。 erb 和 index_android.ht.erb) 这样您就可以为您在 mobile_classifier 方法中定义的每个设备类别提供单独的视图/层。

    【讨论】:

    • 所以使用插件应用程序仍然调用该方法,但如果请求来自移动设备,它会呈现移动视图?它会自动检测移动设备吗?这个插件支持哪些移动设备?
    • 抱歉,移动版面呢?有没有办法使用这个插件来呈现移动布局,或者我只是向我的应用程序控制器添加一个方法?
    • 对不起,我没有看到你的第二个问题。请检查我的更新答案
    猜你喜欢
    • 2013-01-01
    • 2016-07-04
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 2018-10-17
    相关资源
    最近更新 更多