Skip to content

Instantly share code, notes, and snippets.

@GriffinHeart
Last active October 15, 2015 06:23
Show Gist options
  • Save GriffinHeart/e18c1bc629023b800e16 to your computer and use it in GitHub Desktop.
Save GriffinHeart/e18c1bc629023b800e16 to your computer and use it in GitHub Desktop.
class User < ActiveRecord::Base
has_many :combo_instances
end
class ComboGame < ActiveRecord::Base
has_many :combo_instances
attr_reader :game_result
validates :hits_required, presence: true
validates :reward_points, presence: true
def play(user)
instance = combo_instances.where(user: user, game: self, status: :active).first
instance ||= ComboInstance.create(user: user, game: self, status: :active)
instance.play
end
def on_complete
@game_result = reward_points
end
end
class ComboInstance < ActiveRecord::Base
belongs_to :combo_game
belongs_to :user
enum status: [:active, :complete]
validates :hits, presence: true
validates :status, presence: true
after_save :check_complete
def play
hits += 1
if hits == combo_game.hits_required
status = :complete
save!
end
end
private
def check_complete
if status_changed? && status == :complete && status_was != :complete
# the combo_game loaded here from the relationship seems to be a different instance than the one who called play
combo_game.on_complete
end
end
end
u = User.new
game = ComboGame.create hits_required: 2, reward_points: 5
game.play(user)
game.game_result
# nil (expected)
game.play(user)
game.game_result
# nil (not expected should be 5 points)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment