Memo

メモ > 技術 > プログラミング言語: Ruby

■概要
Ruby on Rails チュートリアル:実例を使って Rails を学ぼう https://railstutorial.jp/ このページを参考に、Ruby on Railsを勉強予定 Ruby on Rails ガイド:体系的に Rails を学ぼう https://railsguides.jp/ このページも開設が豊富そう Ruby on Railsチュートリアルを軸にしてWeb周辺技術を勉強した - drilldripper’s blog http://drilldripper.hatenablog.com/entry/2017/05/13/214744 勉強した人のメモ Ruby入門 〜Rubyの開発環境を用意する手順やRubyを使ったプログラミングの方法について解説します〜 https://www.javadrive.jp/ruby/ その前に、このページでRubyを勉強予定 Ruby on Rails 4.2 を Windows にインストールする手順をかなり丁寧に説明してみました - Rails 雑感 - Ruby on Rails with OIAX https://www.oiax.jp/rails/zakkan/rails_4_2_installation_on_windows.html 上のページで解説されているRailsのバージョンは4.2.2なので、Rubyは2.1.8にする 「Rails 5.0」ついに正式リリース。JSONで通信できる「API mode」やWebSocket対応の「Action Cable」フレームワーク − Publickey https://www.publickey1.jp/blog/16/rails_50jsonapi_modewebsocketaction_cable.html バージョン5はまだ出たばかりみたい WindowsでのRuby on Rails - 開発環境構築からアプリケーション実行まで | DevelopersIO https://dev.classmethod.jp/server-side/ruby-on-rails/windows_ruby-on-rails_run/ が解りやすそうなので、基本的にこのページを参考にインストール
■Rubyの導入
■Rubyをインストール Downloads https://rubyinstaller.org/downloads/ から「Ruby+Devkit 2.5.7-1 (x64)」をダウンロード 「C:\ruby」にインストール。3つのチェックボックスにチェック なお、2.6だとWindowsではMySQLに接続できなかった(接続ライブラリのmysql2のインストールに失敗する) よって今回は2.5をインストールする ■Ruby動作確認 コマンドプロンプトから以下を入力すると、Rubyのバージョンを表示できる
>ruby -v ruby 2.5.7p206 (2019-10-01 revision 67816) [x64-mingw32]
拡張子「rb」で動作させる場合、.htaccessなどで以下を指定しておく
AddHandler cgi-script .cgi .rb
hello.rb
#!/ruby/bin/ruby #encoding: utf-8 print "Content-type: text/html\n\n" print "<html>\n" print "<head>\n" print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" print "<title>Hello world !</title>\n" print "</head>\n" print "<body>\n" print "<p>テスト</p>\n" print "</body>\n" print "</html>\n" exit
ブラウザからhello.rbにアクセスし、「テスト」と表示されれば成功 以前はencodingの指定が無いとエラーになったが、今回は大丈夫だった
■MySQLの導入
■Ruby+MySQLインストール 以下のコマンドでmysql2をインストール
>gem install mysql2 Fetching: mysql2-0.5.2-x64-mingw32.gem (100%) Successfully installed mysql2-0.5.2-x64-mingw32 Parsing documentation for mysql2-0.5.2-x64-mingw32 Installing ri documentation for mysql2-0.5.2-x64-mingw32 Done installing documentation for mysql2 after 2 seconds 1 gem installed
これでMySQLを使える ■Ruby+MySQL動作確認 以下のテーブルとデータがあるとする
CREATE TABLE address( no INT, name VARCHAR(80), tel VARCHAR(80) ) DEFAULT CHARSET=utf8; INSERT INTO address(no, name, tel) VALUES(1, '山田太郎', '090-1234-5678'); INSERT INTO address(no, name, tel) VALUES(2, "山田花子", "090-2345-6789");
以下のプログラムでテーブルの内容を表示できた
#!/ruby/bin/ruby require 'mysql2' print "Content-type: text/html\n\n" print "<html>\n" print "<head>\n" print "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" print "<title>Hello world !</title>\n" print "</head>\n" print "<body>\n" print "<pre>\n" print "MySQLのテスト。<br>\n" client = Mysql2::Client.new(:host => 'localhost', :user => 'root', :password => '1234') query = %q{select no, name from test.address} results = client.query(query) results.each do |row| puts "--------------------" row.each do |key, value| puts "#{key} => #{value}\n" end end print "</pre>\n" print "</body>\n" print "</html>\n" exit
参考 RubyでMySQLを操作する - Qiita https://qiita.com/toshiro3/items/b65b2ad744d8f3ecc734 ■Ruby+MySQL(駄目だったときの試行錯誤メモ) http://cdn.mysql.com/Downloads/Connector-C/mysql-connector-c-6.1.6-win32.zip から libmysql.dll を入手して、C:\ruby\bin\libmysql.dll に配置する これだけで駄目なら、さらに Index of /pub/mysql/Downloads/MySQL-5.5 http://ftp.jaist.ac.jp/pub/mysql/Downloads/MySQL-5.5/ から mysql-5.5.51-winx64.zip をダウンロードし、展開して C:\ruby\mysql-5.5.51-winx64 に配置 以下のコマンドでmysql2をインストール
>gem install mysql2 -- '--with-mysql-lib="C:\ruby\mysql-5.5.51-winx64\lib" --with-mysql-include="C:\ruby\mysql-5.5.51-winx64\include"' Temporarily enhancing PATH to include DevKit... Building native extensions with: '--with-mysql-lib="C:\ruby\mysql-5.5.51-winx64\lib" --with-mysql-include="C:\ruby\mysql-5.5.51-winx64\include"' This could take a while... Successfully installed mysql2-0.4.4 Parsing documentation for mysql2-0.4.4 Installing ri documentation for mysql2-0.4.4 Done installing documentation for mysql2 after 1 seconds 1 gem installed
これでMySQLを使えるはず 以前は以下の手順でインストールできたが、今のXAMPPにはlibフォルダ自体が無かった
プログラム内に require 'mysql' と書くと LIBMYSQL.dll が無いというエラーになる C:\xampp\mysql\lib\libmysql.dll を C:\ruby\bin\libmysql.dll にコピー
gemでインストールしようとしてもエラーになった
>gem install mysql2 Fetching: mysql2-0.4.4.gem (100%) Temporarily enhancing PATH to include DevKit... Building native extensions. This could take a while... ERROR: Error installing mysql2: ERROR: Failed to build gem native extension. 〜略〜 extconf failed, exit code 1 Gem files will remain installed in C:/ruby/lib/ruby/gems/2.1.0/gems/mysql2-0.4.4 for inspection. Results logged to C:/ruby/lib/ruby/gems/2.1.0/extensions/x64-mingw32/2.1.0/mysql2-0.4.4/gem_make.out
以下のページを参考にインストールできた…が、今は消えている http://halfdome.biz/redmine%E3%82%92windows10%E3%81%AB%E3%82%A4%E3%83%B3%E3%82%B9%E3%83%88%E3%83%BC%... キャッシュから探してインストールできた…が、今はキャッシュも消えている http://webcache.googleusercontent.com/search?q=cache:ShD6SA1YPXIJ:halfdome.biz/redmine%25E3%2582%259... さらに別の方法 http://cdn.mysql.com/Downloads/Connector-C/mysql-connector-c-6.1.6-win32.zip から libmysql.dll を入手して、C:\ruby\bin\libmysql.dll に配置する これだけで駄目なら、さらに Index of /pub/mysql/Downloads/MySQL-5.5 http://ftp.jaist.ac.jp/pub/mysql/Downloads/MySQL-5.5/ から mysql-5.5.51-winx64.zip をダウンロードし、展開して C:\ruby\mysql-5.5.51-winx64 に配置 以下のコマンドでmysql2をインストール
>gem install mysql2 -- '--with-mysql-lib="C:\ruby\mysql-5.5.51-winx64\lib" --with-mysql-include="C:\ruby\mysql-5.5.51-winx64\include"' Temporarily enhancing PATH to include DevKit... Building native extensions with: '--with-mysql-lib="C:\ruby\mysql-5.5.51-winx64\lib" --with-mysql-include="C:\ruby\mysql-5.5.51-winx64\include"' This could take a while... Successfully installed mysql2-0.4.4 Parsing documentation for mysql2-0.4.4 Installing ri documentation for mysql2-0.4.4 Done installing documentation for mysql2 after 1 seconds 1 gem installed
これでMySQLを使えるはず
■Ruby on Railsの導入
■前提
>ruby -v ruby 2.1.8p440 (2015-12-16 revision 53160) [x64-mingw32]
Ruby 2.1 がインストールされているWindows10環境で検証した ■Ruby on Railsをインストール
>gem install rails -v 5.2.2
と、Railsのバージョンを指定してインストール バージョンを指定しないと最新版がインストールされる ■Ruby on Railsの動作確認(SQLite3) ※デフォルトではデータベースにSQLite3が使われる https://www.oiax.jp/rails/zakkan/rails_4_2_installation_on_windows.html この手順で動作確認 コマンドプロンプトで、Railsアプリケーションを作成したい場所へ移動
>cd C:\localhost\home\ruby\public_html\rails >rails new rails-test --skip-bundle >cd rails-test >bundle install >gem install sqlite3 -v '1.4.1' --source 'https://rubygems.org/' >bundle install >rails g scaffold user name:string email:string >rake db:migrate >rails s => Booting Puma => Rails 5.2.3 application starting in development => Run `rails server -h` for more startup options *** SIGUSR2 not implemented, signal based restart unavailable! *** SIGUSR1 not implemented, signal based restart unavailable! *** SIGHUP not implemented, signal based logs reopening unavailable! Puma starting in single mode... * Version 3.12.1 (ruby 2.5.7-p206), codename: Llamas in Pajamas * Min threads: 5, max threads: 5 * Environment: development * Listening on tcp://localhost:3000 Use Ctrl-C to stop Started GET "/" for ::1 at 2019-10-13 01:51:59 +0900
のように表示されれば起動完了 停止させたい場合、「Use Ctrl-C to stop」と書かれているように Ctrl-C を実行する 「rails s」は「rails server」としても起動できる http://localhost:3000/users にアクセスすると 「TypeError: オブジェクトでサポートされていないプロパティまたはメソッドです。」 というエラーが表示された http://qiita.com/falcon8823/items/f4dc2b5a474869dff449 Node.jsをインストールしてからコマンドプロンプトを再起動し、再度scaffoldを実行するとエラーが解消された 名前とメールアドレスが登録管理できれば完了 Ruby - bundle install時に--skip-bundleをつけるメリット|teratail https://teratail.com/questions/17323 ■Ruby on Railsの動作確認(MySQL) あらかじめ以下のデータベースを作成しておいた rails-mysql_development コマンドプロンプトで、Railsアプリケーションを作成したい場所へ移動
>cd C:\localhost\home\ruby\public_html\rails >rails new rails-mysql -d mysql >cd rails-mysql
rails-mysql/config/database.yml を編集(development環境がデフォルトとなり、データベースは rails-mysql_development が使われる)
password: 1234
以下を実行しておくと、各ライブラリが最新になる?
>bundle install
以下のとおり実行
>rails g scaffold user name:string email:string >rake db:migrate >rails s
以下にアクセスしてユーザを管理できれば完了 http://localhost:3000/users ■Railsの起動 作成済みのプログラムは、以下のようにして起動できる
>cd C:\localhost\home\ruby\public_html\rails\rails-test >rails s
■Railsの再起動 コンソールから Ctrl+C で終了し、再度「rails s」で起動する config/environments/staging.rb など設定ファイルで「config.cache_classes = true」としている場合、ビューを編集した場合はRailsの再起動が必要 Ctrl+C を入力すると以下のようになる
[2019-09-30 16:36:26] INFO going to shutdown ... [2019-09-30 16:36:26] INFO WEBrick::HTTPServer#start done. Exiting バッチ ジョブを終了しますか (Y/N)? y >rails s => Booting WEBrick => Rails 4.2.2 application starting in development on http://localhost:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server [2019-09-30 16:36:40] INFO WEBrick 1.3.1 [2019-09-30 16:36:40] INFO ruby 2.1.8 (2015-12-16) [x64-mingw32] [2019-09-30 16:36:40] INFO WEBrick::HTTPServer#start: pid=8964 port=3000
■Railsのバージョンを確認 以下のようにすればRailsのバージョンを確認できる
>cd C:\localhost\home\ruby\public_html\rails\rails-test >rails -v Rails 4.2.2
■Railsのコンソールを起動 以下のようにすればコンソールを起動できる この例では、合わせて環境の設定を確認している
>cd C:\localhost\home\ruby\public_html\rails\rails-test >rails console Loading development environment (Rails 4.2.2) irb(main):001:0> Rails.env => "development"
■Ruby on RailsをEC2へ導入
(下準備編)世界一丁寧なAWS解説。EC2を利用して、RailsアプリをAWSにあげるまで - Qiita https://qiita.com/naoki_mochizuki/items/f795fe3e661a3349a7ce RailsアプリをAWSにイチからデプロイするまでの手順メモ - Code of Duty https://www.codeofduty.me/2018/01/31/railsapp-aws-deploy/ 初心者向け:AWS(EC2)にRailsのWebアプリをデプロイする方法 目次 - Qiita https://qiita.com/iwaseasahi/items/d5f2ef3eac5e349a8f7d ■サーバの基本的な設定 Amazon Linux 2 に Ruby on Rails を導入するものとする(VagrantのCentOS7でも同様に導入できた) EC2起動後、サーバメモの Basis.txt をもとにしてサーバの基本的な設定を行う また、セキュリティグループで3000番ポートを空けておく(Railsがデフォルトで使用するポート) ■依存ライブラリをインストール Ruby On RailsをAmazonLinux2にインストール(2018.3) - Qiita https://qiita.com/2gt/items/b8fba865a9059aacc61e
# yum -y install git # yum -y install gcc # yum -y install openssl-devel # yum -y install readline-devel # yum -y install zlib-devel # yum -y install sqlite-devel # curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash - # yum -y install nodejs # npm -v # node -v
■Ruby(rbenv)をインストール Amazon Linux 2にrbenvをいれる - Qiita https://qiita.com/ryooob/items/ce3354c9f2e0f202ff89 rbenv で ruby の環境を整える - Qiita https://qiita.com/ringo/items/4351c6aee70ed6f346c8 ※Rubyを使いたいユーザになっておく どのユーザからもRubyを使用できるようにする場合、「どのユーザからもRubyを使用できるようにする」を参照 ※ここでは ec2-user でインストールを行うものとする
$ git clone https://github.com/sstephenson/rbenv.git ~/.rbenv $ git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build $ echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bash_profile $ echo 'eval "$(rbenv init -)"' >> ~/.bash_profile $ source ~/.bash_profile $ rbenv --version rbenv 1.1.2-4-g577f046 $ rbenv install --list Available versions: 1.8.5-p52 1.8.5-p113 1.8.5-p114 〜中略〜 truffleruby-19.1.0 truffleruby-19.2.0 truffleruby-19.2.0.1 $ rbenv install 2.5.7 … 今回は Ruby 2.5.7 を使用する $ rbenv global 2.5.7 $ rbenv rehash $ which ruby ~/.rbenv/shims/ruby $ ruby --version ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux]
■BundlerとSQLiteをインストール
$ gem install bundler sqlite3
■Railsをインストール
$ gem install rails -v 5.2.2 … 今回は Rails 5.2.2 を使用する。バージョンを省略すると最新版がインストールされる $ rails --version
■Railsの動作確認(SQLite3) ※/var/www/プロジェクト名 の場所にインストールすべきか
# mkdir -p /var/www/rails-test … root権限でプロジェクト用ディレクトリを作成(存在しない場合) # chown ec2-user. /var/www/rails-test # chmod 775 /var/www/rails-test $ cd /var/www … ec2-userでプロジェクトを作成 $ rails new rails-test --skip-bundle $ cd rails-test $ bundle install $ rails g scaffold user name:string email:string $ rake db:migrate $ rails s -b 0.0.0.0
ブラウザから以下にアクセスする(サーバのIPアドレスが 13.231.145.182 の場合) http://13.231.145.182:3000/ http://13.231.145.182:3000/users ユーザ情報の登録と表示ができれば完了 Ruby - bundle install時に--skip-bundleをつけるメリット|teratail https://teratail.com/questions/17323 ■Bundler経由での動作確認
$ bundle exec rails s -b 0.0.0.0
「bundle exec」が無くても実質同じ結果を得られるようだが、環境依存のリスクを軽減できるらしい ひとまずサーバ上では、Railsのコマンドは「bundle exec」を付けて実行しておくのが無難そう Bundlerとは? - Qiita https://qiita.com/io_fleming/items/14626a9cff44bc87e7db bundle exec を理解したい。 - Qiita https://qiita.com/nishisuke/items/79acacc9e7e7d519ee3f Ruby on Rails - bundle exec と bin/rails の違い|teratail https://teratail.com/questions/120475 ■データベースにMySQLを使用する MySQL(MariaDB)サーバをインストール
# yum -y install mariadb-server … root権限でインストール # mysql --version mysql Ver 15.1 Distrib 5.5.64-MariaDB, for Linux (x86_64) using readline 5.1 # systemctl start mariadb # systemctl enable mariadb
クライアントコマンドもインストール
# yum -y install mysql-devel
サーバメモの Web.txt をもとにして、MySQLの基本的な設定を行う 今回は「webmaster / gV0+8k6BM#z7」の情報で「development」データベースを扱えるようにした
# mkdir /var/www/rails-mysql … root権限でプロジェクト用ディレクトリを作成 # chown ec2-user. /var/www/rails-mysql # chmod 775 /var/www/rails-mysql $ cd /var/www … ec2-userでプロジェクトを作成 $ rails new rails-mysql -d mysql --skip-bundle $ cd rails-mysql $ vi config/database.yml
username: root password: ↓ username: webmaster password: gV0+8k6BM#z7 development: <<: *default database: rails-mysql_development ↓ development: <<: *default database: development
$ bundle install $ rails g scaffold user name:string email:string $ rake db:migrate $ bundle exec rails s -b 0.0.0.0
ブラウザから以下にアクセスする http://13.231.145.182:3000/ http://13.231.145.182:3000/users ユーザ情報の登録と表示ができれば完了 ■Unicornをインストールする なぜrailsの本番環境ではUnicorn,Nginxを使うのか?  ~ Rack,Unicorn,Nginxの連携について ~【Ruby On Railsでwebサービス運営】 - Qiita https://qiita.com/takahiro1127/items/fcb81753eaf381b4b33c nginx+Unicorn経由でアクセスすることにより、大量のアクセスを捌くための仕組みが利用できる 「rails s」での起動は、開発用のものと考えておく また、コンソールから「bundle exec rails s -b 0.0.0.0」としなくても起動できる
$ vi Gemfile … 単に「gem install unicorn」とするとunicornを起動できなかった
# Unicorn gem 'unicorn' … ファイルの最後に追加★実際は本番と検収にのみインストールするか
$ gem install bundler $ bundle install $ vi config/unicorn.conf.rb
# set lets $worker = 2 $timeout = 30 $app_dir = "/var/www/rails-mysql" … アプリケーションの場所を設定 $listen = File.expand_path 'tmp/sockets/.unicorn.sock', $app_dir $pid = File.expand_path 'tmp/pids/unicorn.pid', $app_dir $std_log = File.expand_path 'log/unicorn.log', $app_dir # set config worker_processes $worker working_directory $app_dir stderr_path $std_log stdout_path $std_log timeout $timeout listen $listen pid $pid # loading booster preload_app true # before starting processes before_fork do |server, worker| defined?(ActiveRecord::Base) and ActiveRecord::Base.connection.disconnect! old_pid = "#{server.config[:pid]}.oldbin" if old_pid != server.pid begin Process.kill "QUIT", File.read(old_pid).to_i rescue Errno::ENOENT, Errno::ESRCH end end end # after finishing processes after_fork do |server, worker| defined?(ActiveRecord::Base) and ActiveRecord::Base.establish_connection end
■nginxをインストールする
# amazon-linux-extras list … root権限でインストール # amazon-linux-extras install nginx1.12 -y # systemctl start nginx # systemctl enable nginx # chmod -R 775 /var/lib/nginx … 設定しておかないと、postメソッドでエラーになるらしい
以下にアクセスして動作を確認する http://13.231.145.182/ ■nginx+Unicorn経由でアクセスする
# vi /etc/nginx/conf.d/rails-mysql.conf … root権限で設定。アプリケーション名をファイル名にしておく
upstream unicorn_server { server unix:/var/www/rails-mysql/tmp/sockets/.unicorn.sock … アプリケーションの場所をもとに設定 fail_timeout=0; } server { listen 80; client_max_body_size 4G; server_name 13.231.145.182; … サーバのドメインもしくはIPアドレス keepalive_timeout 5; # Location of our static files root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定 location ~ ^/assets/ { root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定 } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://unicorn_server; break; } } error_page 500 502 503 504 /500.html; location = /500.html { root /var/www/rails-mysql/public; … アプリケーションの場所をもとに設定 } }
# systemctl restart nginx $ cd /var/www/rails-mysql … プロジェクトの場所で Unicorn を起動 $ bundle exec unicorn_rails -c /var/www/rails-mysql/config/unicorn.conf.rb -D -E development $ ps -ef | grep unicorn | grep -v grep
以下にアクセスして動作を確認する http://13.231.145.182/ http://13.231.145.182/users 問題なければ完了 なお、アクセスログやエラーログは、特に変更しなければ通常どおり以下の場所に保存される /var/log/nginx 以下は構築の補足など ■どのユーザからもRubyを使用できるようにする root 権限で /usr/local/rbenv などにインストールし、gem を使いたい場合は root 権限で行う(未検証) ただしその場合、secure_path の設定なども必要となるみたい CentOS7 全体でユーザ共通に使える rbenv をインストールする - らくがきちょう http://sig9.hatenablog.com/entry/2016/10/04/120000 rbenvで入れたRubyを全ユーザが使えるようにする https://cre8cre8.com/rails/rbenv-install-ruby-using-all-users.htm ■RubyやGemのコマンドを使おうとすると「command not found」「command exists in these Ruby versions」と表示される 使用するRubyのバージョンを特定できていない場合に起こる 「rbenv install 2.5.7」を実行した後、「rbenv global 2.5.7」のように指定しないとこのエラーになる
$ ruby -v … エラーになる rbenv: ruby: command not found The `ruby' command exists in these Ruby versions: 2.5.7 $ gem -v … エラーになる rbenv: gem: command not found The `gem' command exists in these Ruby versions: 2.5.7 $ rbenv global 2.5.7 … Rubyのバージョンを指定 $ rbenv rehash $ ruby -v … エラーにならない ruby 2.5.7p206 (2019-10-01 revision 67816) [x86_64-linux] $ gem -v … エラーにならない 2.7.6.2
rbenv: ruby: command not found The `ruby' command exists in these Ruby versions: - Qiita https://qiita.com/Kaisyou/items/34ea9b5800434c1e09e6 ■Railsのコマンドを使おうとすると「Could not find a JavaScript runtime」と表示される
$ rails g scaffold user name:string email:string Traceback (most recent call last): 49: from bin/rails:4:in `<main>' 48: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/activesupport-5.2.3/lib/active_support/dependencies.rb:291:in `require' 〜中略〜 2: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs.rb:4:in `<top (required)>' 1: from /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs.rb:5:in `<module:ExecJS>' /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/execjs-2.7.0/lib/execjs/runtimes.rb:58:in `autodetect': Could not find a JavaScript runtime. See https://github.com/rails/execjs for a list of available runtimes. (ExecJS::RuntimeUnavailable)
このように表示される場合、Node.js など何らかのExecJSランタイムをイントールする 【Rails】Could not find a JavaScript runtimeとなった時にやったこと - むぎちゃ http://djandjan.hateblo.jp/entry/2018/07/25/224929 Amazon Linux2にnodejs+npmをインストールする方法 | SeleGee(セレジー) https://selegee.com/develop/535/ ■Railsにブラウザからアクセスしようとすると「サーバが見つかりません」になる
$ rails s
ではなく
$ rails s -b 0.0.0.0
で起動する Rails 4.2 から rails server が Listen するアドレスが 0.0.0.0 から localhost に変わった デフォルトの localhost では Public DNS 経由でアクセスできないので Listen するアドレスを変更する必要がある 環境によってはアクセスできるかもしれないが、EC2・Vagrant(CentOS)ともに「-b 0.0.0.0」の指定が必要だった EC2でRailsアプリを起動したけどブラウザからアクセスできないとき - Qiita https://qiita.com/sakaimo/items/dd138b39c7480fb2ebff EC2 に Rails の開発環境をサクッと作る https://blog.manabusakai.com/2015/06/rails-setup-on-ec2/ ■RailsでMySQLを使う際に「bundle install」を実行するとエラーになる 以下のエラーになる
$ bundle install 〜中略〜 Fetching mysql2 0.5.2 Installing mysql2 0.5.2 with native extensions Gem::Ext::BuildError: ERROR: Failed to build gem native extension. current directory: /var/www/.rbenv/versions/2.5.7/lib/ruby/gems/2.5.0/gems/mysql2-0.5.2/ext/mysql2 /var/www/.rbenv/versions/2.5.7/bin/ruby -r ./siteconf20191015-25857-1a191fl.rb extconf.rb --with-ldflags=-L/usr/local/opt/openssl/lib --with-cppflags=-I/usr/local/opt/openssl/include checking for rb_absint_size()... yes checking for rb_absint_singlebit_p()... yes checking for rb_wait_for_single_fd()... yes checking for -lmysqlclient... no ----- mysql client is missing. You may need to 'apt-get install libmysqlclient-dev' or 'yum install mysql-devel', and try again. ----- *** extconf.rb failed *** Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. 〜中略〜 An error occurred while installing mysql2 (0.5.2), and Bundler cannot continue. Make sure that `gem install mysql2 -v '0.5.2' --source 'https://rubygems.org/'` succeeds before bundling.
エラーの案内どおり、「yum install mysql-devel」を実行してみる root権限で実行
$ sudo su - # yum install mysql-devel # exit
再度以下を実行すると完了できた
$ bundle install
■Unicorn経由でRailsにアクセスすると「403 Forbidden」と表示される Railsを /home/xxx 内に設置した場合、 以下のようにユーザディレクトリのパーミッションを変更する必要がある(700 を 701 に変更)
# chmod 701 /home/ec2-user
ただし、以下のように /var/www 内に設置すればこの問題は起こらないため、 特に理由がなければ /var/www 内に設置することを推奨
/var/www/プロジェクト名
unicorn nginx rails の連携で自分がハマったところ - Qiita https://qiita.com/hatorijobs/items/8b57f9a89c3bfb442755 ■Railsを削除する場合
# gem uninstall railties -v '6.0.0' … バージョンを指定して削除。この場合は 6.0.0 を削除している
■rackについて なぜrailsの本番環境ではUnicorn,Nginxを使うのか?  ~ Rack,Unicorn,Nginxの連携について ~【Ruby On Railsでwebサービス運営】 - Qiita https://qiita.com/takahiro1127/items/fcb81753eaf381b4b33c ApacheとNginxとPassengerとUnicornの違い【すごい初心者向け】 - ふじいけ技術メモ http://fujiike.hateblo.jp/entry/2015/08/20/170751
■Unicornの代わりにPumaを使用する
※要調査 Rails5からはUnicornではなくPumaが標準のWebサーバとされている ただしUnicornやPassengerに比べて常に高いパフォーマンスを発揮する…というわけでは無いようなので、無理に乗り換える必要は無さそう Pumaの使い方 まとめ - 猫Rails http://nekorails.hatenablog.com/entry/2018/10/12/101011 pumaを使ってみた - Qiita https://qiita.com/kompiro/items/223bb04c2f009787eea8 Pumaの本当の力を引き出す - Qiita https://qiita.com/ykyk1218/items/0ca7f1fa449b41fe1fea
■Unicornの代わりにPassengerを使用する
※要調査 WebサーバにUnicornではなくPassengerを使った場合のメモ ただし Passenger → Unicorn → Puma と移り変わっているらしいので、 今新規にアプリケーションを作るならPassengerを採用する必要は無さそう ruby-on-rails - Railsキャッシュのクリア - コードログ https://codeday.me/jp/qa/20190623/1083429.html [Rails]Passengerの再起動コマンド | Fun-Techlab.com http://www.fun-techlab.com/2016/07/26/restart_passenger/
■CapistranoでRailsをEC2へデプロイ
※検証中 (Capistrano編)世界一丁寧なAWS解説。EC2を利用して、RailsアプリをAWSにあげるまで - Qiita https://qiita.com/naoki_mochizuki/items/657aca7531b8948d267b Capistrano で Rails アプリケーションの自動デプロイ - Qiita https://qiita.com/Salinger/items/4ee4f3c5ebd5227196c0 Capistranoで簡単デプロイ - Qiita https://qiita.com/Esfahan/items/1258d37eb6a85fa35b02 ■概要 ローカルのRailsプロジェクトを、コマンド一つでデプロイできる ただし学習コストが非常に高いとされる 今回は、ローカルVagrant(CentOS7)のRailsプロジェクトをデプロイするものとする そのプロジェクトは
$ cd /var/www/rails-mysql $ bundle exec rails s -b 0.0.0.0
で起動でき、 http://192.168.33.10:3000/users でアクセスできるものとする デプロイ先は、手動で構築したEC2を想定する ■Capistranoのインストール ローカルにある対象プロジェクトの Gemfile の最後に、以下を追記する
# Deploy group :development, :test do gem 'capistrano' gem 'capistrano-bundler' gem 'capistrano-rails' gem 'capistrano-rbenv' end group :production, :staging do gem 'unicorn' end
「bundle install」で capistrano をインストールすると、cap コマンドが使えるようになる さらに「bundle exec cap install」を実行すると、Capistrano用のファイルが作成される
$ bundle install $ bundle exec cap install mkdir -p config/deploy create config/deploy.rb create config/deploy/staging.rb create config/deploy/production.rb mkdir -p lib/capistrano/tasks create Capfile Capified
いったんエラーにならずにファイルを作成できたところまで 引き続き、主に以下のページを参考に進めたい (Capistrano編)世界一丁寧なAWS解説。EC2を利用して、RailsアプリをAWSにあげるまで - Qiita https://qiita.com/naoki_mochizuki/items/657aca7531b8948d267b
■メモ
著名なオープンソースRailsアプリのapp/以下を見る https://zenn.dev/takahashim/articles/ac725fb16ec7a11809c5

Advertisement