2015-11-03 134 views
4

我正在寫一個rails應用程序,需要爲移動用戶提供不同的鏈接給普通的網頁瀏覽器用戶。例如,如果用戶在移動我想顯示:檢測網頁瀏覽器或手機顯示鏈接

<a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a> 

如果用戶是在瀏覽器上我想顯示:

<a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a> 

什麼是做到這一點的最好方法是什麼?由於

回答

6

瀏覽器數據來自於user_agent對象的形式:

#app/controllers/application_controller.rb 
class ApplicationController < ActionController::Base 
    helper_method :mobile? 

    private 

    def mobile? # has to be in here because it has access to "request" 
     request.user_agent =~ /\b(Android|iPhone|iPad|Windows Phone|Opera Mobi|Kindle|BackBerry|PlayBook)\b/i 
    end 
end 

這將允許你使用你的看法如下:

#app/views/controller/view.html.erb 
<% if mobile? %> 
    ... do something for mobile 
<% else %> 
    ... do something else 
<% end %> 

誠實,我不知道爲什麼人們對他們的移動界面工作進行硬編碼。如果您正確使用CSS media queries,則不應該對這些文件有任何問題,儘管您的情況看起來需要服務器端條件。

-2

我建議你使用像引導或基金會的前端工作。這些框架允許您定位到移動視圖和桌面視圖。

+1

我使用的引導,但我仍然需要以確定其移動設備來顯示不同的鏈接...需要這個答案詳細信息,我覺得:) – fixulate

0

我猜測你想實現deep linking。爲此,我建議你使用deeplink.me。但是,如果你想要這樣做的方式,那麼有一個名爲browser的寶石。以下代碼將幫助您進行設置。

的Gemfile:

gem 'browser' 

然後在

application_controller.rb:

class ApplicationController < ActionController::Base 
    before_filter :get_browser 

    def get_browser 
    @browser = Browser.new(:ua => request.user_agent) 
    end 
end 
在你的意見

最後,你可以這樣做:

<% if @browser.mobile? %> 
    <a href="instagram://user?username=<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a> 
<% else %> 
    <a href="http://instagram.com/<%= photo.author %>" target="_blank" class="btn btn-info btn-block"><i class="fa fa-instagram"></i> Captured by <%= photo.author %></a> 
<% end %> 
+0

真棒,要試試這個! – fixulate

相關問題