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 사용 방법

좋은 웹페이지 즐겨찾기