Skip to content

Instantly share code, notes, and snippets.

@reagent
Created November 3, 2011 21:17
Show Gist options
  • Save reagent/1337804 to your computer and use it in GitHub Desktop.
Save reagent/1337804 to your computer and use it in GitHub Desktop.
Alternate ways of implementing lifecyle hooks that don't involve observers
class Activity < ActiveRecord::Base
# columns:
# * entity_id
# * entity_type
# * action
# * created_at
belongs_to :entity, :polymorphic => true
end
class User
has_many :activities, :as => :entity
after_save :log_activity
private
def log_activity
activities.create(:action => 'create')
end
end
class Post
has_many :activities, :as => :entity
private
def log_activity
activities.create(:action => 'create')
end
end
class Activity < ActiveRecord::Base
# columns:
# * entity_id
# * entity_type
# * action
# * created_at
belongs_to :entity, :polymorphic => true
end
class User
has_many :activities, :as => :entity
end
class Post
has_many :activities, :as => :entity
end
class LoggableObserver < ActiveRecord::Observer
observe :user, :post
def after_save(loggable)
loggable.activities.create(:action => 'create')
end
end
module Loggable
extend ActiveSupport::Concern
included do
after_save :log_activity
end
private
def log_activity
activities.create(:action => 'create')
end
end
class Activity < ActiveRecord::Base
# columns:
# * entity_id
# * entity_type
# * action
# * created_at
belongs_to :entity, :polymorphic => true
end
class User
include Loggable
has_many :activities, :as => :entity
end
class Post
include Loggable
has_many :activities, :as => :entity
end
module Loggable
extend ActiveSupport::Concern
included do
after_save :log_activity
has_many :activities, :as => :entity
end
private
def log_activity
activities.create(:action => 'create')
end
end
class Activity < ActiveRecord::Base
# columns:
# * entity_id
# * entity_type
# * action
# * created_at
belongs_to :entity, :polymorphic => true
end
class User
include Loggable
end
class Post
include Loggable
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment