Ruby refactoring fun
Posted by Kresimir Bojcic on August 12, 2009
Comments
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 (more…)