Skip to content
This repository
tree: 63f1f6ad65
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 81 lines (65 sloc) 2.253 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
class Repository
  include DataMapper::Resource
  
  property :id, Serial
  property :owner, String
  property :name, String
  property :created_at, DateTime
  property :updated_at, DateTime
  
  has n, :contributions

  def stale?
    time_now = DateTime.now
    cache_expires_at = self.updated_at + 1

    if time_now >= cache_expires_at
      return true
    else
      return false
    end
  end

  def refresh
    delete_cache
    create_cache
  end

  def delete_cache
    adapter = DataMapper.repository(:default).adapter
    adapter.execute("DELETE FROM contributions WHERE repository_id = #{self.id}")
    adapter.execute("DELETE FROM repositories WHERE id = #{self.id}")
  end

  def create_cache
    cache_contributors_from_github(self.id)
  end
  
  def cache_contributors_from_github(repository_id)
    contributors_text = RestClient.get "https://api.github.com/repos/#{self.owner}/#{self.name}/contributors"
    contributors_json = JSON.parse(contributors_text)
    
    contributors_json.each do |contributor|
      contribution = Contribution.create(:repository => Repository.get(repository_id), :user => contributor['login'], :count => contributor['contributions'])
    end
  end
  
  def self.get_contributions(owner, repo, user) # TODO: Screaming to be refactored #codeSmell
    contributions = 0
    repository = Repository.first(:owner => owner, :name => repo)
    
    if repository

      if repository.stale?
        repository.delete_cache
        repository = Repository.create(:owner => owner, :name => repo)
        repository.create_cache
        contribution = Contribution.first(:repository => repository, :user => user)
        if contribution
          contributions = contribution['count']
        end
      else
        contribution = Contribution.first(:user => user, :repository => repository)
        if contribution
          contributions = contribution['count']
        end
      end
      
    else
      repository = Repository.create(:owner => owner, :name => repo)
      repository.create_cache
      contribution = Contribution.first(:repository => repository, :user => user)
      
      if contribution
        contributions = contribution['count']
      end
    end

    return contributions
  end
end
Something went wrong with that request. Please try again.