idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,100
def exit_status effective_sources . each do | source | next if @ignore . include? ( source ) process_source ( source ) break if @fail_fast && ! @success end @success ? EXIT_SUCCESS : EXIT_FAILURE end
Return exit status
6,101
def effective_sources if @start_with reject = true @sources . reject do | source | if reject && source . eql? ( @start_with ) reject = false end reject end else @sources end end
Return effective sources
6,102
def sources ( file_name ) files = if File . directory? ( file_name ) Dir . glob ( File . join ( file_name , '**/*.rb' ) ) . sort elsif File . file? ( file_name ) [ file_name ] else Dir . glob ( file_name ) . sort end files . map ( & Source :: File . method ( :new ) ) end
Return sources for file name
6,103
def define_child ( name , index ) define_method ( name ) do children . at ( index ) end private name end
Define named child
6,104
def define_group ( name , range ) define_method ( name ) do children [ range ] end private ( name ) memoize ( name ) end
Define a group of children
6,105
def children ( * names ) define_remaining_children ( names ) names . each_with_index do | name , index | define_child ( name , index ) end end
Create name helpers
6,106
def visited_children children . map do | node | if node . is_a? ( Parser :: AST :: Node ) visit ( node ) else node end end end
Return visited children
6,107
def write_to_buffer emit_comments_before if buffer . fresh_line? dispatch comments . consume ( node ) emit_eof_comments if parent . is_a? ( Root ) self end
Trigger write to buffer
6,108
def visit ( node ) emitter = emitter ( node ) conditional_parentheses ( ! emitter . terminated? ) do emitter . write_to_buffer end end
Visit ambiguous node
6,109
def delimited ( nodes , & block ) return if nodes . empty? block ||= method ( :visit ) head , * tail = nodes block . call ( head ) tail . each do | node | write ( DEFAULT_DELIMITER ) block . call ( node ) end end
Emit delimited body
6,110
def emit_comments_before ( source_part = :expression ) comments_before = comments . take_before ( node , source_part ) return if comments_before . empty? emit_comments ( comments_before ) buffer . nl end
Write comments that appeared before source_part in the source
6,111
def emit_eof_comments emit_eol_comments comments_left = comments . take_all return if comments_left . empty? buffer . nl emit_comments ( comments_left ) end
Write end - of - file comments
6,112
def emit_comments ( comments ) max = comments . size - 1 comments . each_with_index do | comment , index | if comment . type . equal? ( :document ) buffer . append_without_prefix ( comment . text . chomp ) else write ( comment . text ) end buffer . nl if index < max end end
Write each comment to a separate line
6,113
def emit_body ( body = body ( ) ) unless body buffer . indent nl buffer . unindent return end visit_indented ( body ) end
Emit non nil body
6,114
def take_before ( node , source_part ) range = source_range ( node , source_part ) if range take_while { | comment | comment . location . expression . end_pos <= range . begin_pos } else EMPTY_ARRAY end end
Take comments appear in the source before the specified part of the node
6,115
def unshift_documents ( comments ) doc_comments , other_comments = comments . partition ( & :document? ) doc_comments . reverse_each { | comment | @comments . unshift ( comment ) } other_comments end
Unshift document comments and return the rest
6,116
def copy_bundler_env gem_path = installed_spec . gem_dir return if gem_path == File . dirname ( gemfile_lock ) FileUtils . install ( gemfile_lock , gem_path , mode : 0644 ) if File . exist? ( dot_bundle_dir ) && File . directory? ( dot_bundle_dir ) FileUtils . cp_r ( dot_bundle_dir , gem_path ) FileUtils . chmod_R ( "u...
Copy over any . bundler and Gemfile . lock files to the target gem directory . This will let us run tests from under that directory .
6,117
def write_merged_lockfiles ( without : [ ] ) unless external_lockfile? copy_bundler_env return end Tempfile . open ( ".appbundler-gemfile" , app_dir ) do | t | t . puts "source 'https://rubygems.org'" locked_gems = { } gemfile_lock_specs . each do | s | spec = safe_resolve_local_gem ( s ) next if spec . nil? case s . s...
This is the implementation of the 3 - arg version of writing the merged lockfiles when called with the 2 - arg version it short - circuits however to the copy_bundler_env version above .
6,118
def with_output super do | out | out . puts header @queued_write = [ ] yield out @queued_write . sort . each do | line | out . puts ( line ) end end end
prepend header and sort lines before closing output
6,119
def on_command_call ( * args ) if args . last && :args == args . last [ 0 ] args_add = args . pop call = on_call ( * args ) on_method_add_arg ( call , args_add ) else super end end
handle Class . new arg call without parens
6,120
def on_assign ( name , rhs , line , * junk ) return unless name =~ / / && junk . empty? if rhs && :call == rhs [ 0 ] && rhs [ 1 ] && "#{rhs[1][0]}.#{rhs[2]}" =~ / \. / kind = $1 == 'Module' ? :module : :class superclass = $1 == 'Class' ? rhs [ 3 ] : nil superclass . flatten! if superclass return on_module_or_class ( ki...
Ripper trips up on keyword arguments in pre - 2 . 1 Ruby and supplies extra arguments that we just ignore here
6,121
def store_translations ( locale , data , options = { } ) super ActiveRecord :: Base . transaction do store_item ( locale , data ) end if store_items? && valid_locale? ( locale ) end
Stores the given translations .
6,122
def fallback_localization ( locale , key_without_locale ) value = nil return nil unless fallbacks = :: Rails . application . config . i18n . fallbacks keys = fallbacks == true ? @locale_cache . keys : fallbacks keys . map ( & :to_s ) . each do | lc | if lc != locale . locale && value . nil? nk = "#{lc}.#{key_without_lo...
fallback to translation in different locale
6,123
def fallback_to_default ( localization_key , localization ) localization_key . localizations . where . not ( default_value : nil ) . where . not ( id : localization . id ) . first &. default_value end
tries to get default_value from localization_key - checks other localizations
6,124
def translate ( text : , from : nil , to : , ** opts ) provider . translate ( text : text , from : from , to : to , ** opts ) end
Uses the active translation provider to translate a text or array of texts .
6,125
def configure ( & block ) unless provider raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' '.provider = PROVIDER_KLASS` before calling #configure.' end provider . tap do | p | p . configure ( & block ) end end
Optional if provider - speciffic environment variables are set correctly . Configures the cloud translation provider with specific settings overriding those from environment if needed .
6,126
def upsert ( locale , key , value ) I18n . with_locale ( locale ) do val = value . is_a? ( Array ) ? [ value ] : value I18n . t ( key , default : val ) unless @raw existing_translation = Lit :: Localization . joins ( :locale , :localization_key ) . find_by ( 'localization_key = ? and locale = ?' , key , locale ) if exi...
This is mean to insert a value for a key in a given locale using some kind of strategy which depends on the service s options .
6,127
def transliterate! ( * kinds ) kinds . compact! kinds = [ :latin ] if kinds . empty? kinds . each do | kind | transliterator = Transliterator . get ( kind ) . instance @wrapped_string = transliterator . transliterate ( @wrapped_string ) end @wrapped_string end
Approximate an ASCII string . This works only for Western strings using characters that are Roman - alphabet characters + diacritics . Non - letter characters are left unmodified .
6,128
def to_ruby_method! ( allow_bangs = true ) leader , trailer = @wrapped_string . strip . scan ( / \A \z / ) . flatten leader = leader . to_s trailer = trailer . to_s if allow_bangs trailer . downcase! trailer . gsub! ( / \\ / , '' ) else trailer . downcase! trailer . gsub! ( / / , '' ) end id = leader . to_identifier id...
Normalize a string so that it can safely be used as a Ruby method name .
6,129
def truncate_bytes! ( max ) return @wrapped_string if @wrapped_string . bytesize <= max curr = 0 new = [ ] unpack ( "U*" ) . each do | char | break if curr > max char = [ char ] . pack ( "U" ) curr += char . bytesize if curr <= max new << char end end @wrapped_string = new . join end
Truncate the string to + max + bytes . This can be useful for ensuring that a UTF - 8 string will always fit into a database column with a certain max byte length . The resulting string may be less than + max + if the string must be truncated at a multibyte character boundary .
6,130
def send_to_new_instance ( * args ) id = Identifier . allocate id . instance_variable_set :@wrapped_string , to_s id . send ( * args ) id end
Used as the basis of the bangless methods .
6,131
def nyan_cat if self . failed_or_pending? && self . finished? ascii_cat ( 'x' ) [ @color_index % 2 ] . join ( "\n" ) elsif self . failed_or_pending? ascii_cat ( 'o' ) [ @color_index % 2 ] . join ( "\n" ) elsif self . finished? ascii_cat ( '-' ) [ @color_index % 2 ] . join ( "\n" ) else ascii_cat ( '^' ) [ @color_index ...
Determine which Ascii Nyan Cat to display . If tests are complete Nyan Cat goes to sleep . If there are failing or pending examples Nyan Cat is concerned .
6,132
def terminal_width if defined? JRUBY_VERSION default_width = 80 else default_width = ` ` . split . map { | x | x . to_i } . reverse . first - 1 end @terminal_width ||= default_width end
A Unix trick using stty to get the console columns
6,133
def scoreboard @pending_examples ||= [ ] @failed_examples ||= [ ] padding = @example_count . to_s . length [ @current . to_s . rjust ( padding ) , success_color ( ( @current - @pending_examples . size - @failed_examples . size ) . to_s . rjust ( padding ) ) , pending_color ( @pending_examples . size . to_s . rjust ( pa...
Creates a data store of pass failed and pending example results We have to pad the results here because sprintf can t properly pad color
6,134
def nyan_trail marks = @example_results . each_with_index . map { | mark , i | highlight ( mark ) * example_width ( i ) } marks . shift ( current_width - terminal_width ) if current_width >= terminal_width nyan_cat . split ( "\n" ) . each_with_index . map do | line , index | format ( "%s#{line}" , marks . join ) end . ...
Creates a rainbow trail
6,135
def colors @colors ||= ( 0 ... ( 6 * 7 ) ) . map do | n | pi_3 = Math :: PI / 3 n *= 1.0 / 6 r = ( 3 * Math . sin ( n ) + 3 ) . to_i g = ( 3 * Math . sin ( n + 2 * pi_3 ) + 3 ) . to_i b = ( 3 * Math . sin ( n + 4 * pi_3 ) + 3 ) . to_i 36 * r + 6 * g + b + 16 end end
Calculates the colors of the rainbow
6,136
def highlight ( mark = PASS ) case mark when PASS ; rainbowify PASS_ARY [ @color_index % 2 ] when FAIL ; "\e[31m#{mark}\e[0m" when ERROR ; "\e[33m#{mark}\e[0m" when PENDING ; "\e[33m#{mark}\e[0m" else mark end end
Determines how to color the example . If pass it is rainbowified otherwise we assign red if failed or yellow if an error occurred .
6,137
def set_fonts ( font ) font_name = Pathname . new ( font ) . basename @pdf . font_families . update ( "#{font_name}" => { normal : font , italic : font , bold : font , bold_italic : font } ) @pdf . font ( font_name ) end
Add font family in Prawn for a given + font + file
6,138
def build_pdf @push_down = 0 @push_items_table = 0 @pdf . fill_color '000000' build_header build_provider_box build_purchaser_box build_payment_method_box build_info_box build_items build_total build_stamp build_logo build_note build_footer end
Build the PDF version of the document (
6,139
def determine_items_structure items_params = { } @document . items . each do | item | items_params [ :names ] = true unless item . name . empty? items_params [ :variables ] = true unless item . variable . empty? items_params [ :quantities ] = true unless item . quantity . empty? items_params [ :units ] = true unless it...
Determine sections of the items table to show based on provided data
6,140
def build_items_data ( items_params ) @document . items . map do | item | line = [ ] line << item . name if items_params [ :names ] line << item . variable if items_params [ :variables ] line << item . quantity if items_params [ :quantities ] line << item . unit if items_params [ :units ] line << item . price if items_...
Include only items params with provided data
6,141
def build_items_header ( items_params ) headers = [ ] headers << { text : label_with_sublabel ( :item ) } if items_params [ :names ] headers << { text : label_with_sublabel ( :variable ) } if items_params [ :variables ] headers << { text : label_with_sublabel ( :quantity ) } if items_params [ :quantities ] headers << {...
Include only relevant headers
6,142
def call ( request_env ) request = :: Rack :: Request . new ( request_env ) request_method = request_env [ 'REQUEST_METHOD' ] . downcase . to_sym request_env [ 'rack.input' ] . rewind request_body = request_env [ 'rack.input' ] . read request_env [ 'rack.input' ] . rewind request_headers = { } request_env . each do | k...
target_uri is the base relative to which requests are made .
6,143
def symbolize_keys ( hash ) hash . keys . each do | key | hash [ ( key . to_sym rescue key ) || key ] = hash . delete ( key ) end hash end
Changes all keys in the top level of the hash to symbols . Does not affect nested hashes inside this one .
6,144
def for_actor ( id : nil , guid : nil , default_properties : { } ) ActorControl . new ( self , id : id , guid : guid , default_properties : default_properties ) end
Creates a new determinator instance which assumes the actor id guid and properties given are always specified . This is useful for within a before filter in a webserver for example so that the determinator instance made available has the logged - in user s credentials prefilled .
6,145
def feature_flag_on? ( name , id : nil , guid : nil , properties : { } ) determinate_and_notice ( name , id : id , guid : guid , properties : properties ) do | feature | feature . feature_flag? end end
Determines whether a specific feature is on or off for the given actor
6,146
def which_variant ( name , id : nil , guid : nil , properties : { } ) determinate_and_notice ( name , id : id , guid : guid , properties : properties ) do | feature | feature . experiment? end end
Determines what an actor should see for a specific experiment
6,147
def parse_outcome ( outcome , allow_exclusion : ) valid_outcomes = experiment? ? variants . keys : [ true ] valid_outcomes << false if allow_exclusion valid_outcomes . include? ( outcome ) ? outcome : nil end
Validates the given outcome for this feature .
6,148
def stop return self if @pid . nil? _log "stopping (##{@pid})" Process . kill ( 'INT' , @pid ) Timeout :: timeout ( 10 ) do sleep ( 10e-3 ) until Process . wait ( @pid , Process :: WNOHANG ) @status = $? end @pid = nil self end
politely ask the process to stop and wait for it to exit
6,149
def wait_log ( regexp ) cursor = 0 Timeout :: timeout ( 10 ) do loop do line = @loglines [ cursor ] sleep ( 10e-3 ) if line . nil? break if line && line =~ regexp cursor += 1 unless line . nil? end end self end
wait until a log line is seen that matches regexp up to a timeout
6,150
def readers_to_cleanup ( reader_class ) reader_class . reader_scope . joins ( :read_marks ) . where ( ReadMark . table_name => { readable_type : readable_class . name } ) . group ( "#{ReadMark.quoted_table_name}.reader_type, #{ReadMark.quoted_table_name}.reader_id, #{reader_class.quoted_table_name}.#{reader_class.quote...
Not for every reader a cleanup is needed . Look for those readers with at least one single read mark
6,151
def truncate ( string , options = { } ) length = options [ :length ] || 30 if string . length > length string [ 0 .. length - 3 ] + "..." else string end end
Truncate the given string to a certain number of characters .
6,152
def rename_keys ( options , map = { } ) Hash [ options . map { | k , v | [ map [ k ] || k , v ] } ] end
Rename a list of keys to the given map .
6,153
def slice ( options , * keys ) keys . inject ( { } ) do | hash , key | hash [ key ] = options [ key ] if options [ key ] hash end end
Slice the given list of options with the given keys .
6,154
def xml_to_hash ( element , child_with_children = "" , unique_children = true ) properties = { } element . each_element_with_text do | e | if e . name . eql? ( child_with_children ) if unique_children e . each_element_with_text do | t | properties [ t . name ] = to_type ( t . text ) end else children = [ ] e . each_ele...
Flatten an xml element with at most one child node with children into a hash .
6,155
def properties ( props = nil ) if props . nil? || props . empty? get_properties else set_properties ( props ) get_properties ( true ) end end
Set properties for this object . If no properties are given it lists the properties for this object .
6,156
def download ( target = Dir . mktmpdir , options = { } ) target = File . expand_path ( target ) FileUtils . mkdir_p ( target ) unless File . exist? ( target ) filename = options [ :filename ] || File . basename ( download_uri ) destination = File . join ( target , filename ) File . open ( destination , "wb" ) do | file...
Download the artifact onto the local disk .
6,157
def upload ( repo , remote_path , properties = { } , headers = { } ) file = File . new ( File . expand_path ( local_path ) ) matrix = to_matrix_properties ( properties ) endpoint = File . join ( "#{url_safe(repo)}#{matrix}" , remote_path ) headers [ "X-Checksum-Md5" ] = md5 if md5 headers [ "X-Checksum-Sha1" ] = sha1 i...
Upload an artifact into the repository . If the first parameter is a File object that file descriptor is passed to the uploader . If the first parameter is a string it is assumed to be the path to a local file on disk . This method will automatically construct the File object from the given path .
6,158
def get_properties ( refresh_cache = false ) if refresh_cache || @properties . nil? @properties = client . get ( File . join ( "/api/storage" , relative_path ) , properties : nil ) [ "properties" ] end @properties end
Helper method for reading artifact properties
6,159
def set_properties ( properties ) matrix = to_matrix_properties ( properties ) endpoint = File . join ( "/api/storage" , relative_path ) + "?properties=#{matrix}" client . put ( endpoint , nil ) end
Helper method for setting artifact properties
6,160
def copy_or_move ( action , destination , options = { } ) params = { } . tap do | param | param [ :to ] = destination param [ :failFast ] = 1 if options [ :fail_fast ] param [ :suppressLayouts ] = 1 if options [ :suppress_layouts ] param [ :dry ] = 1 if options [ :dry_run ] end endpoint = File . join ( "/api" , action ...
Copy or move current artifact to a new destination .
6,161
def to_hash attributes . inject ( { } ) do | hash , ( key , value ) | unless Resource :: Base . has_attribute? ( key ) hash [ Util . camelize ( key , true ) ] = send ( key . to_sym ) end hash end end
The hash representation
6,162
def to_matrix_properties ( hash = { } ) properties = hash . map do | k , v | key = CGI . escape ( k . to_s ) value = CGI . escape ( v . to_s ) "#{key}=#{value}" end if properties . empty? nil else ";#{properties.join(';')}" end end
Create CGI - escaped string from matrix properties
6,163
def to_query_string_parameters ( hash = { } ) properties = hash . map do | k , v | key = URI . escape ( k . to_s ) value = URI . escape ( v . to_s ) "#{key}=#{value}" end if properties . empty? nil else properties . join ( "&" ) end end
Create URI - escaped querystring parameters
6,164
def promote ( target_repo , options = { } ) request_body = { } . tap do | body | body [ :status ] = options [ :status ] || "promoted" body [ :comment ] = options [ :comment ] || "" body [ :ciUser ] = options [ :user ] || Artifactory . username body [ :dryRun ] = options [ :dry_run ] || false body [ :targetRepo ] = targ...
Move a build s artifacts to a new repository optionally moving or copying the build s dependencies to the target repository and setting properties on promoted artifacts .
6,165
def save raise Error :: InvalidBuildType . new ( type ) unless BUILD_TYPES . include? ( type ) file = Tempfile . new ( "build.json" ) file . write ( to_json ) file . rewind client . put ( "/api/build" , file , "Content-Type" => "application/json" ) true ensure if file file . close file . unlink end end
Creates data about a build .
6,166
def builds @builds ||= Collection :: Build . new ( self , name : name ) do Resource :: Build . all ( name ) end end
The list of build data for this component .
6,167
def delete ( options = { } ) params = { } . tap do | param | param [ :buildNumbers ] = options [ :build_numbers ] . join ( "," ) if options [ :build_numbers ] param [ :artifacts ] = 1 if options [ :artifacts ] param [ :deleteAll ] = 1 if options [ :delete_all ] end endpoint = api_path + "?#{to_query_string_parameters(p...
Remove this component s build data stored in Artifactory
6,168
def rename ( new_name , options = { } ) endpoint = "/api/build/rename/#{url_safe(name)}" + "?to=#{new_name}" client . post ( endpoint , { } ) true rescue Error :: HTTPError => e false end
Rename a build component .
6,169
def upload ( local_path , remote_path , properties = { } , headers = { } ) artifact = Resource :: Artifact . new ( local_path : local_path ) artifact . upload ( key , remote_path , properties , headers ) end
Upload to a given repository
6,170
def upload_from_archive ( local_path , remote_path , properties = { } ) artifact = Resource :: Artifact . new ( local_path : local_path ) artifact . upload_from_archive ( key , remote_path , properties ) end
Upload an artifact with the given archive . Consult the artifactory documentation for the format of the archive to upload .
6,171
def artifacts @artifacts ||= Collection :: Artifact . new ( self , repos : key ) do Resource :: Artifact . search ( name : ".*" , repos : key ) end end
The list of artifacts in this repository on the remote artifactory server .
6,172
def drain_fd ( fd , buf = nil ) loop do tmp = fd . read_nonblock ( 4096 ) buf << tmp unless buf . nil? end rescue EOFError , Errno :: EPIPE fd . close true rescue Errno :: EINTR rescue Errno :: EWOULDBLOCK , Errno :: EAGAIN false end
Do nonblocking reads from fd appending all data read into buf .
6,173
def select_until ( read_array , write_array , err_array , timeout_at ) if ! timeout_at return IO . select ( read_array , write_array , err_array ) end remaining = ( timeout_at - Time . now ) return nil if remaining <= 0 IO . select ( read_array , write_array , err_array , remaining ) end
Call IO . select timing out at Time timeout_at . If timeout_at is nil never times out .
6,174
def remove_from_set ( set , item ) Predictor . redis . multi do | redis | redis . srem ( redis_key ( :items , set ) , item ) redis . srem ( redis_key ( :sets , item ) , set ) end end
Delete a specific relationship
6,175
def delete_item ( item ) Predictor . redis . watch ( redis_key ( :sets , item ) ) do sets = Predictor . redis . smembers ( redis_key ( :sets , item ) ) Predictor . redis . multi do | multi | sets . each do | set | multi . srem ( redis_key ( :items , set ) , item ) end multi . del redis_key ( :sets , item ) end end end
delete item from the matrix
6,176
def acquire_token_for_client ( resource , client_cred ) fail_if_arguments_nil ( resource , client_cred ) token_request_for ( client_cred ) . get_for_client ( resource ) end
Gets an access token with only the clients credentials and no user information .
6,177
def acquire_token_with_authorization_code ( auth_code , redirect_uri , client_cred , resource = nil ) fail_if_arguments_nil ( auth_code , redirect_uri , client_cred ) token_request_for ( client_cred ) . get_with_authorization_code ( auth_code , redirect_uri , resource ) end
Gets an access token with a previously acquire authorization code .
6,178
def acquire_token_with_refresh_token ( refresh_token , client_cred , resource = nil ) fail_if_arguments_nil ( refresh_token , client_cred ) token_request_for ( client_cred ) . get_with_refresh_token ( refresh_token , resource ) end
Gets an access token using a previously acquire refresh token .
6,179
def authorization_request_url ( resource , client_id , redirect_uri , extra_query_params = { } ) @authority . authorize_endpoint ( extra_query_params . reverse_merge ( client_id : client_id , response_mode : FORM_POST , redirect_uri : redirect_uri , resource : resource , response_type : CODE ) ) end
Constructs a URL for an authorization endpoint using query parameters .
6,180
def request_params jwt_assertion = SelfSignedJwtFactory . new ( @client_id , @authority . token_endpoint ) . create_and_sign_jwt ( @certificate , @private_key ) ClientAssertion . new ( client_id , jwt_assertion ) . request_params end
Creates a new ClientAssertionCertificate .
6,181
def request_params case account_type when AccountType :: MANAGED managed_request_params when AccountType :: FEDERATED federated_request_params else fail UnsupportedAccountTypeError , account_type end end
The OAuth parameters that respresent this UserCredential .
6,182
def execute ( username , password ) logger . verbose ( "Making a WSTrust request with action #{@action}." ) request = Net :: HTTP :: Get . new ( @endpoint . path ) add_headers ( request ) request . body = rst ( username , password ) response = http ( @endpoint ) . request ( request ) if response . code == '200' WSTrust...
Constructs a new WSTrustRequest .
6,183
def execute request = Net :: HTTP :: Get . new ( @endpoint . path ) request . add_field ( 'Content-Type' , 'application/soap+xml' ) MexResponse . parse ( http ( @endpoint ) . request ( request ) . body ) end
Constructs a MexRequest object for a specific URL endpoint .
6,184
def authorize_endpoint ( params = nil ) params = params . select { | _ , v | ! v . nil? } if params . respond_to? :select if params . nil? || params . empty? URI :: HTTPS . build ( host : @host , path : '/' + @tenant + AUTHORIZE_PATH ) else URI :: HTTPS . build ( host : @host , path : '/' + @tenant + AUTHORIZE_PATH , q...
URI that can be used to acquire authorization codes .
6,185
def discovery_uri ( host = WORLD_WIDE_AUTHORITY ) URI ( DISCOVERY_TEMPLATE . expand ( host : host , endpoint : authorize_endpoint ) ) end
Creates an instance discovery endpoint url for authority that this object represents .
6,186
def validated_dynamically? logger . verbose ( "Attempting instance discovery at: #{discovery_uri}." ) http_response = Net :: HTTP . get ( discovery_uri ) if http_response . nil? logger . error ( 'Dynamic validation received no response from endpoint.' ) return false end parse_dynamic_validation ( JSON . parse ( http_re...
Performs instance discovery via a network call to well known authorities .
6,187
def grant_type case @token_type when TokenType :: V1 TokenRequest :: GrantType :: SAML1 when TokenType :: V2 TokenRequest :: GrantType :: SAML2 end end
Constructs a WSTrustResponse .
6,188
def create_and_sign_jwt ( certificate , private_key ) JWT . encode ( payload , private_key , RS256 , header ( certificate ) ) end
Constructs a new SelfSignedJwtFactory .
6,189
def header ( certificate ) x5t = thumbprint ( certificate ) logger . verbose ( "Creating self signed JWT header with thumbprint: #{x5t}." ) { TYPE => TYPE_JWT , ALGORITHM => RS256 , THUMBPRINT => x5t } end
The JWT header for a certificate to be encoded .
6,190
def payload now = Time . now - 1 expires = now + 60 * SELF_SIGNED_JWT_LIFETIME logger . verbose ( "Creating self signed JWT payload. Expires: #{expires}. " "NotBefore: #{now}." ) { AUDIENCE => @token_endpoint , ISSUER => @client_id , SUBJECT => @client_id , NOT_BEFORE => now . to_i , EXPIRES_ON => expires . to_i , JWT_...
The JWT payload .
6,191
def get_for_client ( resource ) logger . verbose ( "TokenRequest getting token for client for #{resource}." ) request ( GRANT_TYPE => GrantType :: CLIENT_CREDENTIALS , RESOURCE => resource ) end
Gets a token based solely on the clients credentials that were used to initialize the token request .
6,192
def get_with_authorization_code ( auth_code , redirect_uri , resource = nil ) logger . verbose ( 'TokenRequest getting token with authorization code ' "#{auth_code}, redirect_uri #{redirect_uri} and " "resource #{resource}." ) request ( CODE => auth_code , GRANT_TYPE => GrantType :: AUTHORIZATION_CODE , REDIRECT_URI =>...
Gets a token based on a previously acquired authentication code .
6,193
def get_with_refresh_token ( refresh_token , resource = nil ) logger . verbose ( 'TokenRequest getting token with refresh token digest ' "#{Digest::SHA256.hexdigest refresh_token} and resource " "#{resource}." ) request_no_cache ( GRANT_TYPE => GrantType :: REFRESH_TOKEN , REFRESH_TOKEN => refresh_token , RESOURCE => r...
Gets a token based on a previously acquired refresh token .
6,194
def get_with_user_credential ( user_cred , resource = nil ) logger . verbose ( 'TokenRequest getting token with user credential ' "#{user_cred} and resource #{resource}." ) oauth = if user_cred . is_a? UserIdentifier lambda do fail UserCredentialError , 'UserIdentifier can only be used once there is a ' 'matching token...
Gets a token based on possessing the users credentials .
6,195
def request ( params , & block ) cached_token = check_cache ( request_params ( params ) ) return cached_token if cached_token cache_response ( request_no_cache ( request_params ( params ) , & block ) ) end
Attempts to fulfill a token request first via the token cache and then through OAuth .
6,196
def add ( token_response ) return unless token_response . instance_of? SuccessResponse logger . verbose ( 'Adding successful TokenResponse to cache.' ) entry = CachedTokenResponse . new ( @client , @authority , token_response ) update_refresh_tokens ( entry ) if entry . mrrt? @token_cache . add ( entry ) end
Constructs a CacheDriver to interact with a token cache .
6,197
def find ( query = { } ) query = query . map { | k , v | [ FIELDS [ k ] , v ] if FIELDS [ k ] } . compact . to_h resource = query . delete ( RESOURCE ) matches = validate ( find_all_cached_entries ( query . reverse_merge ( authority : @authority , client_id : @client . client_id ) ) ) resource_specific ( matches , reso...
Searches the cache for a token matching a specific query of fields .
6,198
def find_all_cached_entries ( query ) logger . verbose ( "Searching cache for tokens by keys: #{query.keys}." ) @token_cache . find do | entry | query . map do | k , v | ( entry . respond_to? k . to_sym ) && ( v == entry . send ( k . to_sym ) ) end . reduce ( :& ) end end
All cache entries that match a query . This matches keys in values against a hash to method calls on an object .
6,199
def refresh_mrrt ( responses , resource ) logger . verbose ( "Attempting to obtain access token for #{resource} by " "refreshing 1 of #{responses.count(&:mrrt?)} matching " 'MRRTs.' ) responses . each do | response | if response . mrrt? refresh_response = response . refresh ( resource ) return refresh_response if add (...
Attempts to obtain an access token for a resource with refresh tokens from a list of MRRTs .