-
-
Save kivanio/bf2c4de04e9e734a73f4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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