lib/stance/event.rb in stance-0.7.1 vs lib/stance/event.rb in stance-0.8.0
- old
+ new
@@ -3,14 +3,12 @@
module Stance
class Event
include ActiveSupport::Callbacks
define_callbacks :create
- attr_reader :record, :options
+ attr_reader :record, :options, :name
- delegate :subject, :name, to: :record
-
class << self
def before_create(*methods, &block)
set_callback :create, :before, *methods, &block
end
@@ -18,18 +16,26 @@
set_callback :create, :after, *methods, &block
end
end
def initialize(name, subject, metadata, options)
+ @subject = subject
+ @name = name
+ @metadata = metadata
@options = { singleton: false, record: true, class: false }.merge(options)
attrs = { name: name, metadata: metadata }
- if subject.is_a?(String)
- attrs[:subject_type] = subject
- else
+ if subject.is_a?(ActiveRecord::Base)
attrs[:subject] = subject
+ elsif subject.is_a?(Class) && subject < ActiveRecord::Base
+ attrs[:subject_type] = subject.name
+ else
+ @options[:record] = false
end
+
+ return unless @options[:record]
+
@record = Stance::EventRecord.new(attrs)
end
def create
return self if singleton_exists?
@@ -38,26 +44,32 @@
run_callbacks :create do
# Call each public method of the Event class if a custom class.
if self.class.name != 'Stance::Event'
Rails.logger.info "Event: #{full_name}"
- (public_methods(false) - Stance::Event.instance_methods(false)).each do |method|
- send method
- end
+ callback_methods.each { |method| send method }
end
record.save if @options[:record]
end
end
self
end
def full_name
- "#{record.subject_type.downcase}.#{name}"
+ "#{subject.class.name.downcase}.#{name}"
end
+ def subject
+ try(:record)&.subject || @subject
+ end
+
private
+
+ def callback_methods
+ public_methods(false) - Stance::Event.instance_methods(false)
+ end
# Event is a singleton and already exists.
def singleton_exists?
options[:singleton] && subject.events.active.exists?(name: name)
end