Posts Tagged ruby

Ruby: how to override class method with a module

This seems to be a popular interview question. It indeed requires advanced knowledge of ruby.

You have a class with a class method. Write a module that, when included, will override that class method.

Explanation of the problem

Now classic way of mixing in class methods is this (and it doesn’t solve the problem, of course).

    module FooModule
      def self.included base
        base.extend ClassMethods
      end
 
      module ClassMethods
        def bar
          puts "module"
        end
      end
    end
 
    class Klass
      include FooModule
 
      def self.bar
        puts 'class'
      end
    end
 
 
    Klass.bar #=> class

When modules are included or extended into a class, its methods are placed right above this class’ methods in inheritance chain. This means that if we were to call super in that class method, it would print “module”. But we don’t want to touch original class definition, we want to alter it from outside.

So, can we do something?

Good for us, ruby has a concept of “open classes”. This means that we can change virtually everything in the app, even some 3rd-party libraries. Every class can “opened” and new methods can be added to it, or old methods can be redefined. Let’s look how it works. Read the rest of this entry »

Tags: ,

Advanced default parameters

Today I was quite amazed by one of Ruby features. It is about default values of method parameters. For example you can do something like this:

def get_current_actions(project_id, status_id = params[:status_id] || DEFAULT_STATUS_ID)    
    # implementation goes here
end

The code is saying basically this: “if status_id is not passed explicitly, try to take its value from params array. If it doesn’t contain specified key, then fall back to a constant”. This feature (as almost all the rest of Ruby magic) made avaiable by Ruby’s nature: it is interpreted language. This type of code is totally unusual to guys like me, who come from the world of static typing and compiled languages. But I think I’m gonna get used to it :-)

Tags: ,