HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Using Dalli to connect to memcached

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
dallimemcachedconnectusing

Problem

I always seem to struggle refactoring my code. I can look at any other code and know exactly what is going on, but when it comes to cleaning up my code, I get writers block.

The following code works, but I know if can be done much nicer, and with few lines of code. I just wanted to wrap a memcache client to use one server for testing and another for dev/prod or just fetch the value if it cannot connect to the server.

Any tips on refactoring, etc. are much appreciated.

require 'dalli'
class Cache
    def self.fetch(key, ttl, &block)
        if memcache
            memcache.fetch(key, ttl, &block)
        else
            block.call
        end
    end

    def self.memcache
        begin
        if(ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development)
            @memcache ||= Dalli::Client.new('cache.amazonaws.com:11211')    
        else
            @memcache ||= Dalli::Client.new('localhost:11211')  
        end
        rescue Exception => e
            false
        end
    end
end

Solution

This DRY's the code in self.memcache and simply uses a ternary operator for self.fetch.

require 'dalli'
class Cache
  def self.fetch(key, ttl, &block)
    memcache ? memcache.fetch(key, ttl, &block) : block.call
  end

  def self.memcache
    @memcache ||= Dalli::Client.new((ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development) ?
                                    'cache.amazonaws.com:11211' :
                                    'localhost:11211')
  rescue Exception
    false
  end
end

Code Snippets

require 'dalli'
class Cache
  def self.fetch(key, ttl, &block)
    memcache ? memcache.fetch(key, ttl, &block) : block.call
  end

  def self.memcache
    @memcache ||= Dalli::Client.new((ENV['RACK_ENV'] == :production or ENV['RACK_ENV'] == :development) ?
                                    'cache.amazonaws.com:11211' :
                                    'localhost:11211')
  rescue Exception
    false
  end
end

Context

StackExchange Code Review Q#19904, answer score: 3

Revisions (0)

No revisions yet.