idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
16,400
def find_module_named ( name ) res = @modules [ name ] || @classes [ name ] return res if res return self if self . name == name find_enclosing_module_named ( name ) end
Find a named module
16,401
def add_class_or_module ( collection , class_type , name , superclass ) cls = collection [ name ] if cls then cls . superclass = superclass unless cls . module? puts "Reusing class/module #{cls.full_name}" if $DEBUG_RDOC else if class_type == NormalModule then all = @@all_modules else all = @@all_classes end cls = all ...
Adding a class or module to a TopLevel is special as we only want one copy of a particular top - level class . For example if both file A and file B implement class C we only want one ClassModule object for C . This code arranges to share classes and modules between files .
16,402
def superclass raise NoMethodError , "#{full_name} is a module" if module? scope = self begin superclass = scope . classes . find { | c | c . name == @superclass } return superclass . full_name if superclass scope = scope . parent end until scope . nil? or TopLevel === scope @superclass end
Get the superclass of this class . Attempts to retrieve the superclass real name by following module nesting .
16,403
def write ( str ) s = str . to_s @length += Rack :: Utils . bytesize ( s ) @writer . call s header [ "Content-Length" ] = @length . to_s str end
Append to body and update Content - Length .
16,404
def to_s return @normalized if @normalized doctype = nil if @element doc = @element . document doctype = doc . doctype if doc end @normalized = Text :: normalize ( @unnormalized , doctype ) @unnormalized = nil @normalized end
Returns the attribute value with entities replaced
16,405
def value return @unnormalized if @unnormalized doctype = nil if @element doc = @element . document doctype = doc . doctype if doc end @unnormalized = Text :: unnormalize ( @normalized , doctype ) @normalized = nil @unnormalized end
Returns the UNNORMALIZED value of this attribute . That is entities have been expanded to their values
16,406
def resolve_args_with_dependencies ( args , hash ) fail "Task Argument Error" if hash . size != 1 key , value = hash . map { | k , v | [ k , v ] } . first if args . empty? task_name = key arg_names = [ ] deps = value elsif key == :needs task_name = args . shift arg_names = args deps = value else task_name = args . shif...
Resolve task arguments for a task or rule when there are dependencies declared .
16,407
def top_level standard_exception_handling do if options . show_tasks display_tasks_and_comments elsif options . show_prereqs display_prerequisites else top_level_tasks . each { | task_name | invoke_task ( task_name ) } end end end
Run the top level tasks of a Rake application .
16,408
def method_list ( cls ) list = cls . method_list unless @options . show_all list = list . find_all do | m | m . visibility == :public || m . visibility == :protected || m . force_documentation end end c = [ ] i = [ ] list . sort . each do | m | if m . singleton c << m else i << m end end return c , i end
return a list of class and instance methods that we ll be documenting
16,409
def reset @@mutex . synchronize do if self . class . hook_level == 0 Rcov :: RCOV__ . send ( @reset_meth ) @start_raw_data = data_default @end_raw_data = data_default else @start_raw_data = @end_raw_data = raw_data_absolute end @raw_data_relative = data_default @aggregated_data = data_default end end
Remove the data collected so far . Further collection will start from scratch .
16,410
def putbinaryfile ( localfile , remotefile = File . basename ( localfile ) , blocksize = DEFAULT_BLOCKSIZE , & block ) if @resume begin rest_offset = size ( remotefile ) rescue Net :: FTPPermError rest_offset = nil end else rest_offset = nil end f = open ( localfile ) begin f . binmode storbinary ( "STOR " + remotefile...
Transfers + localfile + to the server in binary mode storing the result in + remotefile + . If a block is supplied calls it passing in the transmitted data in + blocksize + chunks .
16,411
def load_from ( dir ) Dir . foreach ( dir ) do | name | next if name =~ / \. / if name =~ / / external_name = $1 is_class_method = $2 == "c" internal_name = RiWriter . external_to_internal ( external_name ) list = is_class_method ? @class_methods : @instance_methods path = File . join ( dir , name ) list << MethodEntry...
read in our methods and any classes and modules in our namespace . Methods are stored in files called name - c|i . yaml where the name portion is the external form of the method name and the c|i is a class|instance flag
16,412
def recursively_find_methods_matching ( name , is_class_method ) res = local_methods_matching ( name , is_class_method ) @inferior_classes . each do | c | res . concat ( c . recursively_find_methods_matching ( name , is_class_method ) ) end res end
Find methods matching name in ourselves and in any classes we contain
16,413
def all_method_names res = @class_methods . map { | m | m . full_name } @instance_methods . each { | m | res << m . full_name } res end
Return a list of all out method names
16,414
def local_methods_matching ( name , is_class_method ) list = case is_class_method when nil then @class_methods + @instance_methods when true then @class_methods when false then @instance_methods else fail "Unknown is_class_method: #{is_class_method.inspect}" end list . find_all { | m | m . name ; m . name [ name ] } en...
Return a list of all our methods matching a given string . Is + is_class_methods + if nil we don t care if the method is a class method or not otherwise we only return those methods that match
16,415
def markup ( str , remove_para = false ) return '' unless str if str =~ / \s \# / then content = str else content = str . gsub ( / \s / ) { $1 . tr '#' , ' ' } end res = formatter . convert content if remove_para then res . sub! ( / / , '' ) res . sub! ( / \/ / , '' ) end res end
Convert a string in markup format into HTML .
16,416
def as_href ( from_path ) if @options . all_one_file "#" + path else RDoc :: Markup :: ToHtml . gen_relative_url from_path , path end end
Returns a reference to outselves to be used as an href = the form depends on whether we re all in one file or in multiple files
16,417
def collect_methods list = @context . method_list unless @options . show_all then list = list . select do | m | m . visibility == :public or m . visibility == :protected or m . force_documentation end end @methods = list . collect do | m | RDoc :: Generator :: Method . new m , self , @options end end
Create a list of Method objects for each method in the corresponding context object . If the
16,418
def add_table_of_sections toc = [ ] @context . sections . each do | section | if section . title then toc << { 'secname' => section . title , 'href' => section . sequence } end end @values [ 'toc' ] = toc unless toc . empty? end
create table of contents if we contain sections
16,419
def http_url ( full_name , prefix ) path = full_name . dup path . gsub! ( / \s \w / , 'from-\1' ) if path [ '<<' ] :: File . join ( prefix , path . split ( "::" ) ) + ".html" end
Returns the relative file name to store this class in which is also its url
16,420
def to_ruby @constants . sort_by { | name , | name } . map do | name , constant | if constant . value . nil? then "# #{name} not available" else constant . to_ruby end end . join "\n" end
Outputs values for discovered constants . If the constant s value was not discovered it is not omitted .
16,421
def merge_in ( old ) merge ( @class_methods , old . class_methods ) merge ( @instance_methods , old . instance_methods ) merge ( @attributes , old . attributes ) merge ( @constants , old . constants ) merge ( @includes , old . includes ) if @comment . nil? || @comment . empty? @comment = old . comment else unless old ....
merge in another class desscription into this one
16,422
def filter_backtrace ( bt ) case IRB . conf [ :CONTEXT_MODE ] when 0 return nil if bt =~ / \( \) / when 1 if ( bt =~ %r! ! or bt =~ %r! \. ! or bt =~ / \. / ) return nil end when 2 return nil if bt =~ / \/ \. / when 3 return nil if bt =~ / \/ \. / bt . sub! ( / \s / ) { "" } end bt end
error message manipulator
16,423
def get_method ( method_entry ) path = method_entry . path_name File . open ( path ) { | f | RI :: Description . deserialize ( f ) } end
return the MethodDescription for a given MethodEntry by deserializing the YAML
16,424
def get_class ( class_entry ) result = nil for path in class_entry . path_names path = RiWriter . class_desc_path ( path , class_entry ) desc = File . open ( path ) { | f | RI :: Description . deserialize ( f ) } if result result . merge_in ( desc ) else result = desc end end result end
Return a class description
16,425
def parse ( args ) old_argv = ARGV . dup ARGV . replace ( args ) begin go = GetoptLong . new ( * OptionList . options ) go . quiet = true go . each do | opt , arg | case opt when "--help" then OptionList . usage when "--version" then show_version when "--list-names" then @list_names = true when "--no-pager" then @use_s...
Parse command line options .
16,426
def parse_files ( options ) file_info = [ ] files = options . files files = [ "." ] if files . empty? file_list = normalized_file_list ( options , files , true ) file_list . each do | fn | $stderr . printf ( "\n%35s: " , File . basename ( fn ) ) unless options . quiet content = File . open ( fn , "r" ) { | f | f . read...
Parse each file on the command line recursively entering directories
16,427
def alter_table ( table_name , options = { } ) table_name = table_name . to_s . downcase altered_table_name = "altered_#{table_name}" caller = lambda { | definition | yield definition if block_given? } transaction do move_table ( table_name , altered_table_name , options ) move_table ( altered_table_name , table_name ,...
Taken from SQLite adapter
16,428
def select ( ypath_str ) matches = match_path ( ypath_str ) if matches result = [ ] matches . each { | m | result . push m . last } YAML . transfer ( 'seq' , result ) end end
Search for YPath entry and return qualified nodes .
16,429
def select! ( ypath_str ) matches = match_path ( ypath_str ) if matches result = [ ] matches . each { | m | result . push m . last . transform } result end end
Search for YPath entry and return transformed nodes .
16,430
def search ( ypath_str ) matches = match_path ( ypath_str ) if matches matches . collect { | m | path = [ ] m . each_index { | i | path . push m [ i ] if ( i % 2 ) . zero? } "/" + path . compact . join ( "/" ) } end end
Search for YPath entry and return a list of qualified paths .
16,431
def match_path ( ypath_str ) depth = 0 matches = [ ] YPath . each_path ( ypath_str ) do | ypath | seg = match_segment ( ypath , 0 ) matches += seg if seg end matches . uniq end
YPath search returning a complete depth array
16,432
def match_segment ( ypath , depth ) deep_nodes = [ ] seg = ypath . segments [ depth ] if seg == "/" unless String === @value idx = - 1 @value . collect { | v | idx += 1 if Hash === @value match_init = [ v [ 0 ] . transform , v [ 1 ] ] match_deep = v [ 1 ] . match_segment ( ypath , depth ) else match_init = [ idx , v ] ...
Search a node for a single YPath segment
16,433
def [] ( * key ) if Hash === @value v = @value . detect { | k , | k . transform == key . first } v [ 1 ] if v elsif Array === @value @value . [] ( * key ) end end
We want the node to act like as Hash if it is .
16,434
def escape ( str ) s = str . gsub ( / \$ / , "#{BS}\\1" ) . gsub ( / \\ / , BACKSLASH ) . gsub ( / \^ / , HAT ) . gsub ( / / , TILDE ) . gsub ( / / , LESSTHAN ) . gsub ( / / , GREATERTHAN ) . gsub ( / / , ",{}," ) . gsub ( / \` / , BACKQUOTE ) s end
Escape a LaTeX string
16,435
def attach_function ( mname , a2 , a3 , a4 = nil , a5 = nil ) cname , arg_types , ret_type , opts = ( a4 && ( a2 . is_a? ( String ) || a2 . is_a? ( Symbol ) ) ) ? [ a2 , a3 , a4 , a5 ] : [ mname . to_s , a2 , a3 , a4 ] arg_types . map! { | e | find_type ( e ) } options = Hash . new options [ :convention ] = defined? ( ...
Attach C function + name + to this module .
16,436
def qualified_const_defined? ( path ) raise NameError , "#{path.inspect} is not a valid constant name!" unless / \w \w / =~ path names = path . to_s . split ( '::' ) names . shift if names . first . empty? names . inject ( Object ) do | mod , name | return false unless uninherited_const_defined? ( mod , name ) mod . co...
Is the provided constant path defined?
16,437
def search_for_file ( path_suffix ) path_suffix = path_suffix + '.rb' unless path_suffix . ends_with? '.rb' load_paths . each do | root | path = File . join ( root , path_suffix ) return path if File . file? path end nil end
Search for a file in load_paths matching the provided suffix .
16,438
def autoload_module! ( into , const_name , qualified_name , path_suffix ) return nil unless base_path = autoloadable_module? ( path_suffix ) mod = Module . new into . const_set const_name , mod autoloaded_constants << qualified_name unless load_once_paths . include? ( base_path ) return mod end
Attempt to autoload the provided module name by searching for a directory matching the expect path suffix . If found the module is created and assigned to + into + s constants with the name + const_name + . Provided that the directory was loaded from a reloadable base path it is added to the set of constants that are t...
16,439
def qualified_name_for ( mod , name ) mod_name = to_constant_name mod ( %w( Object Kernel ) . include? mod_name ) ? name . to_s : "#{mod_name}::#{name}" end
Return the constant path for the provided parent and constant name .
16,440
def load_missing_constant ( from_mod , const_name ) log_call from_mod , const_name if from_mod == Kernel if :: Object . const_defined? ( const_name ) log "Returning Object::#{const_name} for Kernel::#{const_name}" return :: Object . const_get ( const_name ) else log "Substituting Object for Kernel" from_mod = Object en...
Load the constant named + const_name + which is missing from + from_mod + . If it is not possible to load the constant into from_mod try its parent module using const_missing .
16,441
def remove_unloadable_constants! autoloaded_constants . each { | const | remove_constant const } autoloaded_constants . clear explicitly_unloadable_constants . each { | const | remove_constant const } end
Remove the constants that have been autoloaded and those that have been marked for unloading .
16,442
def autoloaded? ( desc ) return false if desc . is_a? ( Module ) && desc . name . blank? name = to_constant_name desc return false unless qualified_const_defined? name return autoloaded_constants . include? ( name ) end
Determine if the given constant has been automatically loaded .
16,443
def mark_for_unload ( const_desc ) name = to_constant_name const_desc if explicitly_unloadable_constants . include? name return false else explicitly_unloadable_constants << name return true end end
Mark the provided constant name for unloading . This constant will be unloaded on each request not just the next one .
16,444
def indent_text ( text , mod , first_line = true ) return "" if text . to_s . empty? spacing = indent ( mod ) text = text . gsub ( / \A \n / , "#{ spacing }\\1" ) if first_line return text . gsub ( / \n \n / , "\n#{spacing}\\1" ) end
Write a text block with the current indent
16,445
def indent ( mod = nil ) if level <= 0 mod ||= 0 else mod ||= options ( :Indent ) mod += ( level - 1 ) * options ( :Indent ) end return " " * mod end
Write a current indent
16,446
def getbinaryfile ( remotefile , localfile = File . basename ( remotefile ) , blocksize = DEFAULT_BLOCKSIZE , & block ) if @resume rest_offset = File . size? ( localfile ) f = open ( localfile , "a" ) else rest_offset = nil f = open ( localfile , "w" ) end begin f . binmode retrbinary ( "RETR " + remotefile , blocksize...
Retrieves + remotefile + in binary mode storing the result in + localfile + . If a block is supplied it is passed the retrieved data in + blocksize + chunks .
16,447
def do_write ( msg ) Thread . new do begin tuple , sec = Marshal . load ( msg ) @ts . write ( tuple , sec ) rescue end end end
Extracts the response URI from + msg + and adds it to TupleSpace where it will be picked up by + reply_service + for notification .
16,448
def lookup_ring ( timeout = 5 , & block ) return lookup_ring_any ( timeout ) unless block_given? msg = Marshal . dump ( [ [ :lookup_ring , DRbObject . new ( block ) ] , timeout ] ) @broadcast_list . each do | it | soc = UDPSocket . open begin soc . setsockopt ( Socket :: SOL_SOCKET , Socket :: SO_BROADCAST , true ) soc...
Looks up RingServers waiting + timeout + seconds . RingServers will be given + block + as a callback which will be called with the remote TupleSpace .
16,449
def create_project_file template = TemplatePage . new ( RDoc :: Page :: HPP_FILE ) values = { "title" => @options . title , "opname" => @op_name } files = [ ] @files . each do | f | files << { "html_file_name" => f . path } end values [ 'all_html_files' ] = files File . open ( @project_name , "w" ) do | f | template . ...
The project file links together all the various files that go to make up the help .
16,450
def create_contents_and_index contents = [ ] index = [ ] ( @files + @classes ) . sort . each do | entry | content_entry = { "c_name" => entry . name , "ref" => entry . path } index << { "name" => entry . name , "aref" => entry . path } internals = [ ] methods = entry . build_method_summary_list ( entry . path ) content...
The contents is a list of all files and modules . For each we include as sub - entries the list of methods they contain . As we build the contents we also build an index file
16,451
def get_renewer ( it ) case it when Numeric , true , nil return it , nil else begin return it . renew , it rescue Exception return it , nil end end end
Returns a valid argument to make_expires and the renewer or nil .
16,452
def push ( tuple ) key = bin_key ( tuple ) @hash [ key ] ||= TupleBin . new @hash [ key ] . add ( tuple ) end
Add + tuple + to the TupleBag .
16,453
def delete ( tuple ) key = bin_key ( tuple ) bin = @hash [ key ] return nil unless bin bin . delete ( tuple ) @hash . delete ( key ) if bin . empty? tuple end
Removes + tuple + from the TupleBag .
16,454
def find_all ( template ) bin_for_find ( template ) . find_all do | tuple | tuple . alive? && template . match ( tuple ) end end
Finds all live tuples that match + template + .
16,455
def find ( template ) bin_for_find ( template ) . find do | tuple | tuple . alive? && template . match ( tuple ) end end
Finds a live tuple that matches + template + .
16,456
def delete_unless_alive deleted = [ ] @hash . each do | key , bin | bin . delete_if do | tuple | if tuple . alive? false else deleted . push ( tuple ) true end end end deleted end
Delete tuples which dead tuples from the TupleBag returning the deleted tuples .
16,457
def write ( tuple , sec = nil ) entry = create_entry ( tuple , sec ) synchronize do if entry . expired? @read_waiter . find_all_template ( entry ) . each do | template | template . read ( tuple ) end notify_event ( 'write' , entry . value ) notify_event ( 'delete' , entry . value ) else @bag . push ( entry ) start_keep...
Creates a new TupleSpace . + period + is used to control how often to look for dead tuples after modifications to the TupleSpace .
16,458
def move ( port , tuple , sec = nil ) template = WaitTemplateEntry . new ( self , tuple , sec ) yield ( template ) if block_given? synchronize do entry = @bag . find ( template ) if entry port . push ( entry . value ) if port @bag . delete ( entry ) notify_event ( 'take' , entry . value ) return entry . value end raise...
Moves + tuple + to + port + .
16,459
def read ( tuple , sec = nil ) template = WaitTemplateEntry . new ( self , tuple , sec ) yield ( template ) if block_given? synchronize do entry = @bag . find ( template ) return entry . value if entry raise RequestExpiredError if template . expired? begin @read_waiter . push ( template ) start_keeper if template . exp...
Reads + tuple + but does not remove it .
16,460
def read_all ( tuple ) template = WaitTemplateEntry . new ( self , tuple , nil ) synchronize do entry = @bag . find_all ( template ) entry . collect do | e | e . value end end end
Returns all tuples matching + tuple + . Does not remove the found tuples .
16,461
def notify ( event , tuple , sec = nil ) template = NotifyTemplateEntry . new ( self , event , tuple , sec ) synchronize do @notify_waiter . push ( template ) end template end
Registers for notifications of + event + . Returns a NotifyTemplateEntry . See NotifyTemplateEntry for examples of how to listen for notifications .
16,462
def keep_clean synchronize do @read_waiter . delete_unless_alive . each do | e | e . signal end @take_waiter . delete_unless_alive . each do | e | e . signal end @notify_waiter . delete_unless_alive . each do | e | e . notify ( [ 'close' ] ) end @bag . delete_unless_alive . each do | e | notify_event ( 'delete' , e . v...
Removes dead tuples .
16,463
def notify_event ( event , tuple ) ev = [ event , tuple ] @notify_waiter . find_all_template ( ev ) . each do | template | template . notify ( ev ) end end
Notifies all registered listeners for + event + of a status change of + tuple + .
16,464
def to_pretty to_a . each_with_index . map { | e , i | "%5d %s" % [ i + 1 , e . shelljoin ] } . join ( "\n" ) end
Return entries just like running history in your shell .
16,465
def update new_collection = Array . new fog_collection = @account_tracker . connection . send ( @type ) || Array . new @log . info "Fetching #{fog_collection.count} #{@type} on #{@account_name}." fog_collection . each do | resource | @log . debug "Fetching resource: #{resource.class} #{resource.identity}" resource . _f...
Creates an object for tracking a single Fog collection in a single account
16,466
def start if not running? @log . debug "Starting tracking for account #{@name}..." @timer = Thread . new do begin while true update ; sleep @delay end rescue Exception => e sleep @delay ; retry end end else @log . info "Already tracking account #{@name}" end end
Creates an object for tracking all collections in a single Fog account
16,467
def update begin @log . info "Polling account #{@name}..." @collection_trackers . each { | tracker | tracker . update } @preceeding_update_time = @most_recent_update @most_recent_update = Time . now @log . info "Polled account #{@name}" @callback . call ( all_resources ) if @callback rescue Exception => e @log . error ...
Polls once for all the resource collections for this tracker s account
16,468
def execute_quiet ( command , error_message ) puts command if @debug return_value = - 1 Open3 . popen3 ( environment , command ) do | _stdin , stdout , stderr , wait_thread | Thread . new do stdout . each do | line | @last_output << line . strip puts line unless @quiet end end Thread . new do stderr . each do | line | ...
Run the command and capture the output
16,469
def cbz ( dir ) Mangdown :: CBZ . all ( dir ) rescue StandardError => error raise Mangdown :: Error , "Failed to package #{dir}: #{error.message}" end
cbz all subdirectories in a directory
16,470
def each_arg ( args ) remains = [ ] i = 0 until i >= args . length return remains += args [ i .. - 1 ] if @stop_words . member? args [ i ] case args [ i ] when / / return remains += args [ ( i + 1 ) .. - 1 ] when / \S / num_params_taken = yield "--#{$1}" , [ $2 ] if num_params_taken . nil? remains << args [ i ] if @sto...
yield successive arg parameter pairs
16,471
def parse_signed_request Rails . logger . info " Facebook application \"#{fb_app.namespace}\" configuration in use for this request." if request_parameter = request . params [ "signed_request" ] encoded_signature , encoded_data = request_parameter . split ( "." ) decoded_signature = base64_url_decode ( encoded_signatu...
If present parses data from the signed request and inserts it into the fbparams object for use during requests
16,472
def store ( type , hash , file ) raise Dis :: Errors :: ReadOnlyError if readonly? store! ( type , hash , file ) end
Stores a file .
16,473
def exists? ( type , hash ) if directory ( type , hash ) && directory ( type , hash ) . files . head ( key_component ( type , hash ) ) true else false end end
Returns true if a object with the given hash exists .
16,474
def get ( type , hash ) dir = directory ( type , hash ) return unless dir dir . files . get ( key_component ( type , hash ) ) end
Retrieves a file from the store .
16,475
def delete ( type , hash ) raise Dis :: Errors :: ReadOnlyError if readonly? delete! ( type , hash ) end
Deletes a file from the store .
16,476
def renew! return if renew? @renew = Thread . new do loop do sleep ttl / 2 begin logger . debug ( " - Renewing Consul session #{id}" ) Diplomat :: Session . renew ( id ) rescue Faraday :: ResourceNotFound logger . warn ( "Consul session #{id} has expired!" ) init rescue StandardError => e logger . error ( e ) end end e...
Create a thread to periodically renew the lock session
16,477
def verify_session ( wait_time = 2 ) logger . info ( " - Wait until Consul session #{id} exists" ) wait_time . times do exists = session_exist? raise CreateSessionError , 'Error creating session' unless exists sleep 1 end logger . info ( " - Found Consul session #{id}" ) rescue CreateSessionError init end
Verify wheather the session exists after a period of time
16,478
def session_exist? sessions = Diplomat :: Session . list sessions . any? { | s | s [ 'ID' ] == id } end
Does the session exist
16,479
def long_out io , level indent = " " * level @children . each_with_index do | child , i | io . write "\n#{indent}" unless i == 0 io . write "- " child . out ( io , level + 1 ) end end
Arrays start with the minus on each line - and each line has the value
16,480
def issuers ( payment_method ) if payment_method != PaymentMethod :: IDEAL && payment_method != PaymentMethod :: IDEAL_PROCESSING raise ArgumentError , "Invalid payment method, only iDEAL is supported." end Ideal :: ISSUERS end
Get a list with payment issuers .
16,481
def setup_transaction ( options = { } ) @logger . debug ( "[setup_transaction] options=#{options.inspect}" ) validate_setup_transaction_params! ( options ) normalize_account_iban! ( options ) if options [ :payment_method ] == PaymentMethod :: SEPA_DIRECT_DEBIT execute_request ( :setup_transaction , options ) end
Setup a new transaction .
16,482
def refundable? ( options = { } ) @logger . debug ( "[refundable?] options=#{options.inspect}" ) validate_required_params! ( options , :transaction_id ) response = execute_request ( :refund_info , options ) response . refundable? end
Checks if a transaction is refundable .
16,483
def refund_transaction ( options = { } ) @logger . debug ( "[refund_transaction] options=#{options.inspect}" ) validate_refund_transaction_params! ( options ) response = execute_request ( :refund_info , options ) unless response . refundable? raise NonRefundableTransactionException , options [ :transaction_id ] end opt...
Refund a transaction .
16,484
def cancellable? ( options = { } ) @logger . debug ( "[cancellable?] options=#{options.inspect}" ) validate_required_params! ( options , :transaction_id ) response = execute_request ( :status , options ) response . cancellable? end
Checks if a transaction is cancellable .
16,485
def cancel_transaction ( options = { } ) @logger . debug ( "[cancel_transaction] options=#{options.inspect}" ) validate_required_params! ( options , :transaction_id ) response = execute_request ( :status , options ) unless response . cancellable? raise NonCancellableTransactionException , options [ :transaction_id ] en...
Cancel a transaction .
16,486
def validate_required_params! ( params , * required ) required . flatten . each do | param | if ! params . key? ( param ) || params [ param ] . to_s . empty? raise ArgumentError , "Missing required parameter: #{param}." end end end
Validate required parameters .
16,487
def validate_setup_transaction_params! ( options ) required_params = [ :amount , :payment_method , :invoicenumber ] required_params << :return_url if options [ :payment_method ] != PaymentMethod :: SEPA_DIRECT_DEBIT case options [ :payment_method ] when PaymentMethod :: IDEAL , PaymentMethod :: IDEAL_PROCESSING require...
Validate params for setup transaction .
16,488
def validate_payment_issuer! ( options ) if options [ :payment_method ] == PaymentMethod :: IDEAL || options [ :payment_method ] == PaymentMethod :: IDEAL_PROCESSING unless Ideal :: ISSUERS . include? ( options [ :payment_issuer ] ) raise ArgumentError , "Invalid payment issuer: #{options[:payment_issuer]}" end end end
Validate the payment issuer when iDEAL is selected as payment method .
16,489
def validate_recurrent_transaction_params! ( options ) required_params = [ :amount , :payment_method , :invoicenumber , :transaction_id ] validate_required_params! ( options , required_params ) validate_amount! ( options ) valid_payment_methods = [ PaymentMethod :: VISA , PaymentMethod :: MASTER_CARD , PaymentMethod ::...
Validate params for recurrent transaction .
16,490
def execute_request ( request_type , options ) request = build_request ( request_type ) response = request . execute ( options ) case request_type when :setup_transaction SetupTransactionResponse . new ( response , config ) when :recurrent_transaction RecurrentTransactionResponse . new ( response , config ) when :refun...
Build and execute a request .
16,491
def build_request ( request_type ) case request_type when :setup_transaction SetupTransactionRequest . new ( config ) when :recurrent_transaction RecurrentTransactionRequest . new ( config ) when :refund_transaction RefundTransactionRequest . new ( config ) when :refund_info RefundInfoRequest . new ( config ) when :sta...
Factory method for constructing a request .
16,492
def as_string ( level ) io = StringIO . new out ( io , level ) io . string end
helper function to return the output as a string ie creates stringio calls out and returns the string
16,493
def add k , v raise "Key should be symbol not #{k}" unless k . is_a? Symbol if ( v . is_simple? ) @simple [ k ] = v else @complex [ k ] = v end end
attributes hold key value pairs
16,494
def save directory = File . dirname @path unless File . directory? directory Dir . mkdir directory end File . open @path , ?w do | file | YAML . dump @hash , file end end
Saves the cache as a YAML file .
16,495
def params_sorted_by_key ( params ) case params when Hash params . map { | k , v | [ k . to_s , params_sorted_by_key ( v ) ] } . sort_by { | k , v | k } . to_h when Array params . map { | val | params_sorted_by_key ( val ) } else params . to_s end end
stringifies and sorts hashes by key at all levels .
16,496
def rebuild! unless project = :: Juici :: Project . where ( name : params [ :project ] ) . first not_found end unless build = :: Juici :: Build . where ( parent : project . name , _id : params [ :id ] ) . first not_found end :: Juici :: Build . new_from ( build ) . tap do | new_build | new_build . save! $build_queue <<...
Find an existing build duplicate the sane parts of it .
16,497
def run ( argv = ARGV ) history << [ filename ] + argv output = @outputs [ argv ] || @default_output puts output [ :puts ] if output [ :puts ] warn output [ :warn ] if output [ :warn ] exit output [ :exit ] if output [ :exit ] end
Run the double .
16,498
def create ( & block ) register self . instance_eval ( & block ) if block_given? content = self . to_ruby fullpath = File . join ( self . class . bindir , filename ) f = File . open ( fullpath , 'w' ) f . puts content f . close FileUtils . chmod ( 0755 , File . join ( self . class . bindir , filename ) ) self end
Create the executable double .
16,499
def to_ruby ruby = [ '#!/usr/bin/env ruby' ] ruby << "$: << '#{File.expand_path('..', File.dirname(__FILE__))}'" ruby << 'require "aruba-doubles"' ruby << 'ArubaDoubles::Double.run do' @outputs . each_pair { | argv , output | ruby << " on #{argv.inspect}, #{output.inspect}" } ruby << 'end' ruby . join ( "\n" ) end
Export the double to executable Ruby code .