5
6

More than 5 years have passed since last update.

Rails3.2からRails4系に上げる際にin?でハマるよ

Last updated at Posted at 2015-03-04

ActiveSupportについてるObject#in?メソッド
Object#include?の逆をやってくれる便利なメソッドなんだが, Railsを4にあげて実行するとエラーになるから書き換えなきゃいけない

※Rails4.2に付随するActiveSupportでチェックしている、Rails4.0ではチェックしていない

#includeの例
[1, 2, 3].include?(2) => true

# Rails3.2まではこちら通る
2.in?(1, 2, 3) => true 

#Rails4以降はこちら, Rails3.2でもこのコードで通る
2.in?([1, 2, 3]) => true 

in?の使用箇所のソースコード

active supportのin?メソッドの引数が、*を使った引数の数を指定しない形から, 配列に変更になった

変更前

 def in?(*args)
    if args.length > 1
      args.include? self
    else
      another_object = args.first
      if another_object.respond_to? :include?
        another_object.include? self
      else
        raise ArgumentError.new("The single parameter passed to #in? must respond to #include?")
      end
    end
  end

変更後

  def in?(another_object)
    another_object.include?(self)
  rescue NoMethodError
    raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
  end
5
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6