public
Last active

Experiments with Module Includes in Ruby

  • Download Gist
include-experiments.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
# I created a generic Rails like ApplicationController so that you can just
# run this code via a command line prompt without the need for Rails
 
 
module Recorder
def self.included(base)
base.send(:before_filter, :some_method)
base.send(:after_filter, :another_method)
end
def initialize
super
#self references the instance of the UsersController class
@model_class = self.class
puts @model_class # UsersController
end
def some_method
puts 'from before filter method'
puts @model_class # UsersController
end
def another_method
puts 'from after filter method'
puts @model_class # UsersController
end
end
 
class ApplicationController
 
#stubbing out some stuff
@@before_filters = []
@@after_filters = []
def self.before_filter(method)
@@before_filters << method
end
def self.after_filter(method)
@@after_filters << method
end
def run(filter)
self.class.class_variable_get(('@@'+filter).intern).each do |method|
send(method)
end
end
include Recorder
end
 
class UsersController < ApplicationController; end
 
 
controller = UsersController.new
 
controller.run("before_filters")
 
controller.run("after_filters")

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.