Skip to content

@themusicman /include-experiments.rb
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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

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
Something went wrong with that request. Please try again.