1class CookieStore
 2  include ::Capybara::DSL
 3
 4  class << self
 5    def set_cookies(user_id, cookies)
 6      Resque.redis.hset("cookies", user_id, cookies.join("desmond"))
 7    end
 8
 9    def get_cookies(user_id)
10      cookies = Resque.redis.hget("cookies", user_id)
11      construct(cookies) unless cookies.nil?
12    end
13
14    def remove_cookies(user_id)
15      Resque.redis.hdel("cookies", user_id)
16    end
17
18    def valid_cookies_cached?(user_id)
19      cookies = self.get_cookies(user_id)
20      cookies.present? && cookies.all? {|c| c.valid?}.tap {|r| self.remove_cookies(user_id) unless r}
21    end
22
23    private
24
25    def construct(cookies)
26      string_cookies = cookies.split('desmond')
27      string_cookies.map {|sc| Vudu::Cookie.new(sc)}
28    end
29  end
30end

I'm looking for a good way to clean up line #20. It seems there should be a good way of reusing the result of #all? in the #remove_cookies side effect.

posted Nov 18 '14 at 15:28

'desmond' was just used as an arbitrary splitter

1 Refactor


Prefer this refactor

Shortest Code!

 1class CookieStore
 2
 3
 4    def valid_cookies_cached?(user_id)
 5      cookies = self.get_cookies(user_id)
 6      cookies.present? && cookies.all? {|c| c.valid?}.tap {|r| self.remove_cookies(user_id) unless r}
 7    end
 8
 9    def other_method(foo)
10      'bar'
11    end
12  end
13end

You didn't add the #other_method.

suggested Nov 20 '14 at 18:56