Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kivanio/bf2c4de04e9e734a73f4 to your computer and use it in GitHub Desktop.
Save kivanio/bf2c4de04e9e734a73f4 to your computer and use it in GitHub Desktop.
# event.rb
class Event < ActiveRecord::Base
belongs_to :eventable, polymorphic: true
end
# migration
class CreateEvents < ActiveRecord::Migration
def change
create_table :events do |t|
t.string :event_type
t.integer :eventable_id
t.string :eventable_type
t.hstore :metadata
t.timestamps
end
end
end
# eventable.rb
require 'active_support/concern'
module Eventable
extend ActiveSupport::Concern
EVENT_TYPES = [:accepted, :denied]
included do
has_many :events, as: :eventable
attr_accessor :metadata
end
def create_event(type)
Event.create(eventable: self, event_type: type, metadata: self.metadata)
end
# create dynamic methods based on the event types of the model
#
EVENT_TYPES.each do |event_type|
define_method "create_#{event_type}_event" do |args={}|
unless Hash(args).empty?
if self.metadata.nil?
self.metadata = args
else
self.metadata.merge(args)
end
end
Event.create(eventable: self, event_type: event_type, metadata: self.metadata)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment