Method: Numerous.numerousKey

Defined in:
lib/numerousapp.rb

.numerousKey(s: nil, credsAPIKey: 'NumerousAPIKey') ⇒ String

find an apikey from various default places

Parameters:

  • s (String) (defaults to: nil)

    See documentation for details; a file name or a key or a “readable” object.

  • credsAPIKey (String) (defaults to: 'NumerousAPIKey')

    Key to use in accessing json dict if one is found.

Returns:

  • (String)

    the API key.



1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
# File 'lib/numerousapp.rb', line 1061

def self.numerousKey(s:nil, credsAPIKey:'NumerousAPIKey')

	if not s
	    # try to get from environment
	    s = ENV['NUMEROUSAPIKEY']
	    if not s
	        return nil
        end
    end

	closeThis = nil

	if s == "@-"             # creds coming from stdin
	    s = STDIN

	# see if they are in a file
	else
	    begin
	        if s.length() > 0         # is it a string or a file object?
	            # it's stringy - if it looks like a file open it or fail
	            begin
	        	if s.length() > 1 and s[0] == '@'
	        	    s = open(s[1..-1])
	        	    closeThis = s
	        	elsif s[0] == '/' or s[0] == '.'
	        	    s = open(s)
	        	    closeThis = s
                    end
	            rescue
	        	return nil
                end
            end
	    rescue NoMethodError     # it wasn't stringy, presumably it's a "readable"
	    end
    end

	# well, see if whatever it is, is readable, and go with that if it is
	begin
	    v = s.read()
	    if closeThis
	        closeThis.close()
        end
	    s = v
	rescue NoMethodError
	end

	# at this point s is either a JSON or a naked cred (or bogus)
	begin
	    j = JSON.parse(s)
	rescue TypeError, JSON::ParserError
	    j = {}
    end


	#
	# This is kind of a hack and might hide some errors on your part
	#
	if not j.include? credsAPIKey  # this is how the naked case happens
	    # replace() bcs there might be a trailing newline on naked creds
	    # (usually happens with a file or stdin)
	    j[credsAPIKey] = s.sub("\n",'')
    end

	return j[credsAPIKey]
end