カテゴリー : Ruby on Rails

[Ruby on Rails 4] group :assets do … end は廃止

Ruby on Rails 4 から Gemfile に group :assets do … end と書くのは廃止になったそうです。

Ruby on Rails | ルビーオンレイルズ

続きを読む

Ruby on Rails4 + Mongoid + RSpec

Ruby on Rails4 + Mongoid + RSpec の環境構築メモ。

gem install rails --version 4.0.1
rails new myapp --skip-active-record --skip-test-unit
cd myapp
# Gemfile
gem 'mongoid', git: 'https://github.com/mongoid/mongoid.git'
rails g mongoid:config
      create  config/mongoid.yml
rails g rspec:install
% git diff
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb
index 943bc19..9b7b0ef 100644
--- a/spec/spec_helper.rb
+++ b/spec/spec_helper.rb
@@ -13,6 +13,19 @@ Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
 ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)
 
 RSpec.configure do |config|
+  ## Mongoid
+  config.before(:suite) do
+    DatabaseCleaner[:mongoid].strategy = :truncation
+  end
+
+  config.before(:each) do
+    DatabaseCleaner[:mongoid].start
+  end
+
+  config.after(:each) do
+    DatabaseCleaner[:mongoid].clean
+  end
+
   # ## Mock Framework
   #
   # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line:
@@ -22,12 +35,12 @@ RSpec.configure do |config|
   # config.mock_with :rr
 
   # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
-  config.fixture_path = "#{::Rails.root}/spec/fixtures"
+  # config.fixture_path = "#{::Rails.root}/spec/fixtures"
 
   # If you're not using ActiveRecord, or you'd prefer not to run each of your
   # examples within a transaction, remove the following line or assign false
   # instead of true.
-  config.use_transactional_fixtures = true
+  # config.use_transactional_fixtures = true
 
   # If true, the base class of anonymous controllers will be inferred
   # automatically. This will be the default behavior in future versions of
diff --git a/config/application.rb b/config/application.rb
index 7c9e566..9694074 100644
--- a/config/application.rb
+++ b/config/application.rb
@@ -4,7 +4,7 @@ require File.expand_path('../boot', __FILE__)
 # require "active_record/railtie"
 require "action_controller/railtie"
 require "action_mailer/railtie"
-require "sprockets/railtie"
+# require "sprockets/railtie"
 # require "rails/test_unit/railtie"
 
 # Require the gems listed in Gemfile, including any gems
diff --git a/config/initializers/mongoid.rb b/config/initializers/mongoid.rb
new file mode 100644
index 0000000..e400231
--- /dev/null
+++ b/config/initializers/mongoid.rb
@@ -0,0 +1 @@
+Mongoid.load!(Rails.root.to_s + "/config/mongoid.yml")

参考情報

Mongoid: Installation

Getting Started Rails 4 with MongoDB | Just Some More Dev Ideas

Using Mongoid with Rspec

Mongoid: Installation [Configuration]

[Ruby on Rails] PDFKit が NoMethodError (undefined method `chomp’ for nil:NilClass): というエラーで動かない

Ruby on Rails で PDFKit を使ってまして、CentOS で動かないという状況に陥りました。

NoMethodError (undefined method `chomp' for nil:NilClass):
  pdfkit (0.5.3) lib/pdfkit/configuration.rb:20:in `wkhtmltopdf'
  pdfkit (0.5.3) lib/pdfkit/pdfkit.rb:31:in `initialize'
  pdfkit (0.5.3) lib/pdfkit/middleware.rb:21:in `new'
  pdfkit (0.5.3) lib/pdfkit/middleware.rb:21:in `call'
  warden (1.2.1) lib/warden/manager.rb:35:in `block in call'
  warden (1.2.1) lib/warden/manager.rb:34:in `catch'
  warden (1.2.1) lib/warden/manager.rb:34:in `call'
  actionpack (3.2.13) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'

下記を参考に直してみても、RuntimeError pdfkit (0.5.3) lib/pdfkit/pdfkit.rb:73:in `to_pdf’ というエラーが出る。

NoMethodError · Issue #82 · pdfkit/pdfkit

原因は2つあって、1つ目はApacheにBasic認証を設定していたこと。

2つ目は /usr/local/bin へ path を通すことで解決しました。

path を通す方法は下記のとおりです。

まず、 /usr/local/bin/ruby_wrapper に下記の内容を記載して保存します。

#!/bin/sh
export PATH="$PATH:/usr/local/bin" 
exec "/usr/local/bin/ruby" "$@"

次に、Apache の httpd.conf で Passenger で使う Ruby の Path を ruby_wrapper に変更します。

PassengerRuby /usr/local/bin/ruby_wrapper

以上です。

[Ruby on Rails] ActionDispatch::Cookies::CookieOverflow error

Ruby on Rails で flash に大量の文字列を詰め込むと ActionDispatch::Cookies::CookieOverflow error が発生しました。

Raised when storing more than 4K of session data.

ActionDispatch::Cookies::CookieOverflow

解決方法は、セッションを Cookie ではなく ActiveRecord や Redis などで置き換えることです。

Ruby on Rails ActionDispatch::Cookies::CookieOverflow error – WILT

[Ruby on Rails][Haml] text mail 内で改行するにはバックスラッシュを使う

Ruby on Rails + Haml で、text mail 内で改行するには、バックスラッシュを使います。

Dear
= @user.name,
\
Your username is
= @user.username
\
\
\
\
Your status is
= @user.status

[参考]:HAML: Line breaks in text mail

[Ruby on Rails] Action Mailer でのメール送信処理

Ruby on Rails の Action Mailer でのメール送信処理をする方法をメモ。

主にこのへんを読む。

Action Mailer Basics — Ruby on Rails Guides

Rails 3 の Action Mailerまとめ – おもしろWEBサービス開発日記

ActionMailer Railsアプリからメールを送信 – 酒と泪とRubyとRailsと

Action Mailer

Gmail で送信する設定方法

config/environments/production.rb に下記のような感じで設定する。

MyApp::Application.configure do
  # Mailer
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
 
  config.action_mailer.smtp_settings = {
    address: "smtp.gmail.com",
    port: 587,
    domain: 'example.com',
    user_name: "gmail_user",
    password: "gmail_pass",
    authentication: 'plain',
    enable_starttls_auto: true,
  }
end

[参考]

Rails 3.0 でメールの送信に Gmail を使う – LazyLoadLife

railsでgmailをメールクライアントとして設定する | simpleplay's Log

[Ruby on Rails] ActionMailer views で helper メソッドを使う方法

Ruby on Rails の ActionMailer views で helper メソッドを使う方法をメモ。

例えば、app/views/contact_mailer/inquiry.text.haml で ApplicationHelper に定義したメソッドを使いたい場合は、下記のように add_template_helper メソッドを使います。

class ContactMailer < ActionMailer::Base
  add_template_helper(ApplicationHelper)
 
  def inquiry(contact)
  end
end

[参考]:ruby on rails – How to use my view helpers in my ActionMailer views? – Stack Overflow

[Ruby on Rails] RSpec でのファイルアップロードの方法

Ruby on Rails + RSpec でのファイルアップロードするためのメソッドをメモ。

fixture_file_upload
Rack::Test::UploadedFile.new
ActionController::TestUploadedFile.new
ActionDispatch::Http::UploadedFile.new

[参考]:ruby – How do I test a file upload in rails? – Stack Overflow はてなブックマーク - ruby - How do I test a file upload in rails? - Stack Overflow

[Ruby on Rails] Boolean型の presence validation

Ruby on Rails で、Boolean型の presence validation は false が invalid になってしまう。

なので、

validates :possible, presence: true

presence を指定するのではなく、

validates :possible, inclusion: {in: [true, false]}

というように inclusion で true, false の2値のみに限定してあげれば良い。

[参考]:validation – Rails: how do I validate that something is a boolean? – Stack Overflow はてなブックマーク - validation - Rails: how do I validate that something is a boolean? - Stack Overflow

[Ruby on Rails] 日付・時刻のバリデーションなら「ValidatesTimeliness」

Ruby on Rails で、日付・時刻のバリデーションをするなら ValidatesTimeliness という gem がおすすめです。

ActiveRecord だけでなく Mongoid でも使えるみたい。

adzap/validates_timeliness · GitHub はてなブックマーク - adzap/validates_timeliness · GitHub

validates_timeliness gem をインストール後、日本語のエラーメッセージを最低限、設定します。

# config/locales/model.ja.yml
ja:
  activerecord:
    errors:
      messages:
        invalid_date: は正しい形式で入力してください。
        invalid_time: は正しい形式で入力してください。
        invalid_datetime: は正しい形式で入力してください。

基本的な設定はこれだけで、あとはモデルに validates_datetime とかでバリデーションを設定できます。

# app/models/article.rb
class Article < ActiveRecord::Base
  validates_datetime :published_at
  validates_date :published_date
  validates_time :published_time
end

日付や時刻のバリデーションフォーマットがデフォルトのものだけでは、足りない場合は、独自定義したフォーマットを追加することもできます。

Plugin Parser を config.use_plugin_parser = true でONにして、config.parser.add_formats で追加するだけです。

# config/initializers/validates_timeliness.rb
ValidatesTimeliness.setup do |config|
 
  config.use_plugin_parser = true
  config.parser.add_formats(:time, "%H:%M")
 
end

上記は、Time に「01:23」みたいなフォーマットも許可する設定です。

もっと詳しい情報はWikiを見てください。

Plugin Parser · adzap/validates_timeliness Wiki はてなブックマーク - Plugin Parser · adzap/validates_timeliness Wiki

ValidatesTimeliness は、Date/time parser に timeliness を使ってるので、デフォルトのフォーマットは timeliness のページから確認できます。

timeliness/README.rdoc at master · adzap/timeliness · GitHub はてなブックマーク - timeliness/README.rdoc at master · adzap/timeliness · GitHub

ValidatesTimeliness 便利ですね。

日付や時刻のフォーマットって普遍だと思うので、Railsにデフォルトで搭載されていても良さそうなのに何でないんでしょうね?