Class: Hubba::Cache
- Inherits:
-
Object
- Object
- Hubba::Cache
- Defined in:
- lib/hubba/cache.rb
Overview
lets you work with GitHub api “offline” using just a local cache of stored json
Instance Method Summary collapse
-
#get(request_uri) ⇒ Object
fix/todo: cut of query string e.g.
-
#initialize(dir) ⇒ Cache
constructor
A new instance of Cache.
- #put(request_uri, obj) ⇒ Object
- #request_uri_to_basename(request_uri) ⇒ Object
Constructor Details
#initialize(dir) ⇒ Cache
7 8 9 |
# File 'lib/hubba/cache.rb', line 7 def initialize( dir ) @dir = dir end |
Instance Method Details
#get(request_uri) ⇒ Object
fix/todo: cut of query string e.g. ?per_page=100 why? why not?
12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/hubba/cache.rb', line 12 def get( request_uri ) ## check if request_uri exists in local cache basename = request_uri_to_basename( request_uri ) path = "#{@dir}/#{basename}.json" if File.exist?( path ) text = File.read( path ) ## todo/fix: use File.read_utf8 json = JSON.parse( text ) json else nil ## todo/fix: raise exception - why? why not?? end end |
#put(request_uri, obj) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/hubba/cache.rb', line 25 def put( request_uri, obj ) basename = request_uri_to_basename( request_uri ) path = "#{@dir}/#{basename}.json" if obj.is_a?( Resource ) ## note: for convenience support Resource obj too data = obj.data else data = obj # assume Hash or Array -- todo: add support for String - why? why not?? end File.open( path, 'w' ) do |f| f.write JSON.pretty_generate( data ) end end |
#request_uri_to_basename(request_uri) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/hubba/cache.rb', line 41 def request_uri_to_basename( request_uri ) ## 1) cut off leading / ## 2) convert / to ~ ## 3) remove (optional) query string (for now) - why? why not? ## ## e.g. ## '/users/geraldb' => 'users~geraldb', ## '/users/geraldb/repos' => 'users~geraldb~repos', ## '/users/geraldb/orgs' => 'users~geraldb~orgs', ## '/orgs/wikiscript/repos' => 'orgs~wikiscript~repos', ## '/orgs/planetjekyll/repos' => 'orgs~planetjekyll~repos', ## '/orgs/vienna-rb/repos' => 'orgs~vienna~rb.repos', basename = request_uri[1..-1] basename = basename.gsub( '/', '~') basename = basename.sub( /\?.*\z/, '' ) ## note: must escape ? (use \z for $) basename end |