Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
require 'rubygems'
require 'dm-core'
DataMapper.setup(:default, "sqlite3:///#{Dir.pwd}/test.db")
module Eventable
def self.included(base)
base.class_eval do
after :create do
Event.create :comment => event_comment, :related => self
end
end
end
def events
Event.all(:related_id => self.id, :related_class => self.class.to_s)
end
end
class Project
include DataMapper::Resource
include Eventable
property :id, Serial
property :name, String
def event_comment
"Project created"
end
end
class Ticket
include DataMapper::Resource
include Eventable
property :id, Serial
property :title, String
def event_comment
"Ticket created"
end
end
class Event
include DataMapper::Resource
property :id, Serial
property :comment, String
property :related_id, Integer
property :related_class, String
def related=(object)
@related = object
self.related_id = @related.id
self.related_class = @related.class.to_s
end
def related
@related ||= Kernel.const_get(related_class).get(related_id)
end
def method_missing(method_name, *args, &block)
if method_name.to_s == self.related_class.downcase
return related
end
super
end
end
Project.auto_migrate!
Ticket.auto_migrate!
Event.auto_migrate!
@project1 = Project.create :name => 'Project 1'
@ticket1 = Ticket.create :title => 'Ticket 1'
puts @project1.inspect
# => #<Project id=1 name="Project 1">
puts @ticket1.inspect
# => #<Ticket id=1 title="Ticket 1">
puts Event.all.inspect
# => [#<Event id=1 comment="Project created" related_id=1 related_class="Project">, #<Event id=2 comment="Ticket created" related_id=1 related_class="Ticket">]
puts Event.get(1).related.inspect
# => #<Project id=1 name="Project 1">
puts Event.get(1).related.name.inspect
# => "Project 1"
puts Event.get(2).related.inspect
# => #<Ticket id=1 title="Ticket 1">
puts Event.get(2).related.title.inspect
# => "Ticket 1"
puts @project1.events.inspect
# => [#<Event id=1 comment="Project created" related_id=1 related_class="Project">]
puts @ticket1.events.inspect
# => [#<Event id=2 comment="Ticket created" related_id=1 related_class="Ticket">]
puts Event.get(1).project.inspect
# => #<Project id=1 name="Project 1">
Event.get(1).ticket
# => undefined method `ticket' for #<Event:0x111a2c8> (NoMethodError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment