Ruby refactoring fun

I my last post I’ve said that I don’t care if code for method_missing implementation is ugly. Well I’ve lied.
This is starting point

def method_missing(method, *params)
     method = method.to_s
     type = :get
     if (method.index('store_').nil? == false) #if you have name conflict use store_ prefix,
                                                             #or rename hash key or class method
         method.gsub!('store_','')
     elsif (method.index('exists_').nil? == false)
         method = method.gsub!('exsists_','')
         type = :check_if_exists
     elsif (method.index('set_').nil? == false && params.count == 1)
         method = method.gsub!('set_','')
         type = :set
     end
     method = method.to_sym
     if type == :get
         return @store[method] if @store.keys.collect(&:to_sym).include?(method)
     elsif type == :check_if_exists
        return @store.keys.collect(&:to_sym).include?(method)
     else
        return @store[method] = params[0]
     end
     return nil  # return nil if key does not exist
  end


If you want to see what kid of result did I get read on

  def method_missing(method, *params)
     command = Command.new(method, { :store => :get, :exists => :check_if_exists,  :set => :set },
 :get )
     case command.name
       when :get then
          return @store[command.method] if @store.keys.collect(&:to_sym).include?(command.method)
       when :check_if_exists then
          return @store.keys.collect(&:to_sym).include?(command.method)
       when :set then
          @store[command.method] = params[0]
       else return nil
     end
  end 

All this is possible with the help of brand-new-and-shiny Command class

class Command 

attr_reader :name
attr_reader :method

def initialize(method, command_map, default_value = nil)
  @name = default_value
  @method = method
  parse(command_map)
end

private

def parse(command_map)
    method = @method.to_s
    command_map.each_pair do |key, value|
       parse_string = "#{key}_"
       if method.index(parse_string).nil? == false
         @name = value.to_sym
         @method = method.gsub(parse_string,'').to_sym
         break
       end
    end
end
end


To be honest, my real life code was a bit more brutal, so Command class really payed of there.
I really like how much Ruby is NOT getting in my way. Language is really elegant and has much more appeal to me that ROR itself. (ROR drew me to the Ruby, just like Compiz drew me to the Ubuntu, and than Ubuntu to Linux, and then Linux to Arch :) )

blog comments powered by Disqus