1
0

More than 3 years have passed since last update.

libvipsを使ってRails6でActiveStorageする【Windows,Ubuntu環境】

Last updated at Posted at 2019-11-26

この記事でつくるもの

RailsのActiveStorageを使って簡単なサムネイル表示するCRUDを作成します。
tmp.gif

手順

  • Ubuntuにlibvipsの最新ソースを持ってきて、ビルドとインストール
  • UbuntuからWindow環境をマウントしてrails new
  • ActiveSrorageに必要なRailsコマンドと設定
  • 必要なgemのインストール
  • Ubuntuからrails s

Ubuntuにlibvipsの最新ソースを持ってきて、ビルドとインストール

RailsのActiveStorageはlibvipsまたはImageMagickが必要です。
この記事では実行速度の速いlibvipsを使用します。

まずは必要なパッケージをインストールします。

Ubuntu
$ sudo apt-get install git build-essential libxml2-dev libfftw3-dev \
    libmagickwand-dev libopenexr-dev liborc-0.4-0 \
    gobject-introspection libgsf-1-dev \
    libglib2.0-dev liborc-0.4-dev


gitソースから取得したソースをビルドするのに必要なパッケージ

Ubuntu
$ sudo apt-get install automake libtool swig gtk-doc-tools 


libvips取得し、ビルドとインストール

Ubuntu
$ git clone https://github.com/libvips/libvips.git
$ cd libvips
libvips$ ./autogen.sh
libvips$ make
libvips$ sudo make install


PATHの設定

Ubuntu
$ export VIPSHOME=/usr/local
$ export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$VIPSHOME/lib
$ export PATH=$PATH:$VIPSHOME/bin
$ export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:$VIPSHOME/lib/pkgconfig
$ export MANPATH=$MANPATH:$VIPSHOME/man

UbuntuからWindow環境をマウントしてrails new

UbuntuではWindow環境をマウントして参照できます。
Windowsからの方がソース編集しやすいので、マウントしてrails newします。

Ubuntu
$ cd /mnt/c/tmp_rails
/mnt/c/tmp_rails$ rails new sample
/mnt/c/tmp_rails$ cd sample

ActiveSrorageに必要なRailsコマンドと設定

ActiveSrorageを使うためのマイグレーションファイルを作成

Ubuntu
/mnt/c/tmp_rails/sample$ rails active_storage:install


Userモデルをscaffoldで作成

Ubuntu
/mnt/c/tmp_rails/sample$ rails g scaffold user name image:attachment


Userモデルにはimage:attachmentによりhas_one_attachedが追加される

app/models/user.rb
class User < ApplicationRecord
  has_one_attached :image
end


モデルをマイグレーションする

Ubuntu
/mnt/c/tmp_rails/sample$ rails db:migrate


showページでサムネイル表示するようにする

app/views/users/show.html.erb
<p>
  <strong>Image:</strong>
  <%= image_tag @user.image.variant(resize_to_limit: [100, 100]) %>
</p>


libvipsを使うように指定

app/config/application.rb
module Sample
  class Application < Rails::Application
    config.load_defaults 6.0
    config.active_storage.variant_processor = :vips #追記
  end
end

必要なgemのインストール

image_processingはコメントアウトを外し、ruby-vipsは追記します

Gemfile
gem 'image_processing', '~> 1.2'
gem 'ruby-vips'

Ubuntuからrails s

Ubuntu
/mnt/c/tmp_rails/sample$ rails s

これで http://127.0.0.1:3000/users をブラウザから開けばデモのように動きます。

参考

1
0
1

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
1
0