Last active
March 18, 2022 12:30
-
-
Save javierav/11365c7437e8ec71a6a6c143fd9e6bd5 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
class ActionBase | |
def self.call(*params) | |
new(*params).call | |
end | |
def self.on(event, *methods) | |
methods.each { |m| __on_listeners[event.to_sym] << m.to_sym } | |
end | |
def self.__on_listeners | |
@__on_listeners ||= Hash.new { |hash, key| hash[key] = [] } | |
end | |
def self.call_event(options={}) | |
options.reverse_merge!( | |
on: :success, | |
actor: :actor, | |
resource: :resource, | |
target: :target, | |
context: :context, | |
klass: "#{name}Event" | |
) | |
@__call_events ||= 0 | |
define_method("__call_event_#{@__call_events}") do | |
options[:klass].safe_constantize.call(options.slice(:actor, :resource, :target, :context)) | |
end | |
on options[:on], "__call_event_#{@__call_events}" | |
end | |
private | |
def publish(event) | |
self.class.__on_listeners[event.to_sym].each { |m| send(m) } | |
end | |
def create(parent, attributes, ivar=nil) | |
parent.create(attributes).tap do |object| | |
instance_variable_set("@#{ivar}", object) if ivar.present? | |
if object.persisted? | |
yield object if block_given? | |
publish :success | |
else | |
publish :failure | |
end | |
end | |
end | |
def update(object, attributes) | |
object.tap do | |
if object.update(attributes) | |
yield object if block_given? | |
publish :success | |
else | |
publish :failure | |
end | |
end | |
end | |
def destroy(object) | |
object.tap do | |
if object.destroy | |
yield object if block_given? | |
publish :success | |
else | |
publish :failure | |
end | |
end | |
end | |
end |
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
class Example < ActionBase | |
call_event on: :success, actor: :current_user, resource: :user, target: -> { @user.parent }, context: nil, klass: 'ExampleEvent' | |
on :success, :print_info | |
def initialize(user, attributes, current_user) | |
@user = user | |
@attributes = attributes | |
@current_user = current_user | |
end | |
def call | |
update(@user, @attributes) | |
end | |
private | |
def print_info | |
puts "Success" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment