@@ -62,39 +62,43 @@ def read(source_url)
6262
6363 private
6464
65- # Takes a github.{com|io} url and returns its api.google .com url
65+ # Takes a github.{com|io} url and returns its api.github .com url
6666 def to_github_api ( url )
6767 uri = URI ( url )
68- return nil unless uri . host =~ /(\. |\A )(github\. com|github\. io)\Z /i
69-
70- if uri . host . end_with? ( 'github.io' )
71- github_api_from_io ( uri )
72- elsif uri . host . end_with? ( 'github.com' )
73- github_api_from_com ( uri )
68+ parts = uri . path . split ( '/' ) # 'example.com/foo/bar' will have path == '/foo/bar', so three parts
69+
70+ # http(s)://github.com/<username>/<repo> is the strict way to pass
71+ if uri . host &.downcase == 'github.com' && parts . size == 3
72+ github_api_from_com ( parts )
73+ # http(s)://<username>.github.io/<repo> is the strict way to pass
74+ elsif uri . host &.downcase &.end_with? ( '.github.io' ) && ( uri . host . count ( '.' ) == 2 ) && parts . size >= 2
75+ github_api_from_io ( uri , parts )
7476 end
7577 end
7678
77- def github_api_from_io ( uri )
78- parts = uri . path . split ( '/' )
79+ def github_api_from_com ( parts )
80+ "#{ GITHUB_API_BASE } /#{ parts [ 1 ] } /#{ parts [ 2 ] } "
81+ end
82+
83+ def github_api_from_io ( uri , parts )
7984 repo = parts [ 1 ]
8085 owner = uri . host . split ( '.' ) . first
8186 "#{ GITHUB_API_BASE } /#{ owner } /#{ repo } "
8287 end
8388
84- def github_api_from_com ( uri )
85- parts = uri . path . split ( '/' )
86- "#{ GITHUB_API_BASE } /#{ parts [ 1 ] } /#{ parts [ 2 ] } "
87- end
88-
8989 # Fetch cached data or opens webpage/api and cache it
9090 # I chose to cache because GitHub limits up to 60 requests per hour for unauthenticated user
9191 # https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28#primary-rate-limit-for-unauthenticated-users
9292 # One GitHub URL equals to 4 GitHub API requests.
9393 # key: string key for the cache
9494 # ttl: time-to-live in seconds (default 7 days)
9595 def get_or_set_cache ( key , url )
96+ content = open_url ( url )
97+ return unless content
98+
99+ data = JSON . parse ( content . read )
96100 Rails . cache . fetch ( key , expires_in : TTL ) do
97- JSON . parse ( open_url ( url ) . read )
101+ data
98102 end
99103 rescue StandardError => e
100104 @messages << "#{ self . class . name } get_or_set_cache failed for #{ url } , #{ e . message } "
0 commit comments