class Panthro

Attributes

mirror[RW]
path[RW]

Public Instance Methods

call(env) click to toggle source
# File lib/panthro.rb, line 5
def call env
  @env          = env
  @file_path    = "#{ self.class.path }#{ env['PATH_INFO'] }"

  return get_from_cache if File.exists? @file_path
  get_from_mirror
end

Private Instance Methods

get(uri) click to toggle source
# File lib/panthro.rb, line 26
def get uri
  http    = Net::HTTP.new( uri.host, uri.port )
  request = Net::HTTP::Get.new( uri.request_uri )
  resp    = http.request( request )
  resp    = get( URI resp['location']  ) if resp.code == '302'
  resp
end
get_from_cache() click to toggle source
# File lib/panthro.rb, line 58
def get_from_cache
  file    = File.open @file_path, "r"
  content = file.read
  file.close

  [ 200, {}, [ content ] ]
end
get_from_mirror() click to toggle source
# File lib/panthro.rb, line 34
def get_from_mirror
  @uri  = URI uri_str
  @resp = get @uri
  write_cache!

  headers = @resp.to_hash
  headers.delete 'transfer-encoding'
  headers.each{ |k,v| headers[k] = v.first }

  [ @resp.code, headers, [ @resp.body ] ]
end
uri_str() click to toggle source
# File lib/panthro.rb, line 20
def uri_str
  uri  = "#{ Panthro.mirror }#{ @env['PATH_INFO'] }"
  uri += "?#{ @env['QUERY_STRING'] }" unless @env['QUERY_STRING'].empty?
  uri
end
write_cache!() click to toggle source
# File lib/panthro.rb, line 46
def write_cache!
  return if @uri.path =~ /\/api\//
  return unless @resp.code =~ /20/

  dir = File.dirname @file_path
  FileUtils.mkdir_p dir unless File.directory? dir

  open( @file_path, "wb" ) do |file|
    file.write @resp.body
  end
end