1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

RubyでValueObjectを作るベストなやり方を考えてみた

Posted at

結論

以下のようにするのがベストではないかと思ってますが、もっと良いやり方あったらコメントください。

module ValueObjectable
  def initialize(args)
    super(args)
    freeze
  end
end

class Location < Struct.new(:country, :city, keyword_init: true)
  include ValueObjectable
end

## 特徴 ##
# 1. OpenStructのように Hash で初期化できる
tokyo = Location.new(country: 'Japan', city: 'Tokyo')
=> #<struct Location country="Japan", city="Tokyo">

# 2. 比較演算ロジックを自前で定義しないでいい
fukuoka = Location.new(country: 'Japan', city: 'Fukuoka')
tokyo == fukuoka
=> false

# 3. 値は不変
tokyo.country = 'U.S'
FrozenError: can't modify frozen Location
1
0
1

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?