docbrown/app/models/github_repo.rb
rhymes 81fff248dd
Refactoring GitHub Repos functionality - step 1 (#7764)
* Rename find_or_create to upsert and improve validation and testing

* Add User.authenticated_through?

* Refactor settings/integrations

* Refactor profile github repositories rendering

* Refactor repos fetching

* Only fetch a single repo and improve error messages

* Remove unused code

* Cleanups

* Fix specs

* Remove trailing whitespace

* Fix spec

* Trigger Travis
2020-05-12 13:48:19 +02:00

63 lines
1.8 KiB
Ruby

class GithubRepo < ApplicationRecord
belongs_to :user
serialize :info_hash, Hash
validates :name, :url, :github_id_code, presence: true
validates :url, url: true, uniqueness: true
validates :github_id_code, uniqueness: true
scope :featured, -> { where(featured: true) }
after_save :clear_caches
before_destroy :clear_caches
# Update existing repository or create a new one with given params.
# Repository is searched by either GitHub ID or URL.
def self.upsert(user, **params)
repo = user.github_repos.
where(github_id_code: params[:github_id_code]).
or(where(url: params[:url])).
first
repo ||= new(params.merge(user_id: user.id))
repo.update(params)
repo
end
def self.update_to_latest
where("updated_at < ?", 1.day.ago).find_each do |repo|
user_token = User.find_by(id: repo.user_id).identities.where(provider: "github").last.token
client = Octokit::Client.new(access_token: user_token)
begin
fetched_repo = client.repo(repo.info_hash[:full_name])
repo.update!(
github_id_code: fetched_repo.id,
name: fetched_repo.name,
description: fetched_repo.description,
language: fetched_repo.language,
fork: fetched_repo.fork,
bytes_size: fetched_repo.size,
watchers_count: fetched_repo.watchers,
stargazers_count: fetched_repo.stargazers_count,
info_hash: fetched_repo.to_hash,
)
repo.user&.touch(:github_repos_updated_at)
rescue StandardError => e
repo.destroy if e.message.include?("404 - Not Found")
end
end
end
private
def clear_caches
return if user.blank?
user.touch
CacheBuster.bust(user.path)
CacheBuster.bust("#{user.path}?i=i")
CacheBuster.bust("#{user.path}/?i=i")
end
end