Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trying to dynamically create around_ callbacks in ActiveRecord
# A module for creating around callbacks in a model
module Piddle
module TimelineFor
def self.included(klass)
klass.send(:extend, ClassMethods)
end
module ClassMethods
def timeline_for(event, opts={})
method_name = :"timeline_for_#{event.to_s}"
define_method(method_name) do |&block|
Rails.logger.debug method_name.to_s
yield block
Rails.logger.debug "After yield in #{method_name.to_s}"
end
send(:around_update, method_name)
end
end
end
end
class User < ActiveRecord::Base
around_update :test_update
def test_update
Rails.logger.debug "test_update"
yield
Rails.logger.debug "Finished test_update"
end
end
u=User.last
u.name = 'something'
u.save
######### output (as expected):
# test_update
# Finished test_update
# second version of the User model using Piddle to create the callback
require 'piddle/piddle'
class User2 < ActiveRecord::Base
include Piddle::TimelineFor
timeline_for :update
end
u=User.last
u.name = 'gfgfhfhfgh'
u.save
########### output
timeline_for_update
LocalJumpError: no block given (yield)
from /vagrant/lib/piddle/piddle.rb:13:in `block in timeline_for'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment