Skip to content

Instantly share code, notes, and snippets.

@nagait84
Created December 11, 2020 01:59
Show Gist options
  • Save nagait84/ca349389ed006f2f20010157bf511cab to your computer and use it in GitHub Desktop.
Save nagait84/ca349389ed006f2f20010157bf511cab to your computer and use it in GitHub Desktop.
【Rails】ハッシュに破壊的メソッドを追加したクラスを定義
# ハッシュを拡張して破壊的メソッドを追加したクラスを定義
class HashWithDestructiveMethods < Hash
class << self
def [](*args)
new.merge!(Hash[*args])
end
end
alias_method :regular_writer, :[]= unless method_defined?(:regular_writer)
def initialize(constructor = {})
super()
constructor.each_pair do |k, v|
regular_writer(k, v)
end
end
# @!group Destructive methods
# FIXME: ここにほしい変換メソッドをいっぱい追加する
# ハッシュの値を整数型(Integer)に変換
def to_i!(key)
self[key] = self[key].to_i
end
# ハッシュの値を日付型(Date)に変換
def to_date!(key)
self[key] = self[key].to_date
end
# ハッシュの値を日時型(Datetime)に変換
def to_datetime!(key)
self[key] = self[key].to_datetime
end
# @!endgroup
# ハッシュクラスに変換
# @return [Hash]
def to_hash
new_hash = {}
each do |key, value|
new_hash[key] = value
end
new_hash
end
end
@nagait84
Copy link
Author

Usage

hash_with_d = HashWithDestructiveMethods.new(aaa: '1', bbb: '2', ccc: '3')
# => { aaa: '1', bbb: '2', ccc: '3' }

hash_with_d.to_i!(:aaa)
hash_with_d.to_i!(:ccc)
hash_with_d
# => { aaa: 1, bbb: '2', ccc: 3 }

hash_with_d.to_hash
# => { aaa: 1, bbb: '2', ccc: 3 }
hash_with_d.to_hash.class
# => Hash

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment