Skip to content

Instantly share code, notes, and snippets.

@spp
Created October 26, 2009 07:48
Show Gist options
  • Save spp/218487 to your computer and use it in GitHub Desktop.
Save spp/218487 to your computer and use it in GitHub Desktop.
# Create a file my_modeule.rb
# Include it in your application load path (Standard: app/lib )
# FILE CONTENTS BEGIN HERE
module MyModule
def self.included(base)
base.extend ClassMethods
class << base
attr_accessor :class_variable
end
attr_accessor :instance_variable
end
module ClassMethods
# Options passed here will be overridden by those passed in the instance method
def i_am_a_class_method(options = {})
# Class variables available here
self.class_variable
end
end
module InstanceMethods
# By default these methods are not available.
# They are only added when we call the 'i_am_a_class_method' method.
def i_am_an_instance_method(options = {})
# All instance variables from class will be available here
"Whatever the output yo desire!"
end
private
def a_private_method
# Manipulate stuff here
end
end
end
# The most important line. Include it to ActiveRecord::Base, so that
# Its available to all models
ActiveRecord::Base.send :include, MyModule
# FILE CONTENTS END HERE
# How to use it:
class MyModel < ActiveRecord::Base
i_am_a_class_method :param_one => :something, :param_two => "something_else"
# This one line will add all the instance methods you wrote in your module.
end
# Now simply:
MyModel.new.i_am_an_instance_method
# Whatever the output you desire!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment