Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【意見求む】ActiveRecordモデルでのdelegateの積極利用について #84

Open
ohta-rh opened this issue Apr 1, 2014 · 0 comments
Labels

Comments

@ohta-rh
Copy link
Contributor

ohta-rh commented Apr 1, 2014

csv出力とか、1画面内での情報が多い場合は
delegateを多用すると楽かもしれません

# 例えばこのようなクラスが3つあるとします。
# それぞれ「name」属性をもっていると仮定します。

class Hoge < AR::Base
  has_many :piyo

  def full_name
    %(full #{name})
  end
end

class Piyo < AR::Base
  has_one :foo
  belongs_to :hoge
end

class Foo < AR::Base
   belongs_to :piyo
end

# Piyoの内容をカンマ区切りで標準出力に表示するという要件がでてきました。
# ただし、hogeとfooの内容を同時にだしてくれとのことでした。しかもhogeの場合はfull_nameで表示してくれと...

# delegateしない例
Piyo.includes(:hoge, :foo).each do |piyo|
  print %(#{piyo.hoge.full_name}, #{piyo.foo.name})
end

# delegateする例

# Piyoを以下に書き換えます
class Piyo < AR::Base
  belongs_to :hoge
  has_one :foo

  delegate :full_name, to: :hoge, prefix: true
  delegate :name, to: :foo, prefix: true
end

# delegateして呼び出します。
Piyo.includes(:hoge, :foo).each do |piyo|
   print %(#{piyo.hoge_full_name},#{piyo.foo_name})
end

メリットとしては親子関係にあるクラスから直接属性や、メソッドコールが可能なため
依存関係のあるオブジェクトに処理を委譲することができます。

つかいどころはむずかしいですが。。なんかいい案があれば。。

@ohta-rh ohta-rh added the Rails label Apr 1, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant