我似乎总是难以重构我的代码。我可以查看任何其他代码,并且确切地知道发生了什么,但是当涉及到清理我的代码时,我会让编写人员阻塞。
下面的代码可以工作,但我知道是否可以做得更好,并且只需要几行代码。我只是想包装一个memcache客户机,以便使用一个服务器进行测试,另一个服务器用于dev/prod,或者在无法连接到服务器的情况下获取值。
任何关于重构等的技巧都非常感谢。
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发布于 2012-12-24 23:20:18
这是self.memcache中的代码,只需为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发布于 2012-12-29 03:53:02
如果我真的想把fetch作为类方法,我会这样写它。如果这不是强制性的,我将使fetch成为唯一的公共实例方法,以及rest私有实例方法。
require 'dalli'
class Cache
def self.fetch(key, ttl, &block)
memcache ? memcache.fetch(key, ttl, &block) : block.call
end
def self.memcache
@memcache ||= new_client
end
def self.new_client
begin
Dalli::Client.new(memcache_host)
rescue StandardError
false
end
end
def self.memcache_host
(production? || development?) ? 'cache.amazonaws.com:11211' : 'localhost:11211'
end
def self.production?
environment == :production
end
def self.development?
environment == :development
end
def self.environment
ENV['RACK_ENV']
end
end发布于 2015-01-22 22:21:50
我会这样做:
require 'dalli'
class Cache
def self.fetch(key, ttl, &block)
memcache and
memcache.fetch(key, ttl, &block) or
block.call
end
def self.host
@host ||= (ENV['RACK_ENV'] == :production || ENV['RACK_ENV'] == :development) ?
'cache.amazonaws.com:11211' :
'localhost:11211'
end
def self.memcache
@memcache ||= Dalli::Client.new(host)
rescue StandardError
nil
end
end我更喜欢在方法上返回nil而不是false,否则这些方法会在成功时返回一个对象。如果它在失败时返回false,那么它应该在成功时返回true,但是这会将该方法的名称更改为memcache。
https://codereview.stackexchange.com/questions/19904
复制相似问题