Skip to content

Instantly share code, notes, and snippets.

@themusicman
Created July 5, 2012 23:35
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save themusicman/3057139 to your computer and use it in GitHub Desktop.
Save themusicman/3057139 to your computer and use it in GitHub Desktop.
Experiments with Module Includes in Ruby
# 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")
@grillermo
Copy link

The stubbing thingies shades the purpose of this class, to teach how to include, is not newbie friendly :(
I would sacrifice the ability to run via command line prompt for the sake of clarity.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment