Class: PincodeFinder::GitHubClient
- Inherits:
-
Object
- Object
- PincodeFinder::GitHubClient
- Defined in:
- lib/pincode_finder/github_client.rb
Instance Method Summary collapse
- #get_file_with_sha ⇒ Object
-
#initialize ⇒ GitHubClient
constructor
A new instance of GitHubClient.
- #update_file(json_data, sha) ⇒ Object
Constructor Details
#initialize ⇒ GitHubClient
Returns a new instance of GitHubClient.
8 9 10 11 12 13 14 |
# File 'lib/pincode_finder/github_client.rb', line 8 def initialize @owner = PincodeFinder.config.github_owner @repo = PincodeFinder.config.github_repo @token = PincodeFinder.config.github_token @api = "https://api.github.com" @file = "pincode_data_optimized.json.gz" end |
Instance Method Details
#get_file_with_sha ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/pincode_finder/github_client.rb', line 16 def get_file_with_sha uri = URI("#{@api}/repos/#{@owner}/#{@repo}/contents/data/#{@file}") req = Net::HTTP::Get.new(uri) req["Authorization"] = "token #{@token}" req["Accept"] = "application/vnd.github+json" res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) } return { json: {}, sha: nil } unless res.is_a?(Net::HTTPSuccess) data = JSON.parse(res.body) content = Base64.decode64(data["content"]) json_string = Zlib::GzipReader.new(StringIO.new(content)).read { json: JSON.parse(json_string), sha: data["sha"] } end |
#update_file(json_data, sha) ⇒ Object
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/pincode_finder/github_client.rb', line 35 def update_file(json_data, sha) json_string = JSON.pretty_generate(json_data) # compress string_io = StringIO.new gz = Zlib::GzipWriter.new(string_io) gz.write(json_string) gz.close compressed = string_io.string encoded = Base64.strict_encode64(compressed) uri = URI("#{@api}/repos/#{@owner}/#{@repo}/contents/data/#{@file}") body = { message: "Update #{@file}", content: encoded, sha: sha, branch: "main" } req = Net::HTTP::Put.new(uri) req["Authorization"] = "token #{@token}" req["Accept"] = "application/vnd.github+json" req.body = body.to_json Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |h| h.request(req) } end |