Last active
August 29, 2015 14:02
-
-
Save robguilfoyle/bca820adbe001b0b642f to your computer and use it in GitHub Desktop.
Eventable Modules
This file contains hidden or 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