Created
September 5, 2012 18:00
-
-
Save ideasasylum/3641379 to your computer and use it in GitHub Desktop.
Trying to dynamically create around_ callbacks in ActiveRecord
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
# 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 |
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 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 |
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
# 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