Module: HydraCache

Extended by:
HydraCache
Included in:
HydraCache
Defined in:
lib/hydra_cache.rb,
lib/hydra_cache/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#fixtures_pathObject



62
63
64
# File 'lib/hydra_cache.rb', line 62

def fixtures_path
  @fixtures_path || File.expand_path('fixtures')
end

#prefixObject

Returns the value of attribute prefix.



6
7
8
# File 'lib/hydra_cache.rb', line 6

def prefix
  @prefix
end

#revisionObject

Returns the value of attribute revision.



7
8
9
# File 'lib/hydra_cache.rb', line 7

def revision
  @revision
end

Instance Method Details

#cache_filename(request) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hydra_cache.rb', line 45

def cache_filename(request)
  uri = URI.parse(request.url)
  uri.query = uri.query.split('&').sort.join('&') if uri.query

  body = request.body.to_s.split(/\n/).map do |line|
    Digest::SHA1.hexdigest(line)
  end.sort.join

  params = Array(request.params).map do |k,v|
    Digest::SHA1.hexdigest("#{k},#{v}")
  end.sort.join

  digest = Digest::MD5.hexdigest("#{uri}|#{body}|#{params}|#{request.method}")

  File.join(fixtures_path, prefix.to_s.gsub(/\W+/,'_'), "#{digest}.yml")
end

#get_cache(request) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/hydra_cache.rb', line 24

def get_cache(request)
  filename = cache_filename(request)

  if File.exist?(filename)
    YAML.load_file(filename)
  else
    false
  end
end

#getter(request) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/hydra_cache.rb', line 14

def getter(request)
  if response = get_cache(request)
    response.request = request
  else
    request.cache_timeout = 1
  end

  response
end

#set_cache(request) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/hydra_cache.rb', line 34

def set_cache(request)
  filename = cache_filename(request)
  response = request.response
  response.request = request.inspect

  FileUtils.mkdir_p(File.dirname(filename))
  File.open(filename, 'w') do |f|
    f << response.to_yaml
  end
end

#setter(request) ⇒ Object



10
11
12
# File 'lib/hydra_cache.rb', line 10

def setter(request)
  set_cache request
end