23
22

More than 5 years have passed since last update.

Rails5 で追加されてる active_support/core_ext のメソッドを眺めてみた

Last updated at Posted at 2015-12-28

ActionCable とか、RailsAPI とか、そこらへんの目玉はいろんな人が紹介してくれていますが、
ActiveSupport の core_ext で Rails 5 から追加されたメソッドを調べてみました。
rails のリポジトリを clone してきて、以下のコマンドでみているので、Rails 5 beta に含まれていないものもあるかもしれません。

git diff origin/4-2-stable origin/master activesupport/lib/active_support/core_ext

Array#without

Enumerable#without というのもあって、それの Array 版。
reject に近いですが、reject よりも速いみたいです。

users = ['yamada', 'tanaka', 'sato']
#=> ["yamada", "tanaka", "sato"]
users.without('yamada')
#=> ["tanaka", "sato"]

Array#inquiry

配列のインスタンスに #inquiry? とすると、#any? と、String#inquiry みたいに hoge? な感じのことを Array でも使えるようになります。

users = ['yamada', 'tanaka', 'sato'].inquiry
#=> ["yamada", "tanaka", "sato"]
users.any?('sato')
#=> true
users.any?('sato', 'suzuki')
#=> true
users.any?('suzuki', 'kimura')
#=> false

users.tanaka?
#=> true
users.suzuki?
#=> false

Numeric#positive?, negative?

数字が正数か負数かを判断するメソッドです。

number = -1
number.negative?
#=> true

number = 1
number.positive?
#=> true

Enumerable#pluck

AR の pluck を Enumerable でも使えるようになります。

users = [{name: 'yamada'}, {name: 'tanaka'}, {name: 'sato'}]
#=> [{:name=>"yamada"}, {:name=>"tanaka"}, {:name=>"sato"}]
users.pluck(:name)
#=> ["yamada", "tanaka", "sato"]

Date#prev_day, next_day

yesterday, tommorow と同じ。

time = Time.new
#=> 2015-12-29 17:00:22 +0900
time.next_day
#=> 2015-12-30 17:00:22 +0900
time.prev_day
#=> 2015-12-28 17:00:22 +0900

Date(Time)#next_weekday, prev_weekday, on_weekend?

次の平日とか、前の平日とか、週末かどうかとかが取れるようになりました。

Time#days_in_year

指定した年が何日あるかが取れるようになりました。

Time.days_in_year(2016)
#=> 366

# 指定しない場合は current.year になる
Time.days_in_year
#=> 365

thread_mattr_reader, thread_mattr_writer, thread_mattr_accessor

Changelog にサンプルが載っていましたが、Thread に属性を設定できるようになるようです。
以下、Changelog のサンプル

module Current
  thread_mattr_accessor :account
  thread_mattr_accessor :user

  def self.reset()
    self.account = self.user = nil 
  end
end

class ApplicationController < ApplicationRecord
  before_action :set_current 
  after_action { Current.reset }

  private

  def set_current 
    Current.account = Account.find(params[:account_id]) 
    Current.user = Current.account.users.find(params[:user_id])
  end
end

class MessagesController < ApplicationController 
  def create 
    @message = Message.create!(message_params)
  end
end

class Message < ActiveRecord::Base
  has_many :events 
  after_create :track_created

  private 

  def track_created 
    events.create! origin: self, action: :create
  end
end

class Event < ApplicationRecord
  belongs_to :creator, class_name: 'User' 
  before_validation { self.creator ||= Current.user }
end

参考

23
22
0

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
23
22