Archive for category Uncategorized

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: ,

Mongoid, db.system.namespaces queries

Recently I faced some issues with Mongoid when upgrading my Rails app from REE+Passenger to MRI 1.9.3+Unicorn.

There are some Resque workers in the background. After some deploy they started to consume a ton of traffic from MongoDB. After some investigation, I found that they heavily read system.namespaces collection. I tried upgrading to latest versions of mongoid(2.4.3) and mongo(1.5.2) to no avail. This does not happen with normal unicorn workers. This also does not happen if I downgrade mongoid to 2.0.1.

I am still not sure what’s happening here. I’ll update this post when I discover something.

Tags: ,

How to quickly lock screen in Mac OS X?

I am tired of googling the same information over and over, so I am posting it here.

To quickly lock your screen, press Ctrl+Shift+Eject.

Also, you can press Fn+Ctrl+Eject to quickly restart your Mac, shut it down or put to sleep.

Email validation done right

Let’s imagine that you have to check if a string is a valid email. You could come up with something like:

    /[a-zA-Z0-9\.]+@[a-z]+\.[a-z]+/

It works, right? WRONG. Sure it’ll handle a couple of your test examples. But it’s not ready for real world usage. Here’s a standards compliant Perl regex.

/(?(DEFINE)
   (?<address>         (?&mailbox) | (?&group))
   (?<mailbox>         (?&name_addr) | (?&addr_spec))
   (?<name_addr>       (?&display_name)? (?&angle_addr))
   (?<angle_addr>      (?&CFWS)? < (?&addr_spec) > (?&CFWS)?)
   (?<group>           (?&display_name) : (?:(?&mailbox_list) | (?&CFWS))? ;
                                          (?&CFWS)?)
   (?<display_name>    (?&phrase))
   (?<mailbox_list>    (?&mailbox) (?: , (?&mailbox))*)
 
   (?<addr_spec>       (?&local_part) \@ (?&domain))
   (?<local_part>      (?&dot_atom) | (?&quoted_string))
   (?<domain>          (?&dot_atom) | (?&domain_literal))
   (?<domain_literal>  (?&CFWS)? \[ (?: (?&FWS)? (?&dcontent))* (?&FWS)?
                                 \] (?&CFWS)?)
   (?<dcontent>        (?&dtext) | (?&quoted_pair))
   (?<dtext>           (?&NO_WS_CTL) | [\x21-\x5a\x5e-\x7e])
 
   (?<atext>           (?&ALPHA) | (?&DIGIT) | [!#\$%&'*+-/=?^_`{|}~])
   (?<atom>            (?&CFWS)? (?&atext)+ (?&CFWS)?)
   (?<dot_atom>        (?&CFWS)? (?&dot_atom_text) (?&CFWS)?)
   (?<dot_atom_text>   (?&atext)+ (?: \. (?&atext)+)*)
 
   (?<text>            [\x01-\x09\x0b\x0c\x0e-\x7f])
   (?<quoted_pair>     \\ (?&text))
 
   (?<qtext>           (?&NO_WS_CTL) | [\x21\x23-\x5b\x5d-\x7e])
   (?<qcontent>        (?&qtext) | (?&quoted_pair))
   (?<quoted_string>   (?&CFWS)? (?&DQUOTE) (?:(?&FWS)? (?&qcontent))*
                        (?&FWS)? (?&DQUOTE) (?&CFWS)?)
 
   (?<word>            (?&atom) | (?&quoted_string))
   (?<phrase>          (?&word)+)
 
   # Folding white space
   (?<FWS>             (?: (?&WSP)* (?&CRLF))? (?&WSP)+)
   (?<ctext>           (?&NO_WS_CTL) | [\x21-\x27\x2a-\x5b\x5d-\x7e])
   (?<ccontent>        (?&ctext) | (?&quoted_pair) | (?&comment))
   (?<comment>         \( (?: (?&FWS)? (?&ccontent))* (?&FWS)? \) )
   (?<CFWS>            (?: (?&FWS)? (?&comment))*
                       (?: (?:(?&FWS)? (?&comment)) | (?&FWS)))
 
   # No whitespace control
   (?<NO_WS_CTL>       [\x01-\x08\x0b\x0c\x0e-\x1f\x7f])
 
   (?<ALPHA>           [A-Za-z])
   (?<DIGIT>           [0-9])
   (?<CRLF>            \x0d \x0a)
   (?<DQUOTE>          ")
   (?<WSP>             [\x20\x09])
 )
 
 (?&address)/x

I couldn’t even imagine that the matter is *this* complex.

Funny side benefit :-)

There I was, minding my own business, trying to solve problems in graph theory and I accidentally made a Sudoku puzzle solver! Isn’t it funny how life turns out sometimes? But that’s just how awesome LINQ is.

Eric Lippert on LINQ

Tags:

Intuitive behaviour

Today I was looking at exception stack trace. One of suspicious places was ‘…\reports_controller.rb:129″. Okay, navigating to this location using RubyMine is a piece of cake. Ctrl+Shift+N to get to reports_controller.rb, then Ctrl+G to position caret at specified line. But hey, that’s two actions. I hit Ctrl+Shift+N, put ‘reports_controller.rb:129′ in and voila! It worked just as I expected!
RubyMine: +1 to intuitivity, +1 to overall impression.

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: ,

Iterations are good

Iterations in software development. Tried to implement proper solution on the first try? I bet you failed. It’s like in Google Earth zooming in your house from the planet view. To achieve your goal, you’ve got to advance a little bit, adjust your position, advance further… Iterate until done.

Tags: