Created
July 5, 2012 23:35
-
-
Save themusicman/3057139 to your computer and use it in GitHub Desktop.
Experiments with Module Includes in Ruby
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
# 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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.