2016年2月14日日曜日

【Rails4.2.xx】 Using Capistrano3

  • Published Date:Feb. 14, 2016

Article Summary

This article is how to use Capistrano3.

環境

  • rails4.2.5 & centos6.5
  • ruby2.3.0
  • rbenv
  • unicorn

About capistrano

Capistrano3 is deployment tool. This is writtern by Ruby, it is good for rails app.
Other programing languages can be also available Capistrano3. if you use rails app, you can use many convient functions.

Purposes of use

deployment is hard job. On the other hand, these tasks are delicate.
if you faile deployment operation, many customers have such a bad influence.

if you use capistrano, it is easy to deploy web app.
In terms of secirity, deployment should be executed automatically.

cap install

At first, Add Capistrano to your project's Gemfile.

{project_folder}/Gemfile

group :development do
  # Access an IRB console on exception pages or by using <%= console %> in views
  gem 'web-console', '~> 2.0'
  gem 'capistrano', '~> 3.2.1'
  gem 'capistrano-ssh-doctor', '~> 1.0'
  gem 'capistrano-rails'
  gem 'capistrano-rbenv', github: "capistrano/rbenv"
  gem 'capistrano-bundler', "~> 1.1.0"
  gem 'capistrano3-unicorn' # unicornを使っている場合のみ
end

install.

terminal

rbenv exec bundle install

cap install.

terminal

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
Capified

cap command creates all necessary configuration files.
if your app need other environments, you make file manually. In my case, Local env is development. Staging env is operation verification. Production env is public site. So, my cap files are default settings.
Next step is to set deployment setting.

Setting Capfile

My enviroment uses rbenv. add capistrano/rbenv to Capfile.

{project_folder}/Capfile

require 'capistrano/rbenv'

confirm version of ruby which running rails.

terminal

[root@vagrant-centos65 ~]# ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

add version of ruby to Capfile.

{project_folder}/Capfile

require 'capistrano/rbenv'

set :rbenv_ruby, '2.3.0'

Next, add rbenv path to Capfile.

terminal

[root@vagrant-centos65 ~]# which rbenv
/usr/local/rbenv/bin/rbenv

add "/usr/local/rbenv" to Capfile.

{project_folder}/Capfile

require 'capistrano/rbenv'

set :rbenv_ruby, '2.3.0'
set :rbenv_custom_path, '/usr/local/rbenv'

Use Bundler.

{project_folder}/Capfile

require 'capistrano/bundler'

add other libraries. assets compile, unicorn restart, db migrate, site-map update.


require 'capistrano/rbenv'

set :rbenv_ruby, '2.3.0'
set :rbenv_custom_path, '/usr/local/rbenv'

require 'capistrano/rails/assets'
require 'capistrano/rails/migrations'
require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano3/unicorn'

config/deploy.rb

This step is to set deploy.rb. This file describes common deployment operation.
add git infomation to Capfile.

{project_folder}/Capfile

set :application, 'sampleweb'
set :repo_url, 'git@xxxxxxxx:test/sample_web.git'

# Default value for :scm is :git
set :scm, :git

Capistrano get source code using git clone command. On Linux, Set information of git , as you can use git clone command.

rbenv uses the system Ruby.

{project_folder}/Capfile

set :rbenv_type, :system # :system or :user
set :rbenv_ruby, '2.3.0'

add symbolic link to Capfile.

{project_folder}/Capfile

set :linked_dirs, %w{bin log tmp/pids tmp/cache tmp/sockets bundle public}

add pid file to Capfile.
By default, unicorn_rails will create a PID file. this path is not default.

{project_folder}/Capfile

set :unicorn_pid, -> {"#{shared_path}/tmp/pids/unicorn.pid"}

add default enviroment to Capfile.

{project_folder}/Capfile

set :default_env, { path: "/usr/local/rbenv/shims:/usr/local/rbenv/bin:$PATH" }

When you execute deploy, capistrano execute assets precompile. Code is follow.

{project_folder}/Capfile

  namespace :assets do
    Rake::Task['deploy:assets:precompile'].clear_actions
    
    desc "Precompile assets"
    task :precompile do
      puts "-----nothing-------"
    end
  end

When you execute deploy, capistrano restart unicorn. Code is follow.

{project_folder}/Capfile

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'unicorn:restart'
      # Your restart mechanism here, for example:
      # execute :touch, release_path.join('tmp/restart.txt')
    end
  end

Define Multiple Stages

Capistrano3 can define multiple stages.
At first, define staging.rb.

I use vagrant as staging environment. write code of ssh login.

{project_folder}/config/deploy/staging.rb

role :app, %w{root@192.168.33.50}
role :web, %w{root@192.168.33.50}
role :db,  %w{root@192.168.33.50}

set :ssh_options, {
  verbose: :debug,
  auth_methods: %w(password),
  password: "vagrant"
}

deploy test

execute deploy.

terminal

vagrant ssh

cd {project_folder}

bundle exec cap staging deploy:check

if error occurs, fix error.
you should pay attention to user permission. and you confirm as you can use git clone command.
execute command by root permission.

terminal

D, [2016-02-01T08:48:42.485315 #11434] DEBUG -- tcpsocket[3fe196317614]: received packet nr 55 type 96 len 12
I, [2016-02-01T08:48:42.485343 #11434]  INFO -- net.ssh.connection.session[3fe1963eb554]: channel_eof: 7
D, [2016-02-01T08:48:42.485384 #11434] DEBUG -- tcpsocket[3fe196317614]: received packet nr 56 type 97 len 12
I, [2016-02-01T08:48:42.485407 #11434]  INFO -- net.ssh.connection.session[3fe1963eb554]: channel_close: 7
D, [2016-02-01T08:48:42.485469 #11434] DEBUG -- tcpsocket[3fe196317614]: queueing packet nr 46 type 97 len 28
INFO [ca5786bf] Finished in 0.034 seconds with exit status 0 (successful).

check is success. On production environment, execute deploy.

deploy

execute production deploy.

terminal

I, [2016-01-26T06:40:47.922269 #745]  INFO -- net.ssh.connection.session[3fdd4a672b9c]: channel_data: 66 29b
DEBUG [159535d3]    Successful ping of Google
D, [2016-01-26T06:40:47.923078 #745] DEBUG -- tcpsocket[3fdd4a0a92ec]: received packet nr 465 type 94 len 44
I, [2016-01-26T06:40:47.923165 #745]  INFO -- net.ssh.connection.session[3fdd4a672b9c]: channel_data: 66 27b
DEBUG [159535d3]    Successful ping of Bing
D, [2016-01-26T06:40:47.923676 #745] DEBUG -- tcpsocket[3fdd4a0a92ec]: received packet nr 466 type 98 len 44

... // something 

INFO [db1051b1] Finished in 0.102 seconds with exit status 0 (successful).

Conclusion

Capistrano3 is convenient deployment tool.
In my case, I use Capistrano 3 with java and php.

Production environment should be automated. I recommend that you define capistrano, before you start project.

See you.

日本語

2016年2月1日月曜日

rails4.2.x Combine div tag with link_to

  • Published Date:Feb. 1, 2016

Article Summary

Explain how to combine div tag with link_to.

日本語で読む

Environment

  • rails4.2.4
  • ruby2.3.0

link_to

When you create web app on Rails, there are opportunities to combine div tag with a tag.
For example, HTML source, as follows:

{app_folder}/app/view/xxx.erb

<a href="">
<div>
 // image or text
</div>
</a>

A HTML described above could be combined div tag with like_to tag, as follows:

{app_folder}/app/view/xxx.erb

<%= link_to test_path(@test) do %>
<div>
 // image or text
</div>
<% end %>

link_to tag block surrounds div tag, Creates a link tag of div.

Conclusion

Blocks are one of the most useful function of ruby.
if you have a little time, I recommend that you study block of ruby.

See you.

日本語

2016年1月7日木曜日

elasticsearch. plugin install failed. SSLException java.security.ProviderException

  • Published Date:Jun. 7, 2016

Article Summary


On Elasticsearch, When I executed bin/plugin command, SSLException java.security.ProviderException occurred.
This article describes how to modify this error.
日本語で読む

Environment


  • vagrant centos6.5
  • elasticsearch2.1.1
  • java(OpenJDK) version 1.7.0_91

Failure of kuromoji plugin installation.


kurimoji is the Japanese Analysis plugin. elasticsearch 2.1 integrates this plugin as official.
So, this plugin can be installed using the plugin manager.

terminal

sudo /usr/share/elasticsearch/bin/plugin install --verbose analysis-kuromoji

Failed: SSLException[java.security.ProviderException: java.security.KeyException]; nested: ProviderException[java.security.KeyException]; nested: KeyException;
ERROR: failed to download out of all possible locations

But, in my environment, plugin installation failed.

Switch Java Version


The cause of the failure is java version.
so, I checked java version.

terminal

// centos
yum search java | grep openjdk
java-1.6.0-openjdk.x86_64 : OpenJDK Runtime Environment
java-1.6.0-openjdk-demo.x86_64 : OpenJDK Demos
java-1.6.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.6.0-openjdk-javadoc.x86_64 : OpenJDK API Documentation
java-1.6.0-openjdk-src.x86_64 : OpenJDK Source Bundle
java-1.7.0-openjdk.x86_64 : OpenJDK Runtime Environment
java-1.7.0-openjdk-demo.x86_64 : OpenJDK Demos
java-1.7.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.7.0-openjdk-javadoc.noarch : OpenJDK API Documentation
java-1.7.0-openjdk-src.x86_64 : OpenJDK Source Bundle
java-1.8.0-openjdk.x86_64 : OpenJDK Runtime Environment
java-1.8.0-openjdk-debug.x86_64 : OpenJDK Runtime Environment with full debug on
java-1.8.0-openjdk-demo.x86_64 : OpenJDK Demos
java-1.8.0-openjdk-demo-debug.x86_64 : OpenJDK Demos with full debug on
java-1.8.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.8.0-openjdk-devel-debug.x86_64 : OpenJDK Development Environment with
java-1.8.0-openjdk-headless.x86_64 : OpenJDK Runtime Environment
java-1.8.0-openjdk-headless-debug.x86_64 : OpenJDK Runtime Environment with full
java-1.8.0-openjdk-javadoc.noarch : OpenJDK API Documentation
java-1.8.0-openjdk-javadoc-debug.noarch : OpenJDK API Documentation for packages
java-1.8.0-openjdk-src.x86_64 : OpenJDK Source Bundle
java-1.8.0-openjdk-src-debug.x86_64 : OpenJDK Source Bundle for packages with

There is java-1.8.0-openjdk.
Next, check using java version.

terminal

alternatives --config java

There are 2 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
   1           /usr/lib/jvm/jre-1.5.0-gcj/bin/java
*+ 2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java


java-1.8.0-openjdk is not installed.
I will install it.

terminal

sudo yum install -y java-1.8.0-openjdk

check using java version.

terminal

java -version
java version "1.7.0_91"

Java version is still not changed. I will switch java version.

terminal

sudo alternatives --config java

There are 3 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
   1           /usr/lib/jvm/jre-1.5.0-gcj/bin/java
*+ 2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
   3           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Enter to keep the current selection[+], or type selection number: 3

I check using java version again.

terminal

java -version
openjdk version "1.8.0_65"
OpenJDK Runtime Environment (build 1.8.0_65-b17)
OpenJDK 64-Bit Server VM (build 25.65-b01, mixed mode)

Version was changed to java-1.8.0-openjdk.

Reinstallation of kurimoji plugijn


On java-1.8.0-openjdk, bin/plugin command executes again.

terminal

sudo /usr/share/elasticsearch/bin/plugin install --verbose analysis-kuromoji

Downloading .DONE
- Plugin information:
Name: analysis-kuromoji
Description: The Japanese (kuromoji) Analysis plugin integrates Lucene kuromoji analysis module into elasticsearch.
Site: false
Version: 2.1.1
JVM: true
 * Classname: org.elasticsearch.plugin.analysis.kuromoji.AnalysisKuromojiPlugin
 * Isolated: true
Installed analysis-kuromoji into /usr/share/elasticsearch/plugins/analysis-kuromoji

It worked out.
just in case, I will check installed plugin.

terminal

sudo /usr/share/elasticsearch/bin/plugin list
Installed plugins in /usr/share/elasticsearch/plugins:
    - analysis-kuromoji

I want to continie to using java7.

terminal

sudo alternatives --config java

There are 3 programs which provide 'java'.

  Selection    Command
-----------------------------------------------
   1           /usr/lib/jvm/jre-1.5.0-gcj/bin/java
*  2           /usr/lib/jvm/jre-1.7.0-openjdk.x86_64/bin/java
 + 3           /usr/lib/jvm/jre-1.8.0-openjdk.x86_64/bin/java

Enter to keep the current selection[+], or type selection number: 2

java -version
java version "1.7.0_91"
OpenJDK Runtime Environment (rhel-2.6.2.2.el6_7-x86_64 u91-b00)
OpenJDK 64-Bit Server VM (build 24.91-b01, mixed mode)

sudo /usr/share/elasticsearch/bin/plugin list
Installed plugins in /usr/share/elasticsearch/plugins:
    - analysis-kuromoji

It worked out.

Conclusion


On elasticsearch2.1.1, if you want to execute plugin command, you must update to java version 8.
Once installed, you can use by java version 7.

But I recommend that you makes your app environment latest. update work is very important.

See you

Reference Site


日本語


2016年1月6日水曜日

Rails5. Update work of rails v5.0.0 beta 1 from rails4. Page 2

  • Published Date:Jun. 6, 2016

Environment


  • rails 4.2.4, rails 4.2.5 → rails5.0.0 beta1
  • ruby 2.2.3
  • rbenv rbenv 0.4.0-183-gc18a3f9

Article Summary


Rails 5.0.0 Beta1 Released. I think Rails 5 will probably be released in spring of 2015.
But, if you change from rails 4 to rails 5 in Gemfile, your app would not operate correctly.

Currently, I'm doing much trial and error. At same time, I understood a lot of things. so, I write what I understood.
This article is a continuation from previous article.
read in Japanese

config.logger is unsupported


I took a lot of time this error. Rails 4.2.x implements log rotation from this setting. But this setting is fatal error on Rails 5.0.0 beta1.
So, you must change the following description.

Before

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  config.logger = Logger.new('log/development.log', 'daily')

After

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  # remove
  # config.logger = Logger.new('log/development.log', 'daily')

you must implement log rotation by another way.

cannot load such file -- sass


This error shows sass file was fail to read. So, remove sass file. Your app is launched normally.
This error shows that your app was fail to read sass file. You should remove sass file. if you do, your app will be launched successfully.

bin/setup


Compared with rails 4, this file was changed many settings.
For instance, rake commands were changed to rails commands.
you should use termial commnad.

terminal

rake rails:update

this command can overwrite bin/setup file. before execute, I recommend that git branch switch to new git branch.

Other


These files had better change to file of rails5.
you create sample rails 5 project, and your app should compared with sample rails 5 by diff.


// change
config/environments/development.rb

// new file
active_record_belongs_to_required_by_default.rb

Summary


Applied the contents of previous article and this article, I modified rails code. My app was be able to launch rails 5 successfully.
I plan to release my app on production mode in a few weeks.

See you.

Recommended Book for Rails 4 Developer


For Improving your ruby programming.


Administrating Site(createing rails)


Useful site


Japanese


Rails5 Update work of rails v5.0.0 beta 1 from rails4. Page 1

  • Published Date:Jun. 6, 2016

Environment


  • rails 4.2.4, rails 4.2.5 → rails5.0.0beta1
  • ruby 2.2.3
  • rbenv rbenv 0.4.0-183-gc18a3f9

Article Summary


Rails 5.0.0Beta1 Released. I think Rails 5 will probably be released in spring of 2015.
But, if you change from rails 4 to rails 5 in Gemfile, your app would not operate correctly.

Currently, I'm doing much trial and error. At same time, I understood a lot of things. so, I write what I understood.

Japanese

Spring is unsupported


On Rails 5.0.0Beta1, Spring gem is not available. So, if your app uses spring, you should remove spring gem.
if you use Bundler, you should do the follow.

terminal

vi Gemfile

// comment out
#gem 'spring'
#gem 'spring-commands-rspec'

rbenv exec bundle exec gem uninstall spring
rbenv exec bundle exec gem uninstall spring-commands-rspec

kaminari is unsupported


On Rails 5.0.0Beta1, kaminari gem is not available. it occurs ActionView::MissingTemplate.
if you want to use kaminari, you should change to latest kaminari gem.
if you use Bundler, you should change the Gemfile.

Before

{project_folder}/Gemfile

gem 'kaminari'

After

{project_folder}/Gemfile

gem 'kaminari', github: 'amatsuda/kaminari'

After you modified Gemfile, execute bundle update.

terminal

rbenv exec bundle install

Using kaminari 1.0.0.alpha (was 0.16.3) from git://github.com/amatsuda/kaminari.git (at master)

DEPRECATION WARNING: `serve_static_files` is deprecated and will be removed in Rails 5.1.


serve_static_files became deprecated. This is from Rails 4.2, and will remove it completely on Rails 5.1.
So, you must change the following description.

Before

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  # Configure static asset server for tests with Cache-Control for performance.
  config.serve_static_files  = true

After

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  # Configure static asset server for tests with Cache-Control for performance.
  config.public_file_server.enabled  = true

DEPRECATION WARNING: `static_cache_control` is deprecated and will be removed in Rails 5.1.


static_cache_control became deprecated. This will be also removed completely on Rails 5.1.
So, you must change the following description.

Before

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  # config.serve_static_assets = ENV['RAILS_SERVE_STATIC_FILES'].present?
  config.static_cache_control = 'public, max-age=3600'

After

{project_folder}/config/environments/test.rb(development.rb and production.rb)

  # config.serve_static_assets = ENV['RAILS_SERVE_STATIC_FILES'].present?
  config.public_file_server.headers = { 'Cache-Control' => 'public, max-age=3600' }

DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1.


before_filter became deprecated. This method is very useful, but removed completely on Rails 5.1.
So, you must change the following description.

Before

{projectfolder}/app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_filter :set_locale
  
  // something

end

After

{projectfolder}/app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

  before_action :set_locale
  
  // something

DEPRECATION WARNING: use_transactional_fixtures= is deprecated and will be removed from Rails 5.0.


use_transactional_fixtures became deprecated. This is still unsupported on Rspec. So, you must not modify this.

Summary


if you think rails 5 update, it takes a lot of times.
so, you create new git branch soon, take measures.

I always think that rails major updating is difficult. But rails 5 updating is easier than rails 4 updating.
Rails has always evolved. This time is also same.

See you

Recommended Book for Rails 4 Developer


For Improving your ruby programming.


Administrating Site(createing rails)


Useful site


Japanese

2016年1月4日月曜日

Execute Rpsec Test. remote true ajax method on Rails Controller.

  • Published Date:Jun. 4, 2016

Article Summary


On Rails, developer can easy to implement ajax.
But, in case of doing rspec test, you must write code in a deffrent way from normal controller rspec test.

This article describes how toimplement "remote ajax rspec".

Environment


  • ruby 2.2.4
  • rails 4.2.5
  • spec-rails 3.0.2

Noraml Controller Implementation


Generally, when developers implement rails controller of rspec, implement like the following example.

/app/controller/test_controller.rb

post :confirm, @params

Detail Explanation

  • controller: test_controller.rb
  • method : confirm
  • method type : post
  • parameter : @params

This is general implementation method of rails controller.
Let's change rspec test from this to "remote true" ajax method.

"remote true" ajax method Controller Implementation


Using xhr, Rspec can call ajax method of controller.

/app/controller/test_controller.rb

xhr :post, :confirm, @params

Very easy.
Enjoy Rspec Life.

See you.

Recommended Book for Rails 4 Developer


For Improving your ruby programming.


Administrating Site(createing rails)


日本語

2016年1月3日日曜日

Update Ruby Version On Using Rails 4. Update from Ruby 2.2.4 to Ruby 2.3.0.

  • Published Date:Jun. 3, 2016

Article Summary


This article describes how to update from Ruby 2.2.4 to Ruby 2.3.0 on Rails 4.

Environment


  • Rails4.2.5
  • Ruby2.2.4 → Ruby2.3.0

Switch Ruby2.3.0


ruby 2.3.0 to proceed with the description in the premise on which it is installed.

terminal

// switch ruby version
rbenv global 2.3.0

ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

Install required Gem


Install required Gem for ruby 2.3.0p0.

terminal

// confirm gem version.
rbenv exec gem -v
2.5.1

rbenv exec gem list --local

*** LOCAL GEMS ***

bigdecimal (1.2.8)
did_you_mean (1.0.0)
io-console (0.4.5)
json (1.8.3)
minitest (5.8.3)
net-telnet (0.1.1)
power_assert (0.2.6)
psych (2.0.17)
rake (10.4.2)
rdoc (4.2.1)
test-unit (3.1.5)

// install bundler for ruby 2.3.0p0 
rbenv exec gem install bundler

rbenv exec gem list --local

*** LOCAL GEMS ***

bigdecimal (1.2.8)
bundler (1.11.2)
did_you_mean (1.0.0)
io-console (0.4.5)
json (1.8.3)
minitest (5.8.3)
net-telnet (0.1.1)
power_assert (0.2.6)
psych (2.0.17)
rake (10.4.2)
rdoc (4.2.1)
test-unit (3.1.5)

After Confirming ruby 2.3.0 and gem, Install required gem for rails project.

terminal

// move project folder
cd {prohect_folder}

// confirm gemfile.lock

// execute bundle install
rbenv exec bundle install --path /home/vagrant/vanish/dev/vendor/bundle

Bundle complete! 18 Gemfile dependencies, 70 gems now installed.

After completion, you execute test to confirm degradation.

terminal

// execute test
rbenv exec bundle exec rspec

Finished in 0.7514 seconds (files took 6.03 seconds to load)
42 examples, 0 failures, 4 pending

Worked out well.

Conclusion


In my case, It was easy to change from Ruby 2.2.4 to Ruby 2.3.0.
You should try it.
From now on, I will try to implement new function of Ruby 2.3.0.
Thank you for reading this article.

See you.

Recommended Book for Rails 4 Developer


For Improving your ruby programming.


Administrating Site(createing rails)


日本語

2015年12月27日日曜日

Rubyのバージョンをアップする rbenvを利用してRuby2.2.4からRuby2.3.0へアップデート

  • 公開日:2015年12月27日

記事概要


Ruby2.3.0が2015年12月25日にリリースされました。この記事はRubyのバージョンをアップする方法を記載した記事です

環境


  • Ruby2.2.4 → Ruby2.3.0
  • centos6.5
  • rbenv

現在のrbenvとrubyのバージョンを確認


まずは現状の環境の確認をします。Rubyの現在のバージョンを確認します。

terminal

ruby -v
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-linux]

続けてrbenvの現在のバージョンを確認します。

terminal

rbenv -v
rbenv 0.4.0-215-g90373d7

インストール可能なrubyの一覧を確認します。

terminal

rbenv install --list
  2.2.4
  2.3.0-dev
  2.3.0-preview1
  2.3.0-preview2

まだRuby2.3.0はありませんね。

rbenvのバージョンアップ


Ruby2.3.0を利用できるように、rbenvとruby-buildをupdateします。
まずはrbenvです。

terminal

// pathを確認
which rbenv
~/.rbenv/bin/rbenv

// rbenv配下に移動
cd ~/.rbenv
// pullで最新バージョンを習得
git pull

// バージョンチェック
rbenv -v
rbenv 1.0.0-3-g22f4980

// 反映
rbenv rehash

ruby-buildのバージョンアップ


続いてruby-buildです。

terminal

// rbenvのruby-build配下に移動
cd .rbenv/plugins/ruby-build
// pullで最新バージョンを習得
git pull

Fast-forward
 bin/ruby-build             |    2 +-
 script/brew-publish        |    2 +-
 share/ruby-build/2.3.0     |    2 ++
 share/ruby-build/2.3.0-dev |    2 +-
 share/ruby-build/2.4.0-dev |    2 ++

インストール可能なrubyの一覧を確認します。

terminal

 rbenv install --list

  2.3.0-dev
  2.3.0-preview1
  2.3.0-preview2
  2.3.0
  2.4.0-dev

Ruby2.3.0が追加されていますね。2.4.0-devまで追加されていますが、ご愛嬌。

Ruby2.3.0install


いよいよRuby2.3.0をinstallします。rbenvを使ってinstallします。

terminal

// install
rbenv install 2.3.0

// デフォルトの設定にする
rbenv global 2.3.0

// versionチェック         
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]

上手く導入できました。

まとめ


Rubyは着実に良いバージョンアップをしている言語だと思います。
まだしばらくは、WEBアプリ開発のメイン言語として活躍してくれそうです。

railsへの適用, chefを使ったupdate, 2.3の新機能の使い方も適用次第、説明していきたいと思います。

以上です

Rails4の開発にオススメの本


Rubyの応用力をつけるのにオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年12月26日土曜日

rails4 uninitialized constant Xxxx::Application::CN (NameError)

  • 公開日:2015年12月26日

記事概要


rails4で多言語化対応したときに、発生したエラーの修正方法をまとめた記事です。

環境


  • ruby2.2.3
  • rails4.2.5
  • unicorn
  • nginx1.8

多言語化


多言語化設定をするときに、application.rbに以下のような設定をしました。

config/application.rb

    config.i18n.default_locale = :en
    config.i18n.available_locales = [:en, :ja, :zh-CN]

上記の記載をすると「uninitialized constant Xxxx::Application::CN (NameError)」が発生しました。
調査したところ、原因は中国語(zh-CN)の設定でした。

エラーを修正するには、上記を

config/application.rb

    config.i18n.default_locale = :en
    config.i18n.available_locales = [:en, :ja, "zh-CN"]

のように修正したら動くようになりました。
zh-CNは【:】でなく、【"】で指定しないと動かないようです。

まとめ


railsのアプリは、最小限の実装で多言語化に対応できます。
アプリを作るなら、是非世界を目指したサービスを作成しましょう。
最初は、日本語の他は、英語と中国語だけで十分だと思います。

以上です

Rails4の開発にオススメの本


Rubyの応用力をつけるのにオススメの本


運営サイト(railsで作成しています)


参考サイト

rails4 多言語化対応を行う

  • 公開日:2015年12月17日

記事概要


rails4で多言語化に対応したので、そのやり方を記載した記事です。

環境


  • ruby2.2.3
  • rails4.2.5
  • unicorn
  • nginx1.8

Gemfile


railsの多言語化対応には、Rails Internationalization (I18n)を利用します。(Rails Internationalization (I18n) API )
まずはgemを導入します。

Gemfile

# Use rails-i18n for localization
gem 'rails-i18n', '~> 4.0.0'

記載して保存したらgemをinstallします。

terminal

rbenv exec bundle install

installに成功したのを確認したら先に進みます。

利用言語の設定


railsアプリで利用する言語を設定します。
設定はapplication.rbに記載します。

config/application.rb

    config.i18n.default_locale = :en
    config.i18n.available_locales = [:en, :ja, "zh-CN"]

上記の設定では、config.i18n.default_localeでデフォルトの言語を「英語」にしています。
また、「英語」「日本語」「中国語(簡体字)」を config.i18n.available_localesで利用可能な言語に設定しています。

テストの実行


これまでの設定が正しいことを確認するために、テストを流します(テストコードを記載していないプロジェクトの場合は、この箇所は無視してください。)

terminal

rbenv exec bundle exec rspec

Finished in 0.13951 seconds (files took 2.76 seconds to load)

成功したら、次はrouteを修正します。

Routeの設定


言語を判別するには、

  • 言語をサブドメインに記述する(http://en.www.test.com)
  • パラメーターに言語情報を持つ(http://www.test.com?lang=en)
  • URLに記述する(http://www.test.com/en/)

のパターンがありますが、ここでは「URLに記述」のパターンを利用します。
routes.rbを開き、scopeで既存のurl routeを囲みます。

config/routes.rb

scope "(:locale)", locale: /ja|en|zh-CN/ do
  get 'home', to: 'home#index'
  resources :test
end

続いて、パラメータからlocaleを判定することが出来るようにapplication_controller.rbに処理を記載します。

app/controllers/application_controller.rb

  before_filter :set_locale
  
  # 全リンクにlocale情報をセットする
  def default_url_options(options={})
    { :locale => I18n.locale }
  end

  # リンクの多言語化に対応する
  def set_locale
    I18n.locale = params[:locale] || I18n.default_locale
  end

続いては、言語ファイルを用意しましょう。

locales


言語のファイルはlocalesファイルの下に配置します。

config/locales

en.yml
zh-CN.yml
ja.yml

config/locales/en.yml

en:
  hello: "Hello world"

config/locales/ja.yml

ja:
  hello: "こんにちわ"

config/locales/zh-CN.yml

zh-CN:
  hello: "你好"

これで準備は完了です。

View


tメソッドを利用します。引数はhashのkeyを指定します。

app/views/xxxxx.erb

<%= t("hello") %>

ブラウザで確認します。

デフォルト(英語): http://192.168.33.40:3000/home

日本: http://192.168.33.40:3000/ja/home

中国語: http://192.168.33.40:3000/zh-CN/home

見事に反映されていますね。

まとめ


railsのアプリは、最小限の実装で多言語化に対応できます。
アプリを作るなら、是非世界を目指したサービスを作成しましょう。
最初は、日本語の他は、英語と中国語だけで十分だと思います。

以上

Rails4の開発にオススメの本


オススメ開発マシン


運営サイト(railsで作成しています)


参考サイト

2015年12月5日土曜日

rails4 rails4.2.4から4.2.5にバージョンアップする

  • 公開日:2015年12月05日

記事概要


rails4.2.4から4.2.5にバージョンアップしたときの手順を記載した記事です。

環境

  • rails4.2.4→rails4.2.5
  • ruby2.2.3
  • Foundation 6

rails4.2.5のリリース


rails4.2.5が2015年12月にリリースされました。
久しぶりのバージョンアップです。
直近にruby2.3のリリースとrails5のリリースも控えているので、サクッとバージョンアップしておきましょう。

Gemfileの変更


Gemfileを以下のように書き換えます。

{rail-app-folder}/Gemfile

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.4'

↓

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.2.5'

rails update


bundle updateを実行します。bundle updateを実行することで、Gemfile.lockを更新できます。

terminal

// Gemfile.lock を更新いてgemを更新する
rbenv exec bundle update

// gemを更新(確認用。実行しなくてもOK)
rbenv exec bundle install

// railsのバージョンを確認
rbenv exec bundle exec rails --version
Rails 4.2.5

テストを実行


テストを実行してデグレが起きていないことを確認します。

terminal

// テストを実行
rbenv exec bundle exec rspec

rails4.2.4で動いていれば、4.2.5でも問題は発生しないと思います。あとは、ブラウザで動作確認もしておきましょう。

まとめ


ruby2.3のリリースとrails5のリリースが近づいています。環境はなるべく意識して最新の状態を保ちましょう。
でないと、移行作業に苦労してしまいます。
いつもいっているように、あまり技術的負債を溜めないようにしましょう。

以上です。

Rails4の開発にオススメの本


運営サイト(railsで作成しています)


関連記事

rails4 Foundation 6を使用する

  • 公開日:2015年12月05日

記事概要


rails4でFoundation 6を利用する場合の説明記事です。

環境

  • rails4.2.4
  • ruby2.2.3
  • Foundation 6

Foundation 6のインストール


Foundation 6の公式サイトには以下のgemを使った導入方法の説明が記載されています。

{rail-app-folder}/Gemfile

gem 'foundation-rails'

しかし、この方法はお勧めしません。
理由は、Foundation6が不要になったり、Foundation6のアップデートをする場合に、gemでインストールしてしまうと後の修正が大変になってしまうからです。
なので、この記事では、通常のダウンロードをしてファイルを配置する形を説明します。

Foundation 6に必要なファイルを配置する


公式サイトからダウンロードしてきたFoundation 6のファイルをrailsアプリのディレクトリに配置します。
rails4では、cssやjavascriptのファイルをAsset Pipelineの機能を利用して使うのが一般的です。この機能を利用する場合は、app/assetsディレクトリにcssやjsを配置する必要があります。

今回のアプリでもAsset Pipelineは利用するので、

{rail-app-folder}/app/assets/stylesheets

foundation.css

{rail-app-folder}/app/assets/javascripts

foundation.js

のようにファイルを配置します。

app/views/layout/application.html.erbへの記載


Foundation6のcssとjsファイルは共通で利用するので、application.html.erbに

app/views/layout/application.html.erb

  <%= stylesheet_link_tag "application", media: "all" %>
  <%= javascript_include_tag "application" %>

のように記述します。

アプリを起動


WEBrickを起動して確認しましょう。

terminal

rbenv exec bundle exec rails s -b 0.0.0.0

うまくアプリが立ち上がったら、ブラウザからソースコードを確認して、

html

<link rel="stylesheet" media="all" href="/assets/foundation.self-9b3ba3fcd76e7ef0282715e4069bac5699978f1970d3ac85f98ddf645c955531.css?body=1" />
<link rel="stylesheet" media="all" href="/assets/application.self-e80e8f2318043e8af94dddc2adad5a4f09739a8ebb323b3ab31cd71d45fd9113.css?body=1" />

のようにhtmlが生成されていることを確認しましょう。

まとめ


Foundation6はFoundation5と比較すると、かなりの変更が行われています。
間違ってbundle updateでcssやjsを更新してしまうと、画面デザインがめちゃくちゃになってしまうので気を付けましょう。
cssやjsは手動で配置することをお勧めします。

また、本番環境でAsset Pipelineが失敗しないように、必ず本番用のデプロイ手順(自動化)も用意しましょう。個人的には、railsのdeployにはcapistranoを使うのが良いと思います。

以上です。

Rails4の開発にオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年12月1日火曜日

rails4 ActiveModel::ForbiddenAttributesErrorの対応

  • 公開日:2015年12月01日

記事概要


ActiveModel::ForbiddenAttributesErrorが発生した場合の対応方法を説明した記事です。

環境


  • ruby2.2.3
  • ruby4.2.4

ActiveModel::ForbiddenAttributesErrorとは


Mass-assignment (モデルの複数属性への一括代入)を防ぐために発生するエラーです。
rails4では、 Strong Parameters を用いて Mass-assignment に対応します。

ActiveModel::ForbiddenAttributesErrorが発生するコード


以下にサンプルのコントローラーを記載します。createメソッドは、submitボタンを押されると呼び出され、User情報を作成します。

app/controllers/user_controller.rb

class UserController < ApplicationController

  def create
    @user = User.new(params)
    # salt作成
    @user.salt
      if @user.save
      redirect_to action: 'show', id: @user.id
    else
      flash[:notice] = 'Successfully checked in'
      redirect_to controller: 'home', action: 'index'
    end
  end

end

上記の処理でcreateメソッドが呼び出されると、ActiveModel::ForbiddenAttributesErrorが発生します。
このエラーを防ぐために、下記のように修正します。

ActiveModel::ForbiddenAttributesErrorが発生しないように修正した処理


app/controllers/user_controller.rb

class UsesController < ApplicationController

  def create
    @user = User.new(user_params)
    # salt作成
    @user.salt
      if @user.save
      redirect_to action: 'show', id: @user.id
    else
      flash[:notice] = 'Successfully checked in'
      redirect_to controller: 'home', action: 'index'
    end
  end
  
    private

    # Never trust parameters from the scary internet, only allow the white list through.
    def user_params
      params.require(:user).permit(:name, :password)
    end

end

「params.require(:user).permit(:name, :password)」となっています。
このコードは「params が :user というキーを持ち、params[:user] は :name 及び :password というキーを持つハッシュであること」を検証しています。

上記の実装を追加することで、エラーなく実行することが可能になります。

まとめ


ActiveModel::ForbiddenAttributesErrorは簡単に修正できます。
しかし、rails3からアップデートする場合は、コード量次第ではそれなりの時間を取られるかもしれません。
面倒ですが、技術的負債はこまめに返してきましょう。

以上です。

Rails4の開発にオススメの本


Rubyの応用力をつけるのにオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年11月29日日曜日

rails4 modelのvalidate:maximumをrspecでテストする

  • 公開日:2015年11月29日

記事概要


rails4でmodelのvalidateをrspecで記述する方法の説明記事です。
すぐ忘れてしまうので、まとめました。参考にする際は、rspecのバージョンに注意してください。この記事では3.X系を利用しています。

環境


  • ruby2.2.3
  • ruby4.2.4
  • rspec-rails 3.0.2

モデルの作成


ここではサンプルとしてNoteというモデルを作成します。

このモデルにvalidateを記載します。

models/note.rb

# encoding: utf-8
class Note < ActiveRecord::Base

  validates :title, length: { maximum: 64 }

end

上記のモデルでは、titleという属性をもっています。validateとして、

  • 最大文字数は64文字

を設定しています。
このvalidateをテストするrspecを実装します。

rspecモデルの作成


spec/models/note_spec.rbにテストコードを実装します。
境界値のエラー文字数65字の文字列を設定します。

spec/models/note_spec.rb

  it "fails validation with 65 word number of title" do
    note = Note.new
    ## 65文字を設定
    note.title = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    
    expect(note).not_to be_valid
  end

失敗を期待するので、not_to be_validを指定しています。上記のrspecを実行します。

terminal

benv exec bundle exec rspec spec/models/note_spec.rb

1 example, 0 failures

うまくいきました。次は境界値の正常文字数64字の文字列を設定します。

spec/models/note_spec.rb

  it "successes validation with 64 word number of title." do
    note = Note.new
    ## 64文字を設定
    note.title = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    
    expect(note).to be_valid
  end

失敗を期待するので、be_validを指定しています。実行します。

terminal

benv exec bundle exec rspec spec/models/note_spec.rb

2 example, 0 failures

うまくいきました。最後に値がnilの場合を設定します。

spec/models/note_spec.rb

  it "successes validation with nil of title" do
    note = Note.new
    expect(note).to be_valid
  end

実行します。

terminal

benv exec bundle exec rspec spec/models/note_spec.rb

3 example, 0 failures

うまくいきました。

まとめ


modelのvalidate処理は、テストコードを書く必要があるかどうかは微妙だと個人的には思っています。

とはいえ、書いておいても損はないと思うので、プロジェクトの締め切りに応じて書く、書かないをコントロールするとよいのではないでしょうか。

以上です。

Rails4の開発にオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年10月8日木曜日

Vagrant has detected that you have a version of VirtualBox installed that is not supported. vagrantをバージョンアップ

  • 公開日:2015年10月08日

記事概要


Docker Toolboxをインストールした後にvagrantを起動したら「Vagrant has detected that you have a version of VirtualBox installed that is not supported. 」というエラーが発生しました。どうやら、Docker Toolboxをインストールすると、VirtualBox自動的にアップデートされてしまうようです。
この記事は、起動しなくなったVagrantを再び動かすための対策方法です。

環境


  • vagrant1.6.3→1.7.4

vagrant upエラー


vagrant upコマンドを実行すると、以下のエラーが発生しました。


The provider 'virtualbox' that was requested to back the machine
'default' is reporting that it isn't usable on this system. The
reason is shown below:

Vagrant has detected that you have a version of VirtualBox installed
that is not supported. Please install one of the supported versions
listed below to use Vagrant:

4.0, 4.1, 4.2, 4.3

原因は、Docker Toolboxのインストールです。
Docker Toolboxのインストールにより、自動的にVirtualBoxがアップデートされてしまったようです。
VirtualBoxのバージョンを確認します。


VBoxManage -v
5.0.4r102546

4系を利用していたのが5系になっています。
これが原因で古いvagrantが動かなくなったようです。
現在のvagrantのバージョンを確認します。


vagrant -v
Vagrant 1.6.3

現在(2015/10/05)はversion 1.7.4が最新なので入れ替えます。
公式サイトに遷移します。
vagrantをダウンロードして再インストールします。

インストール後は、マシンを再起動してバージョンを確認します。


vagrant -v
Vagrant 1.7.4

1.7.4になったのでvagrantが起動しなくなってしまったプロジェクトに移動してvagrant upを実行します。


cd {project-folder}
vagrant up

default: flag to force provisioning. Provisioners marked to run always will still run.

動作しました。これで完了です。

まとめ


そろそろvagrantをサブにして、本格的にdockerに移行していかないといけないなと思いました。

いつも言っていますが、技術的負債は溜めないようにしましょう。
やばいと感じたら、すぐに新しい技術を取り入れましょう。
技術的負債の解消は、当初想像するよりずっと時間がかかるのが普通です。

以上です。

Rails4の開発にオススメの本


イノベーションを感じるのにオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年9月27日日曜日

Rails4のバージョンをアップする rails4.2.1からrails4.2.4へアップデート

  • 公開日:2015年09月27日

記事概要


Rails4でRails4のバージョンをアップする方法を記載した記事です

環境


  • Rails4.2.4
  • Ruby2.2.2
  • bundle, rbenv

Rails4のバージョンアップ


rails4.2.1からrails4.2.4へのアップデートは、マイナーバージョンアップデートです。
アップデートをするにあたって、特に注意点はありません。
なので、

  • railsのアップデート
  • テストコードの実行
  • 動作確認

の手順を一気に進めていきます。

まずはGemfileを変更します。

Gemfile

#gem 'rails', '4.2.1'
gem 'rails', '4.2.4'

設定ファイルの変更が終わったら『bundle update rails』コマンドでrailsのみを更新します。


bundle update rails
Fetching gem metadata from https://rubygems.org/............
Fetching version metadata from https://rubygems.org/...
Fetching dependency metadata from https://rubygems.org/..
Resolving dependencies........
Using rake 10.4.2
Using i18n 0.7.0
Installing json 1.8.3 (was 1.8.2)
Installing minitest 5.8.1 (was 5.6.0)
Using thread_safe 0.3.5
Using tzinfo 1.2.2
Installing activesupport 4.2.4 (was 4.2.1)
Using builder 3.2.2
Using erubis 2.7.0
Using mini_portile 0.6.2
Using nokogiri 1.6.6.2
Using rails-deprecated_sanitizer 1.0.3
Installing rails-dom-testing 1.0.7 (was 1.0.6)
Installing loofah 2.0.3 (was 2.0.1)
Using rails-html-sanitizer 1.0.2
Installing actionview 4.2.4 (was 4.2.1)
Installing rack 1.6.4 (was 1.6.0)
Using rack-test 0.6.3
Installing actionpack 4.2.4 (was 4.2.1)
Installing globalid 0.3.6 (was 0.3.5)
Installing activejob 4.2.4 (was 4.2.1)
Installing mime-types 2.6.2 (was 2.5)
Using mail 2.6.3
Installing actionmailer 4.2.4 (was 4.2.1)
Installing activemodel 4.2.4 (was 4.2.1)
Installing arel 6.0.3 (was 6.0.0)
Installing activerecord 4.2.4 (was 4.2.1)
Using bundler 1.9.8
Using thor 0.19.1
Installing railties 4.2.4 (was 4.2.1)
Using hike 1.2.3
Installing multi_json 1.11.2 (was 1.11.0)
Using tilt 1.4.1
Installing sprockets 2.12.4 (was 2.12.3)
Installing sprockets-rails 2.3.3 (was 2.2.4)
Installing rails 4.2.4 (was 4.2.1)
Using actionview-encoded_mail_to 1.0.7
Using addressable 2.3.8
Using descendants_tracker 0.0.4
Using ice_nine 0.11.1
Using axiom-types 0.1.1
Using colorize 0.7.7
Using net-ssh 2.9.2
Using net-scp 1.2.1
Using sshkit 1.7.1
Using capistrano 3.2.1
Using capistrano-bundler 1.1.4
Using capistrano-rails 1.1.3
Using capistrano-rbenv 2.0.3 from git://github.com/capistrano/rbenv.git (at master)
Using capistrano-ssh-doctor 1.0.0
Using capistrano3-unicorn 0.2.1
Using hitimes 1.2.2
Using timers 4.0.1
Using celluloid 0.16.0
Using coderay 1.1.0
Using coercible 1.0.0
Using coffee-script-source 1.9.1.1
Using execjs 2.5.2
Using coffee-script 2.4.1
Using coffee-rails 4.0.1
Using database_cleaner 1.4.1
Using diff-lcs 1.2.5
Using launchy 2.4.3
Using email_spec 1.6.0
Using equalizer 0.0.11
Using factory_girl 4.5.0
Using factory_girl_rails 4.5.0
Using ffi 1.9.8
Using formatador 0.2.5
Using hashie 3.4.1
Using multi_xml 0.5.5
Using rack-accept 0.4.5
Using rack-mount 0.8.3
Using virtus 1.0.5
Using grape 0.11.0
Using rb-fsevent 0.9.4
Using rb-inotify 0.9.5
Using listen 2.10.0
Using lumberjack 1.0.9
Using nenv 0.2.0
Using shellany 0.0.1
Using notiffany 0.0.6
Using method_source 0.8.2
Using slop 3.6.0
Using pry 0.10.1
Using guard 2.12.5
Using guard-compat 1.2.1
Using rspec-support 3.2.2
Using rspec-core 3.2.3
Using rspec-expectations 3.2.1
Using rspec-mocks 3.2.1
Using rspec 3.2.0
Using guard-rspec 4.5.0
Using jbuilder 2.2.13
Using jquery-rails 4.0.3
Using kaminari 0.16.3
Using kgio 2.9.3
Using libv8 3.16.14.7
Using mysql2 0.3.18
Using raindrops 0.13.0
Using rdoc 4.2.0
Using ref 1.0.5
Using rspec-rails 3.2.1
Using sass 3.2.19
Using sass-rails 4.0.5
Using sdoc 0.4.1
Using spring 1.3.4
Using spring-commands-rspec 1.0.4
Using therubyracer 0.12.2
Using uglifier 2.7.1
Using unicorn 4.9.0
Bundle updated!

成功です。続けてrspecの既存のテストコードを実行します。


bundle exec rspec spec
155 examples, 0 failures

成功です。
最後に、ブラウザ経由で一通りの動作を確認します。問題なければ、Rails4のバージョンアップは成功となります。

あとはCapistrano等を使って本番環境にビルドしましょう。

まとめ


2015年の秋には、rails5のリリースが予定されています。
技術的負債が溜まっているプロジェクトを抱えているなら、今のうちにコツコツと解消しておきましょう。

以上

Rails4の開発にオススメの本


イノベーションを感じるのにオススメの本


運営サイト(railsで作成しています)


参考サイト

2015年9月26日土曜日

Rails4でログを日付でローテーションする

  • 公開日:2015年09月26日

記事概要


Rails4でログを日付でローテーションする設定方法を記載した記事です

環境


  • Rails4.2.4
  • Ruby2.2.2
  • bundle, rbenv

Rails4ログ設定の基本


Rails4のログはデフォルトの設定では、


{project folder}/log

の配下に出力されます。
また、ログは環境ごとに別ファイルで出力されます。

ログファイル

path 説明
log/development.log 開発環境で出力されるログ
log/production.log 本番環境で出力されるログ
log/test.log テスト環境で出力されるログ

環境ごとに出力されるログレベルはデフォルトでは以下になります。

ログレベル

環境(ENV) ログレベル(LOG LEVEL)
development debug
production info
test debug

上記で説明したことを総合すると、本番環境でのログ出力は
ログレベルinfoでlog/production.logに出力される
ということになります。

しかし、このデフォルト設定のままで、アプリを使用し続けるとログの容量が大量に蓄積してしまいます。
なので、適切なログのローテーションの設定をする必要があります。

Rails4ログローテションの設定


Rails4でログローテションの設定をするのは簡単です。

environment/production.rb

config.logger = Logger.new('log/production.log', 'daily')

上記は本番環境の設定です。
一日ごとにログローテーションをして、ログをlog/production.logに出力しています。
また、本番環境以外に適用するには、環境別の設定ファイルに記載することで反映されます。

環境別の設定ファイル

環境(ENV) 設定ファイル(SETTING FILE)
共通 application.rb
開発環境 environment/development.rb
本番環境 environment/production.rb
テスト環境 environment/test.rb

第二引数の'daily'を設定することで、production.log.YYYYMMDD.N といったログファイルが生成されます。
他にも'weekly'と'monthly'が利用できます。

また、日付でローテーションの設定をした場合、古い日付のログを自動で削除することはできません。
なので、古い日付のログが不要な場合は、シェルを作成してcronで古いログを削除するようにします。

まとめ


Rails4では他にも容量でログのログローテーションを設定することも可能です。こちらの設定をした場合、 過去のログファイルを自動で削除することができます。
また、Linuxのlogrotateの機能を利用することもできます。

どの機能にも一長一短があり、ベストな解はありません。
自分のアプリに最も適したログの設定をすることが重要になります。

以上です。

Rails4の開発にオススメの本


イノベーションを感じるのにオススメの本


運営サイト(railsで作成しています)


参考サイト