← back

Ruby I learned today.

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
  ...
end

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
  extend MyModule
  ...
end

>> 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 — 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 were overriding the method)