Ruby I learned today.

Published on Nov 12, 2010

I am new to ruby . Here is something i feel cool that i learnt today , You can mix in instance methods and class methods by include and extend respectively .

In rails i put a file my_module.rb in my lib directory

Inside which i wrote my module

module MyModule
def foo
puts "bar"
end
end

Rails auto loads the lib folder so you can include MyModule in your ,hmm say , model

Class MyModel << ActiveRecord::Base
include MyModule
...
...

This would add an instance method foo (which is from the module) to your Model. So you can do

>> mm = MyModel.new
>> mm.foo bar

Now if you needed MyModel.foo , ie a class method , you would extend your model.

Class MyModel << ActiveRecord::Base
extends MyModule
...
...
>>MyModel.foo
bar

You can override methods of your class , from a module like this .Which , say for example , lets you monkeypatch active record methods say , which you are not supposed to do though . >: ) (Why ? probably because it will be lot of laugh when your co developer finally realises his bug was because he did not know you overriding the method)