RubyのActiveSupportを使った便利なユーティリティ集
ActiveSupportはRuby on Railsのコア部分であり、多くの便利なユーティリティを提供します。日常のRubyプログラミングを劇的に効率化するActiveSupportの機能を活用します。
目次
ActiveSupportとは何か
ActiveSupportはRuby on Railsの補助ライブラリで、Rubyの標準ライブラリを拡張する多くのメソッドやユーティリティを提供します。
Stringクラスの拡張
ActiveSupportはStringクラスに多くの便利なメソッドを追加します。
require 'active_support/core_ext/string'
puts "hello_world".camelize # => "HelloWorld"
puts "HelloWorld".underscore # => "hello_world"
puts "hello world".titleize # => "Hello World"
puts "active_support".dasherize # => "active-support"時間操作の強力なメソッド
時間や日付を簡単に操作できるメソッドがActiveSupportに含まれています。
require 'active_support/core_ext/numeric/time'
puts 1.day.ago # 現在時刻から1日前
puts 2.weeks.from_now # 2週間後
puts 3.hours.since(Time.now) # 現在時刻から3時間後
puts 10.minutes.ago # 10分前Arrayクラスの拡張
配列操作に役立つメソッドがArrayクラスに追加されます。
require 'active_support/core_ext/array'
array = [1, 2, 3, 4, 5]
puts array.second # => 2
puts array.third # => 3
puts array.fourth # => 4
puts array.from(2) # => [3, 4, 5]
puts array.to(3) # => [1, 2, 3, 4]Hashクラスの強力なユーティリティ
ハッシュ操作をより効率的に行えるメソッドが用意されています。
require 'active_support/core_ext/hash'
hash = { a: 1, b: 2, c: 3 }
puts hash.slice(:a, :b) # => {:a=>1, :b=>2}
puts hash.except(:b) # => {:a=>1, :c=>3}
puts hash.stringify_keys # => {"a"=>1, "b"=>2, "c"=>3}
puts hash.symbolize_keys # => {:a=>1, :b=>2, :c=>3}Blank? と Present?
オブジェクトが空かどうかを判定する便利なメソッドです。
require 'active_support/core_ext/object/blank'
puts "".blank? # => true
puts "hello".present? # => true
puts nil.blank? # => true
puts [].blank? # => true
puts [1, 2, 3].present? # => trueActiveSupport::Concernでモジュールを整理
モジュールの作成や管理を簡単にするためにActiveSupport::Concernが利用できます。
require 'active_support/concern'
module MyModule
extend ActiveSupport::Concern
included do
def greet
"Hello, ActiveSupport!"
end
end
end
class MyClass
include MyModule
end
puts MyClass.new.greet # => "Hello, ActiveSupport!"時間帯(TimeZone)のサポート
ActiveSupportは時間帯の操作や管理をサポートしています。
require 'active_support/time'
time = Time.current
puts time # 現在時刻
puts time.in_time_zone("Tokyo") # 東京の時刻
puts Time.zone = "UTC"
puts Time.current # UTCの現在時刻デリゲートを簡単にするdelegateメソッド
メソッド呼び出しを他のオブジェクトに委譲する際に便利です。
require 'active_support/core_ext/module/delegation'
class User
attr_accessor :profile
def initialize
@profile = Profile.new
end
delegate :name, to: :profile
end
class Profile
def name
"John Doe"
end
end
user = User.new
puts user.name # => "John Doe"Enumerableのsumメソッド
配列の合計を簡単に計算するメソッドがActiveSupportに追加されています。
require 'active_support/core_ext/enumerable'
puts [1, 2, 3, 4].sum # => 10
puts [1.5, 2.5, 3.5].sum # => 7.5Stringのinquiryメソッド
Stringを疑似的なブール値オブジェクトとして扱えます。
require 'active_support/core_ext/string/inquiry'
status = "active".inquiry
puts status.active? # => true
puts status.inactive? # => falseコールバック管理
ActiveSupport::Callbacksを使用して、簡単にコールバックを設定できます。
require 'active_support/callbacks'
class Sample
include ActiveSupport::Callbacks
define_callbacks :process
set_callback :process, :before, -> { puts "Before process" }
set_callback :process, :after, -> { puts "After process" }
def run
run_callbacks :process do
puts "Running process"
end
end
end
Sample.new.run
# 出力:
# Before process
# Running process
# After processSafe Navigation Operator
メソッドチェーン中に`nil`が発生してもエラーを回避します。
require 'active_support/core_ext/object/try'
hash = { user: { name: "Alice" } }
puts hash.dig(:user, :name) # => "Alice"
puts hash.dig(:user, :age) # => nil
puts hash[:user].try(:[], :name) # => "Alice"まとめ
ActiveSupportを利用することで、日常的なRubyコードがよりシンプルで効率的になります。クラスの拡張や時間操作、便利なユーティリティメソッドを積極的に活用していきましょう。
-
前の記事
Google スライド スライドショーを開くショートカットキー 2025.01.10
-
次の記事
ReactのError Boundaryを使ったエラーハンドリング 2025.01.11
コメントを書く