Revisions

gist: 213765 Download_button fork
public
Public Clone URL: git://gist.github.com/213765.git
Embed All Files: show embed
Ruby #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# Summary:
# * We have a Debatable module that adds debate functionality to
# ActiveRecord.
# * Among other things, it makes the class belong to a proponent
# and opponent user.
# * There are 3 classes which are 'debatable'.
#
# The main issue is that a User doesn't have an association back to
# its debates, so nasty, nasty code is used to work around that
#
# I think that this approach was used because the 3 subclasses do have slightly different data associated with them. But, there isn't really any additional behavior aside from what Debatable provides.
#
# Goal:
#
# I'd like to be able to do code like this:
#
# user.debates.in_open_state (where debates is an association and in_open_state is some named_scope)
#
# Considerations:
# * This code is live in production, so there needs to be some way to
# go from this point to some saner point
# * I did not write this code
 
module Debatable # not a great name, but ads debate functionality
  # snip
  def ClassMethods
    def acts_as_debatable
      # snip
      belongs_to :opponent, :class_name => 'User'
      belongs_to :winner, :class_name => 'User'
    end
  end
end
 
class Claim < ActiveRecord::Base
  acts_as_debatable
end
 
class Game < ActiveRecord::Base
  acts_as_debatable
end
 
class Fantasy < ActiveRecord::Base
  acts_as_debatable
end
 
 
class User
  # no actual association to the debatables
 
  def open_debates
    # AIEEEEEEE
    [Claim, Game, Fantasy].inject([]) do |all_debates, debate_type|
      debates = debate_type.find(:all, :conditions => ['(opponent_id = ? OR user_id = ?) AND state IN (?)', id, id, Debatable::CREATED_STATES])
 
      all_debates + debates
    end
  end
 
end