Rails 6 で導入された ActionTextを試してみた


1. はじめに

Rails 6 で導入された ActionTextを試してみたが、インストールでいろいろ面倒だったので忘れないようにメモ。Railsのメジャーバージョンアップは事前によく検証してからアプリ開発環境のアップデートをした方が良い。地雷がたくさんありそう。

2. Rubymineで環境構築

(1) いつものように Create New Project

(2) Rails 6.0.1を使う

6.0.2.1もインストールしてあったので、後の作業でいつの間にか6.0.2.1になった。

Rubyは2.6だと Bundler 1.x系 内蔵で、後で bundleエラーで困ることになるので 2.5.3 を使う。(これに気づくまでbundler 2のインストールなど、無駄に時間を使ってしまった。)

※ ruby 2.7.0 でbundler 2.1.2が同梱されたようです。(2020年01月01日に更新)

(3) エラーの対応

mysql2 でエラーになる。

linking shared-object mysql2/mysql2.bundle
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [mysql2.bundle] Error 1

make failed, exit code 2

途中省略

An error occurred while installing mysql2 (0.5.3), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.5.3' --source 'https://rubygems.org/'` succeeds before bundling.

OpenSSLのConfigが原因だったので以下で解決。

$ brew info openssl
[email protected]: stable 1.1.1d (bottled) [keg-only]
Cryptography and SSL/TLS Toolkit
https://openssl.org/
/usr/local/Cellar/[email protected]/1.1.1d (7,983 files, 17.9MB)
  Poured from bottle on 2019-10-01 at 17:55:09
From: https://github.com/Homebrew/homebrew-core/blob/master/Formula/[email protected]
==> Caveats
A CA file has been bootstrapped using certificates from the system
keychain. To add additional certificates, place .pem files in
  /usr/local/etc/[email protected]/certs

and run
  /usr/local/opt/[email protected]/bin/c_rehash

[email protected] is keg-only, which means it was not symlinked into /usr/local,
because openssl/libressl is provided by macOS so don't link an incompatible version.

If you need to have [email protected] first in your PATH run:
  echo 'export PATH="/usr/local/opt/[email protected]/bin:$PATH"' >> ~/.bash_profile

For compilers to find [email protected] you may need to set:
  export LDFLAGS="-L/usr/local/opt/[email protected]/lib"
  export CPPFLAGS="-I/usr/local/opt/[email protected]/include"

For pkg-config to find [email protected] you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/[email protected]/lib/pkgconfig"

==> Analytics
install: 493,563 (30 days), 1,664,365 (90 days), 2,606,548 (365 days)
install-on-request: 82,390 (30 days), 165,698 (90 days), 453,128 (365 days)
build-error: 0 (30 days)

[email protected] you may need to set: の部分が重要で、以下を実行。

$ export LDFLAGS="-L/usr/local/opt/openssl/lib"
$ export CPPFLAGS="-I/usr/local/opt/openssl/include"
$ bundle config --local build.mysql2 "--with-cppflags=-I/usr/local/opt/openssl/include"
You are replacing the current local value of build.mysql2, which is currently "--with-ldflags=-L/usr/local/opt/openssl/lib"
$ bundle config --local build.mysql2 "--with-ldflags=-L/usr/local/opt/openssl/lib"
You are replacing the current local value of build.mysql2, which is currently "--with-cppflags=-I/usr/local/opt/openssl/include"

$ bundle install を再度実行。

Railsサーバーを起動してみると、次のエラー。

Webpacker configuration file not found /xxx/action_text/config/webpacker.yml. Please run rails webpacker:install Error: No such file or directory @ rb_sysopen - /xxx/action_text/config/webpacker.yml (RuntimeError)

Process finished with exit code 1

メッセージに従って rails webpacker:install を実行。数分かかったがインストール成功。もし、Yarnを入れろと言われたらメッセージに従って $ brew install yarn でインストールする。

Webpacker successfully installed 🎉 🍰

(4) DB構成

database.yml を設定して、 rake 'db:create 実行。以下はRubymineで実行したのでTerminalとは違うけど、手作業でTerminalでやってもOK。

/bin/bash --login -c "env RBENV_VERSION=2.5.3 /usr/local/Cellar/rbenv/1.1.2/libexec/rbenv exec rake 'db:create'"
Created database 'action_text_development'
Created database 'action_text_test'

Process finished with exit code 0.

(5) 適当なSandbox環境をScaffoldする。

$ rails g scaffold sandbox

(6) ActionTextインストール

$ rails action_text:install

(7) Rails構成の確認

Rails6になってるか以下をチェック。

config/application.rb
module ActionText
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0  <=ここが6.0になっていること

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    # Don't generate system test files.
    config.generators.system_tests = nil
  end
end
db/migrate/全てのrbファイル
class CreateActionTextTables < ActiveRecord::Migration[6.0]  <=ここが 6.0 になっていること

OKならMigrateする。

$ rake db:migrate

リッチテキストなので画像も扱いたいから、ImagemagickをMacにインストールしておく。

$ brew install imagemagick
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 3 taps (homebrew/cask-versions, homebrew/core and homebrew/cask).
==> Updated Formulae

途中省略

==> Installing imagemagick
==> Downloading https://homebrew.bintray.com/bottles/imagemagick-7.0.9-8.catalina.bottle.tar.gz
==> Downloading from https://akamai.bintray.com/46/465b851f85405db6bd69a5924bccb53b76b1691934540150e2e16bbd55bfc890?__gda__=exp=1576887828~hmac=578323ae6bdae26b7470ff9f23c520ae4cd9450d174c345e5b064b53ab2606f6&response-content-dispositi
######################################################################## 100.0%
==> Pouring imagemagick-7.0.9-8.catalina.bottle.tar.gz
🍺  /usr/local/Cellar/imagemagick/7.0.9-8: 1,479 files, 24.4MB
==> Caveats
==> sqlite
sqlite is keg-only, which means it was not symlinked into /usr/local,
because macOS provides an older sqlite3.

If you need to have sqlite first in your PATH run:
  echo 'export PATH="/usr/local/opt/sqlite/bin:$PATH"' >> ~/.bash_profile

For compilers to find sqlite you may need to set:
  export LDFLAGS="-L/usr/local/opt/sqlite/lib"
  export CPPFLAGS="-I/usr/local/opt/sqlite/include"

For pkg-config to find sqlite you may need to set:
  export PKG_CONFIG_PATH="/usr/local/opt/sqlite/lib/pkgconfig"

==> python
Python has been installed as
  /usr/local/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
  /usr/local/opt/python/libexec/bin

If you need Homebrew's Python 2.7 run
  brew install python@2

You can install Python packages with
  pip3 install <package>
They will install into the site-package directory
  /usr/local/lib/python3.7/site-packages

See: https://docs.brew.sh/Homebrew-and-Python
==> glib
Bash completion has been installed to:
  /usr/local/etc/bash_completion.d
Gemfile
# Use Active Storage variant
gem 'image_processing', '~> 1.2'  <=コメントを外す

bundle install して、 rake db:migrate する。

(7) Rails起動

bundle updateされたらしく、rails 6.0.2.1になってた。

/bin/bash -c "env RBENV_VERSION=2.5.3 /usr/local/Cellar/rbenv/1.1.2/libexec/rbenv exec ruby /xxx/action_text/bin/rails server -b 0.0.0.0 -p 3000 -e development"
=> Booting Puma
=> Rails 6.0.2.1 application starting in development 
=> Run `rails server --help` for more startup options
Puma starting in single mode...
* Version 4.3.1 (ruby 2.5.3-p105), codename: Mysterious Traveller
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop

とりあえず、起動はできたので、ActionTextを試せる環境ができた。

3. ActionTextで遊ぼう

(1) Scaffoldしたものを設定

app/models/sandobox.rb
class Sandbox < ApplicationRecord
  has_rich_text :content
end
app/controllers/sandboxes_controller.rb
下の方にある以下を修正
    # Never trust parameters from the scary internet, only allow the white list through.
    def sandbox_params
      params.fetch(:sandbox, {}) 
      params.require(:sandbox).permit(:content)  <=これを追加
    end
app/views/sandboxes/_form.html.erb
<%= form_with(model: sandbox, local: true) do |form| %>
  <% if sandbox.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(sandbox.errors.count, "error") %> prohibited this sandbox from being saved:</h2>

      <ul>
        <% sandbox.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  # 下記のコードがリッチテキストエリア
  <div class="field">
    <%= form.label :content %>
    <%= form.rich_text_area :content %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
app/views/sandboxes/show.html.erb
<p id="notice"><%= notice %></p>

<%= @sandbox.content %>

<%= link_to 'Edit', edit_sandbox_path(@sandbox) %> |
<%= link_to 'Back', sandboxes_path %>

(2) Railsサーバー再起動

http://localhost:3000/sandboxes をブラウザで開くと以下の画面が出る。

New Sandbox をクリックしてみると、おお! リッチテキストボックスだ出た。画像も貼れた。

Showしてみる。

4. ファイル保存先の変更

ActiveStorageでリッチテキストに貼り付けた画像などは保存されているようだが、このままだと画像は下図のようにLocalに保存されてしまう。Development環境はLocal保存でも構わないが、Production環境はでAmazon S3などに保存されるように設定をする。

5. 機能不足

ここまでやって気付いたが、下線などのWindowsのリッチテキストエディタで使える機能が使えない。既存のWindowsアプリのOnline化をやろうと思ったが、機能差が大き過ぎてアプリのリプレースは困難と判断し、wysiwyg-rails を試してみることにした。数式も必要なのでKaTeXなどを検討したい。ActionTextはもっと成熟化して機能が増えてから考えれば良いかな。

6. 参照記事

Ruby on Rails 6.0のAction Textを触ってみた。
Rails & Webpackerでフロントエンド開発環境を整える
Upgrading to Rails 6 and getting started with Action Text
HomebrewでImageMagickをインストールする
Active Storageの使い方