require 'rest-client' require 'json' module Github class Client DEFAULT_OPTIONS = { access_token: nil, user: {} } attr_accessor :options # stores user access_token to make authenticated requests def initialize(options={}) store_options(options) check_token end # returns user access_token def access_token @options[:access_token] end # fetches user information from github API using access_token # to identify user def user(options={}) if options.empty? get_user('user') if options.empty? else get_user("users/#{options[:login]}") end end # getter functions access information storked in # @options or fetch information (which stores it) # and returns it # getter for name def name(options={}) if options.empty? user["name"] else user(options)["name"] end end # getter for login def login(options={}) if options.empty? user["login"] else options[:login] end end # getter for email def email(options={}) if options.empty? user["email"] else user(options)["email"] end end # getter for user page url def html_url(options={}) if options.empty? user["html_url"] else user(options)["html_url"] end end # getter for url to get repositories from API def repos_url(options={}) if options.empty? user['repos_url'] else user(options)['repos_url'] end end # fetches user's repositories and wraps them in RepoResponseWrapper def repos(options={}) Github::ReposResponseWrapper.new(request(repos_url(options), access_token), access_token) end private # stores provided optiosn (included access token) def store_options(options) @options ||= DEFAULT_OPTIONS.dup @options.merge!(options) end # checks presence of access token on initialization. Client doesn't work without it def check_token raise ArgumentError, "No access token provided" if !access_token end # fetches user information from API using access_token to identify user def get_user(path) JSON.parse(RestClient.get("https://api.github.com/" + path, {params: {access_token: self.access_token}})) end end end