Skip to content

Instantly share code, notes, and snippets.

@Naggi-Goishi
Last active May 10, 2017 15:58
Show Gist options
  • Select an option

  • Save Naggi-Goishi/6ec20782b683e47fe4af1a1cfe58bdd4 to your computer and use it in GitHub Desktop.

Select an option

Save Naggi-Goishi/6ec20782b683e47fe4af1a1cfe58bdd4 to your computer and use it in GitHub Desktop.
ActiveRecord::Relationのオブジェクトに対してメソッドを追加したい時 ref: http://qiita.com/Naggi-Goishi/items/fa756eb3814847fdd05b
class BeatingFreeza
class << self
def possible?(collection)
new(collection).possible?
end
end
def initialize(collection)
@collection = collection
end
def possible?
collection.pluck(:power).any? { |power| power > Freezer.power } ||
collection.any? { |user| user.super_saiya? } ||
# ....... 以下戦闘力だけではなく、環境や頭の回転などを考慮するようになってくるとこのようにするのがいいでしょう。
# ドラゴンボールは戦闘力で決まってしまうので、ハンターハンターとかのときには、クラスを別途で作りましょう。
end
end
User.all
=> #<ActiveRecord::Relation [#<User id: 1, name: "カカロット", email: "ninjin@saiya.com", power: "130">, #<User id: 2, name: "ベジータ", email: "yasai@saiya.com", power: "75億"> ... 省略]>
class User
def self.can_beat_freezer?
# 便宜上、Freezer.power が 0.0053 (53万) を返すことにします。
# 上記のメンバーだとヘナチョコのボコボコのペチャペチャのギッタンギッタンですね
all.pluck(:power).any? { |power| power > Freezer.power }
end
end
class User < ActiveRecord::Base
def self.can_beat_freeza?
BeatingFreeza.possible?(all)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment