LoginSignup
4
4

More than 5 years have passed since last update.

「Rails + Heroku + Bootstrap」でassetsにサブディレクトリを使用する際の注意点

Last updated at Posted at 2015-02-11

bootstrapのstylesheetを
pc/mobileのサブディレクトリで振り分けた際に問題発生。
localでは正常に動くのに、
staging(とproduction)環境でglyphiconsが☓印になる。なんでだ。

(正確には、モバイル表示にはbootstrapで対応していたものの、
iosアプリ判定のためにディレクトリを振り分けた時点で問題発生。)

precompileの理解を後回しにしてたので、しばらく躓きました。
これこれを読んでも上手くいかず。

日本語の情報が引っかからず、
Rails初学者の穴の一つだと感じたので、以下メモ。
stack overflowのこれをヒントにしました。

原因

asset pipelineがトップディレクトリ内の
application.cssのみを読み込み、
それに応じた挙動をするのを理解していなかったこと。

また、bootstrap.css(or bootstrap.min.css)は
application.html.erb内で指定したcssファイルと
同じ階層に置かなければ読み込まれません。

解決策

ファイル構成

/app/assets/stylesheets/
|             |-- pc
|             |  |
|             |  --- custom.css
|             |  --- custom2.css
|             |  --- .....
|             |
|             -- mobile
|                |
|                --- cunstom.css
|                --- cunstom2.css
|                --- ..... 
application.css
mobileapplication.css
bootstrap.min.css

stylesheet切り替え

views/layouts/application.html.erb
<% if mobileapps? == true %> # application
  <%= stylesheet_link_tag    'mobileapplication', media: 'all', 'data-turbolinks-track' => true %>
<% else %>
  <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>
<% end %>

切り替えメソッド

jpmobileを導入していれば、
request.mobile? または request.smartphone? 等のメソッドで。

今回はモバイル判定ではなく、
iosアプリ判定だったので、こちらを参考に、メソッド作成。
メソッド内では判定だけを行い、上記でstylesheetを切り替えてます。

application_controller.rb
  before_filter :mobileapps?
  helper_method :mobileapps?
 (中略)
  def mobileapps?
    ua = request.env["HTTP_USER_AGENT"]
    if ua.include?('iosapp') #iosアプリ側でUserAgent内に立てたフラグの受け取り
        return true
      # print "iosapp Access"
    else
      # print "PC Access"
    end
  end

読み込むcssの指定

application.css
 *= require bootstrap
 *= require_directory ./pc
mobileapplication.css
 *= require bootstrap
 *= require_directory ./mobile

もっといい方法あると思いますが、
ひとまずこれで動いて☓印を退けられたので、一安心。

4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4