Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

ActiveSupport | Object#with_options

概要

Object#with_options

詳細

Object#with_optionsについて

Object#with_options

オプションを受け取るメソッドに対して、一部のオプションは固定・一部のオプションは可変、
のような場合に固定部を繰り返し記述しない済む。
詳しくはサンプルを参照

サンプル

# encoding: utf-8
require "active_support/concern"
require "active_support/core_ext/object/with_options"

module HogeHigeHageable
  extend ActiveSupport::Concern

  module ClassMethods
    def hogehigehage(options = {})
      puts "#{options[:hoge]}|#{options[:hige]}|#{options[:hage]}"
    end
  end
end

class UserHogeHigeHage
  include HogeHigeHageable
  with_options hige: 'hige', hage: 'hage' do |a|
    a.hogehigehage hoge: 'hoge1'
    a.hogehigehage hoge: 'hoge2'
    a.hogehigehage hoge: 'hoge3'
  end
end

※with_optionsを利用しなかった場合は下記のように冗長な記述になる

class UserHogeHigeHage
  include HogeHigeHageable
  hogehigehage hoge: 'hoge1', hige: 'hige', hage: 'hage'
  hogehigehage hoge: 'hoge2', hige: 'hige', hage: 'hage'
  hogehigehage hoge: 'hoge3', hige: 'hige', hage: 'hage'
end

出力

hoge1|hige|hage
hoge2|hige|hage
hoge3|hige|hage