データ値が整形や値の抽出などで特別な振る舞いが増えてきた場合はデータ値をオブジェクトにするのが良い

 1 class Order
 2   def initialize(customer)
 3      @customer  = customer
 4   end
 5 
 6   def customer_full_name
 7     @customer
 8   end
 9 
10   def customer_first_name
11     @customer.split(" ").first
12   end
13 
14   def customer_family_name
15     @customer.split(" ").last
16   end
17 end

Orderクラスに属性(customer)を操作する処理が復数定義されている

 1 class Order
 2   def initialize(customer_name)
 3      @customer  = Customer.new(customer_name)
 4   end
 5 
 6   def customer
 7     @customer
 8   end
 9 
10   def customer=(name)
11     @customer = Customer.new(name)
12   end
13 end
14 
15 class Customer
16   def initialize(name)
17     @name = name
18   end
19 
20   def name
21     @name
22   end
23 
24   def first_name
25     @name.split(" ").first
26   end
27 
28   def family_name
29     @name.split(" ").last
30   end
31 end

属性をクラスに昇格されて、操作メソッドをクラス内で定義する




comments powered by Disqus


© 2015 kyuden