idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
20,100
def core__send_request_success ( payload ) response = { result : true , error_message : nil } response [ :payload ] = payload if payload render json : response end
This function render a normal success response with a custom payload .
20,101
def core__send_request_fail ( error , payload : nil ) response = { result : false , error_message : error } response [ :payload ] = payload if payload render json : response end
This function render an error message with a possible custom payload .
20,102
def shell_ok? ( command ) sout , status = Open3 . capture2e command return status . to_i == 0 rescue return false end
Runs the shell command . Works the same way as Kernel . system method but without showing the output . Returns true if it was successfull .
20,103
def modify_via_segment_holder_acts_as_list_method ( method , segment ) segment_holder = segment_holder_for ( segment ) raise segment_not_associated_message ( method , segment ) unless segment_holder segment_holder . send ( method ) end
This method together with method missing is used to allow segments to be ordered within a document . It allows an acts_as_list method to be passed to the segment_holder holding a segment so as to alter its position .
20,104
def update ( attrs , safe = false ) self . attributes = attrs if new_record? _root . send ( :_save , safe ) if _root _save ( safe ) else _update_attributes ( converted_attributes ( attrs ) , safe ) end end
Update without checking validations . The + Document + will be saved without validations if it is a new record .
20,105
def download_kb response = @http . get ( "#{BASE_URL}/#{@knowledgebase_id}" ) case response . code when 200 response . parse when 400 raise BadArgumentError , response . parse [ 'error' ] [ 'message' ] . join ( ' ' ) when 401 raise UnauthorizedError , response . parse [ 'error' ] [ 'message' ] when 403 raise ForbiddenE...
Downloads all the data associated with the specified knowledge base
20,106
def form_var_string terraform_vars = terraform_metadata ec2_credentials = @node . network_driver . raw_fog_credentials cleaned_data = terraform_vars . select { | k , v | ! v . is_a? ( Hash ) && ! v . is_a? ( Array ) } all_vars = cleaned_data . merge ( { :access_key => ec2_credentials [ "aws_access_key_id" ] , :secret_k...
Get the terraform variables for this stack and merge in with our EC2 access keys
20,107
def has_file_satisfied_by? ( spec_file ) file_paths . any? { | gem_file | RPM :: Spec . file_satisfies? ( spec_file , gem_file ) } end
module ClassMethods Return bool indicating if spec file satisfies any file in gem
20,108
def unpack ( & bl ) dir = nil pkg = :: Gem :: Installer . new gem_path , :unpack => true if bl Dir . mktmpdir do | tmpdir | pkg . unpack tmpdir bl . call tmpdir end else dir = Dir . mktmpdir pkg . unpack dir end dir end
Unpack files & return unpacked directory
20,109
def each_file ( & bl ) unpack do | dir | Pathname . new ( dir ) . find do | path | next if path . to_s == dir . to_s pathstr = path . to_s . gsub ( "#{dir}/" , '' ) bl . call pathstr unless pathstr . blank? end end end
Iterate over each file in gem invoking block with path
20,110
def install_component if ( backend != :stdlib && command? ( 'rsync' ) ) || backend == :rsync FileUtils . mkdir_p destination_path cmd = [ command? ( 'rsync' ) , '-rtc' , '--del' , '--links' , "#{source_path}/" , destination_path ] logger . debug { "Running command: #{cmd.join ' '}" } system ( * cmd ) else FileUtils . r...
Recursively creates the necessary directories and installs the component . Any files in the install directory not in the source directory are removed . Use rsync if available .
20,111
def set_mode chmod = command? 'chmod' find = command? 'find' return unless chmod && find { fmode : 'f' , dmode : 'd' } . each do | k , v | next if send ( k ) . nil? cmd = [ find , destination_path , '-type' , v , '-exec' ] cmd . concat [ chmod , send ( k ) . to_s ( 8 ) , '{}' , '+' ] logger . debug { "Running command: ...
Recursively sets file mode .
20,112
def set_owner return unless owner || group chown = command? 'chown' return unless chown cmd = [ chown , '-R' , "#{owner}:#{group}" , destination_path ] logger . debug { "Running command: #{cmd.join ' '}" } system ( * cmd ) end
Recursively sets file owner and group .
20,113
def calculate_player_position screen_name @cached_player_position = { } @player_hashes . sort! { | a , b | button_relative_seat ( a ) <=> button_relative_seat ( b ) } @player_hashes = [ @player_hashes . pop ] + @player_hashes unless @player_hashes . first [ :seat ] == @button_player_index @player_hashes . each_with_ind...
long computation is cached which cache is cleared every time a new player is registered
20,114
def betting_order? ( screen_name_first , screen_name_second ) if button? ( screen_name_first ) false elsif button? ( screen_name_second ) true else position ( screen_name_first ) < position ( screen_name_second ) end end
player screen_name_first goes before player screen_name_second
20,115
def page ( number ) number = ( n = number . to_i ) > 0 ? n : 1 Page . new ( self , number , lambda { offset = ( number - 1 ) * @per_page args = [ offset ] args << @per_page if @select . arity == 2 @select . call ( * args ) } ) end
Retrieve page object by number
20,116
def add_webhook_identifier_to_email ( email ) email . message . mailgun_variables = { } email . message . mailgun_variables [ "webhook_identifier" ] = BSON :: ObjectId . new . to_s email end
returns the email after adding a webhook identifier variable .
20,117
def ruby ( program , * arguments ) command = [ program , * arguments ] command . unshift ( 'ruby' ) if program [ - 3 , 3 ] == '.rb' if ( @environment && @environment . bundler ) command . unshift ( 'bundle' , 'exec' ) end run ( * command ) end
Executes a Ruby program .
20,118
def shellescape ( str ) return "''" if str . empty? str = str . dup str . gsub! ( / \- \/ \n /n , "\\\\\\1" ) str . gsub! ( / \n / , "'\n'" ) return str end
Escapes a string so that it can be safely used in a Bourne shell command line .
20,119
def rake_task ( name , * arguments ) name = name . to_s unless arguments . empty? name += ( '[' + arguments . join ( ',' ) + ']' ) end return name end
Builds a rake task name .
20,120
def read_byte_as_integer ( bytelen ) unless bit_pointer % 8 == 0 raise BinaryException . new ( "Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}." ) end if self . length - bit_pointer / 8 < bytelen raise BinaryException . new ( "Rest of self length(#{self.length - bit_pointer/8}byte) " +...
Read specified length of bytes and return as Integer instance . Bit pointer proceed for that length .
20,121
def read_one_bit unless self . length * 8 - bit_pointer > 0 raise BinaryException . new ( "Readable buffer doesn't exist" + "(#{self.length * 8 - bit_pointer}bit exists)." ) end response = to_i ( bit_pointer / 8 ) [ 7 - bit_pointer % 8 ] bit_pointer_inc ( 1 ) return response end
Read one bit and return as 0 or 1 . Bit pointer proceed for one .
20,122
def read_bit_as_binary ( bitlen ) unless bit_pointer % 8 == 0 raise BinaryException . new ( "Bit pointer must be pointing start of byte. " + "But now pointing #{bit_pointer}." ) end unless bitlen % 8 == 0 raise BinaryException . new ( "Arg must be integer of multiple of 8. " + "But you specified #{bitlen}." ) end if se...
Read specified length of bits and return as Binary instance . Bit pointer proceed for that length .
20,123
def execute ( node , arguments ) full_command = construct_full_command ( node , arguments ) begin puts "\n(external) > #{full_command}" . bc_blue + "\n\n" system ( full_command ) rescue Interrupt puts "\nExiting gracefully from interrupt\n" . warning end end
In which the bcome context is passed to an external call
20,124
def option ( option_name ) if option_name . to_s . include? ( '.' ) parts = option_name . to_s . split ( '.' ) var_name = parts . pop group = parts . inject ( self ) do | base , part | grp = base . option ( part ) . value if grp . nil? raise NameError , "No such group: #{base.name}.#{part}" elsif grp . kind_of? ( Opto ...
Find a member by name
20,125
def acts_as_noteworthy ( options = { } ) class_inheritable_accessor :options self . options = options unless included_modules . include? InstanceMethods instance_eval do has_many :mentions , :as => :owner , :order => 'date desc' with_options :as => :owner , :class_name => "Mention" do | c | c . has_many :google_news_me...
Sets up the relationship between the model and the mention model
20,126
def raw_mentions opts = self . options . clone attributes = opts . delete ( :with ) if opts [ :geo ] opts [ :geo ] = self . instance_eval ( "#{opts[:geo]}" ) end query = [ ] attributes . each do | attr | query << self . instance_eval ( "#{attr}" ) end { :google_news => GovKit :: SearchEngines :: GoogleNews . search ( q...
Generates the raw mentions to be loaded into the Mention objects
20,127
def publish_kb response = @http . put ( "#{BASE_URL}/#{@knowledgebase_id}" ) case response . code when 204 nil when 400 raise BadArgumentError , response . parse [ 'error' ] [ 'message' ] . join ( ' ' ) when 401 raise UnauthorizedError , response . parse [ 'error' ] [ 'message' ] when 403 raise ForbiddenError , respons...
Publish all unpublished in the knowledgebase to the prod endpoint
20,128
def simple ( alert_text = nil , sound = nil , badge = nil , category = nil ) new_payload = { aps : { } } if alert_text new_payload [ :aps ] [ :alert ] = alert_text end if sound new_payload [ :aps ] [ :sound ] = sound end if badge new_payload [ :aps ] [ :badge ] = badge end if category new_payload [ :aps ] [ :category ]...
Returns a new ApnsPushMessage instance that encapsulates a single push notification to be sent to a single user .
20,129
def core__widgets_index ( records , search : nil , pagination : 50 ) response = { records : records , total : records . length , per_page : pagination , search : '' , search_key : search , sort : '' , sort_dir : 'ASC' , pagination : 1 , } if search && params [ :widget_index ] && params [ :widget_index ] [ :search ] && ...
This function manage the widget index from front end .
20,130
def remove_config ( key , options = { } ) unless config_registry . has_key? ( key ) raise NameError . new ( "#{key.inspect} is not a config on #{self}" ) end options = { :reader => true , :writer => true } . merge ( options ) config = config_registry . delete ( key ) reset_configs remove_method ( config . reader ) if o...
Removes a config much like remove_method removes a method . The reader and writer for the config are likewise removed . Nested configs can be removed using this method .
20,131
def undef_config ( key , options = { } ) unless configs . has_key? ( key ) raise NameError . new ( "#{key.inspect} is not a config on #{self}" ) end options = { :reader => true , :writer => true } . merge ( options ) config = configs [ key ] config_registry [ key ] = nil reset_configs undef_method ( config . reader ) i...
Undefines a config much like undef_method undefines a method . The reader and writer for the config are likewise undefined . Nested configs can be undefined using this method .
20,132
def remove_config_type ( name ) unless config_type_registry . has_key? ( name ) raise NameError . new ( "#{name.inspect} is not a config_type on #{self}" ) end config_type = config_type_registry . delete ( name ) reset_config_types config_type end
Removes a config_type much like remove_method removes a method .
20,133
def undef_config_type ( name ) unless config_types . has_key? ( name ) raise NameError . new ( "#{name.inspect} is not a config_type on #{self}" ) end config_type = config_type_registry [ name ] config_type_registry [ name ] = nil reset_config_types config_type end
Undefines a config_type much like undef_method undefines a method .
20,134
def check_infinite_nest ( klass ) raise "infinite nest detected" if klass == self klass . configs . each_value do | config | if config . type . kind_of? ( NestType ) check_infinite_nest ( config . type . configurable . class ) end end end
helper to recursively check for an infinite nest
20,135
def message ( event , label , body ) @odd = ! @odd label_color = @odd ? odd_color : even_color format ( ' %s (%.2fms) %s' , color ( label , label_color , true ) , event . duration , color ( body , nil , ! @odd ) ) end
Format a message for logging
20,136
def join commands = [ ] @history . each do | command | program = command [ 0 ] arguments = command [ 1 .. - 1 ] . map { | word | shellescape ( word . to_s ) } commands << [ program , * arguments ] . join ( ' ' ) end return commands . join ( ' && ' ) end
Joins the command history together with && to form a single command .
20,137
def ssh_uri unless @uri . host raise ( InvalidConfig , "URI does not have a host: #{@uri}" , caller ) end new_uri = @uri . host new_uri = "#{@uri.user}@#{new_uri}" if @uri . user return new_uri end
Converts the URI to one compatible with SSH .
20,138
def ssh ( * arguments ) options = [ ] if @uri . port options += [ '-p' , @uri . port . to_s ] end options << ssh_uri arguments . each { | arg | options << arg . to_s } return system ( 'ssh' , * options ) end
Starts a SSH session with the destination server .
20,139
def conf_attr ( name , opts = { } ) @conf_attrs ||= [ ] @conf_attrs << name default = opts [ :default ] accumulate = opts [ :accumulate ] send ( :define_singleton_method , name ) do | * args | nvar = "@#{name}" . intern current = instance_variable_get ( nvar ) envk = "POLISHER_#{name.to_s.upcase}" if accumulate instanc...
Defines a config attribute or attribute on the class which this is defined in . Accessors to the single shared attribute will be added to the class as well as instances of the class . Specify the default value with the attr name or via an env variable
20,140
def lookup ( object , key , opts , & block ) if ! block . nil? define ( object , key , opts , & block ) elsif key =~ / / if AridCache . store . has? ( object , $1 ) method_for_cached ( object , $1 , :fetch_count , key ) elsif object . respond_to? ( key ) define ( object , key , opts , :fetch_count ) elsif object . resp...
Lookup something from the cache .
20,141
def define ( object , key , opts , fetch_method = :fetch , method_name = nil , & block ) blueprint = AridCache . store . add_object_cache_configuration ( object , key , nil , block ) method_for_cached ( object , key , fetch_method , method_name ) blueprint end
Store the options and optional block for a call to the cache .
20,142
def class_name ( object , * modifiers ) name = object . is_a? ( Class ) ? object . name : object . class . name name = 'AnonymousClass' if name . nil? while modifier = modifiers . shift case modifier when :downcase name = name . downcase when :pluralize name = AridCache :: Inflector . pluralize ( name ) else raise Argu...
Return the object s class name .
20,143
def authorized? trace 'authorized?' , 0 , "@user: #{@user.inspect}, @action: #{@action.inspect}, @klass: #{@klass.inspect}, @subject: #{@subject.inspect}, @parent: #{@parent.inspect}" if params_handler = ( user && ( permission_by_role || permission_by_member_role ) ) params_handler = params_handler_default ( params_han...
Initializes the permission object
20,144
def permission_by_member_role m = members_role trace 'authorize_by_member_role?' , 0 , "#{user.try(:name)}:#{m}" p = member_permissions [ m ] trace 'authorize_by_role?' , 1 , "permissions: #{p.inspect}" p && authorization ( p ) end
Checks is a member is authorized You will need to implement members_role in permissions yourself
20,145
def state ( args = { } ) return :available if koji_state ( args ) == :available state = distgit_state ( args ) return :needs_repo if state == :missing_repo return :needs_branch if state == :missing_branch return :needs_spec if state == :missing_spec return :needs_build if state == :available return :needs_update end
Return the state of the gem as inferred by the targets which there are versions for .
20,146
def entries Dir . entries ( source ) . sort . each_with_object ( [ ] ) do | entry , buffer | buffer << source . join ( entry ) if valid_entry? ( entry ) end end
Return a list of all recognized files .
20,147
def valid_directory? ( entry ) File . directory? ( source . join ( entry ) ) && ! IGNORE_DIR . include? ( File . basename ( entry ) ) end
Check if path is a valid directory .
20,148
def valid_file? ( entry ) ext = File . extname ( entry ) . gsub ( / \. / , "" ) . downcase File . file? ( source . join ( entry ) ) && EXTENSIONS . include? ( ext ) && entry !~ IGNORE_FILES end
Check if path is a valid file .
20,149
def validate is_valid = true pages . each do | page | is_valid = false if page . invalid? end is_valid end
Entire form validation . Loops through the form pages and validates each page individually .
20,150
def values active_elements = elements . select do | _ , el | el . is_a? Elements :: Base :: ActiveElement end active_elements . each_with_object ( { } ) do | ( name , el ) , o | o [ name . to_sym ] = el . value end end
Create a hash of form elements values
20,151
def install ( manifest = 'manifest.yml' ) unless File . exist? manifest logger . fatal { "Manifest file '#{manifest}' does not exist." } return false end collection . load_manifest manifest result = options [ :dryrun ] ? collection . install? : collection . install msg = install_message ( result , options [ :dryrun ] )...
Installs the collection .
20,152
def number_to_size ( number , options = { } ) return if number == 0.0 / 1.0 return if number == 1.0 / 0.0 singular = options [ :singular ] || 1 base = options [ :base ] || 1024 units = options [ :units ] || [ "byte" , "kilobyte" , "megabyte" , "gigabyte" , "terabyte" , "petabyte" ] exponent = ( Math . log ( number ) / ...
Convert a number to a human readable size .
20,153
def exchange_code ( jwt_token : ) json_body_str = JSON . generate ( 'authToken' => jwt_token ) response = HTTParty . post ( "#{BASE_URL}/#{@config.env}/#{AUTH_CODE_PATH}" , headers : { 'Content-Type' => MIMETYPE_JSON , 'Accept' => MIMETYPE_JSON , 'Content-Length' => json_body_str . size . to_s , 'Authorization' => auth...
Creates a client
20,154
def skip? return false unless has_group? return true if group . any_true? ( skip_if ) return true unless group . all_true? ( only_if ) false end
Returns true if this field should not be processed because of the conditionals
20,155
def resolvers @resolvers ||= from . merge ( default : self ) . map { | origin , hint | { origin : origin , hint : hint , resolver : ( ( has_group? && group . resolvers [ origin ] ) || Resolver . for ( origin ) ) } } end
Accessor to defined resolvers for this option .
20,156
def rescue_action_locally ( request , exception ) rescue_actions = Hash . new ( 'diagnostics' ) rescue_actions . update ( { 'ActionView::MissingTemplate' => 'missing_template' , 'ActionController::RoutingError' => 'routing_error' , 'AbstractController::ActionNotFound' => 'unknown_action' , 'ActionView::Template::Error'...
Render detailed diagnostics for unhandled exceptions rescued from a controller action .
20,157
def find_resource_in_modules ( resource_name , ancestors ) if namespace = ancestors . detect { | a | a . constants . include? ( resource_name . to_sym ) } return namespace . const_get ( resource_name ) else raise NameError , "Namespace for #{namespace} not found" end end
Searches each module in + ancestors + for members named + resource_name + Returns the named resource Throws a NameError if none of the resources in the list contains + resource_name +
20,158
def find_or_create_resource_for ( name ) resource_name = name . to_s . gsub ( / \- / , '' ) . gsub ( / \- \d / , "n#{$1}" ) . gsub ( / \s / , '' ) . camelize if self . class . parents . size > 1 find_resource_in_modules ( resource_name , self . class . parents ) else self . class . const_get ( resource_name ) end rescu...
Searches the GovKit module for a resource with the name + name + cleaned and camelized Returns that resource . If the resource isn t found it s created .
20,159
def command! ( commands ) command = nil command_index = 0 each_with_index do | arg , i | break if arg == '--' command = commands [ arg . to_sym ] unless command . nil? command_index = i delete_at i break end end delete '--' command ||= commands [ :__default ] return command , command_index end
Gets the command to use from the list of arguments passed to the application . The first argument matching a command name or alias will cause the corresponding command to be selected .
20,160
def expand! each_with_index do | arg , i | next if ! arg . start_with? ( '-' ) self [ i ] = arg . split ( '=' , 2 ) next if arg . start_with? ( '--' ) self [ i ] = arg [ 1 .. - 1 ] . split ( '' ) . uniq . map { | a | '-' + a } end flatten! end
Turns arguments using a special syntax into arguments that are parseable .
20,161
def params! ( params , pos = 0 ) active_params = [ ] to_delete = [ ] each_with_index do | arg , i | next if i < pos || arg . nil? || ! arg . start_with? ( '-' ) param = params [ ( arg . start_with? ( '--' ) ? arg [ 2 .. - 1 ] : arg [ 1 .. 1 ] ) . to_sym ] unless param . nil? to_delete << i scoped_args! param , i + 1 if...
Selects active parameters from a list of available parameters
20,162
def scoped_args! ( has_args , pos = 0 ) to_delete = [ ] each_with_index do | arg , i | next if i < pos break if arg . start_with? ( '-' ) || ! has_args . send ( :more_args? ) to_delete << i has_args . send ( :<< , arg ) end to_delete . reverse . each { | i | delete_at i } end
Gets all arguments passed to a specific scope i . e . a command or an option .
20,163
def solve ( failure_message = "No solution." ) amb = self . new yield ( amb ) rescue Amb :: ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb . report ( failure_message ) end
Class convenience method to search for the first solution to the constraints .
20,164
def solve_all ( failure_message = "No more solutions." ) amb = self . new yield ( amb ) amb . failure rescue Amb :: ExhaustedError => ex puts puts "#{amb.branches_count} branches explored." if $DEBUG amb . report ( failure_message ) end
Class convenience method to search for all the solutions to the constraints .
20,165
def calculate_block_size char_amount = 1 base_length = @oracle . encipher ( DUMMY * char_amount ) . length result = nil ( 1 .. MAX_KNOWN_BLOCK_LENGTH ) . each do | length | new_length = @oracle . encipher ( DUMMY * char_amount ) . length if new_length > base_length result = new_length - base_length break end char_amoun...
calculate the block size by detecting the growth of the resulting ciphertext by sending messages which length increases by one until a change occurs
20,166
def string_encoder return string if string . valid_encoding? str = string Encoding . list . each do | e | begin str . force_encoding ( e . name ) tmp_string = str . encode ( 'UTF-8' ) return tmp_string if tmp_string . valid_encoding? rescue Rails . logger . debug { "Rescue -> #{e.name}" } if defined? ( :: Rails ) end e...
Funzione di encoding semplice
20,167
def get_feedback tokens = [ ] begin setup_ssl ( true ) rescue SocketError => e puts "Error: #{e}" return tokens end if IO . select ( [ @ssl ] , nil , nil , 1 ) while ( line = @ssl . read ( 38 ) ) f = line . unpack ( 'N1n1H64' ) time = Time . at ( f [ 0 ] ) token = f [ 2 ] . scan ( / / ) . join ( ' ' ) tokens << token e...
Calls the APNS feedback service and returns an array of expired push tokens
20,168
def generate_page_link page_number url = core__add_param_to_url ( @args [ :url ] , @args [ :param ] , page_number ) if @args [ :extra_params ] @args [ :extra_params ] . each do | key , value | url = core__add_param_to_url ( url , key , value ) end end url end
This function generate the link to go to a specific page number
20,169
def inflate! ( by_w , by_h = nil ) return inflate_by_size ( by_w ) if by_w . respond_to? :width validate ( by_w , by_h ) @width += by_w @height += by_h self end
INcrease the dimensions of the current Size in the width direction by + by_w + and in the height direction by + by_h + .
20,170
def deflate! ( by_w , by_h = nil ) if by_w . respond_to? :width inflate! ( - by_w . width , - by_w . height ) else inflate! ( - by_w , - by_h ) end end
DEcrease the dimensions of the current Size in the width direction by + by_w + and in the height direction by + by_h + .
20,171
def inflate_by_size ( sz ) width = sz . width height = sz . height validate ( width , height ) @width += width @height += height self end
Change the dimensions using the dimensions of another Size .
20,172
def core__get_application_gems gems = { } Bundler . load . specs . each do | spec | gems [ spec . name ] = spec . version end gems end
This function return the list of gems used by the application .
20,173
def core__get_application_logo_sidebar_path dir = "#{core__get_application_root_path}/app/assets/images/lato/" if File . exist? ( "#{dir}/logo_sidebar.svg" ) return 'lato/logo_sidebar.svg' elsif File . exist? ( "#{dir}/logo_sidebar.png" ) return 'lato/logo_sidebar.png' elsif File . exist? ( "#{dir}/logo_sidebar.jpg" ) ...
This function return the path of the application logo for the sidebar .
20,174
def help ( show_usage = true ) help = '' if show_usage help << " #{name}" if name != :__default @params . values . uniq . sort_by { | a | a . name . to_s } . each do | param | help << ' [' ( [ param . name ] + param . aliases ) . each_with_index do | name , index | name = name . to_s help << '|' if index > 0 help << '-...
Create a new application command with the given name with a reference to the app it belongs to
20,175
def add_param ( parameter ) if parameter . is_a? Hash parameter . each do | alias_name , name | alias_name = alias_name . to_sym name = name . to_sym parameter = @params [ name ] if parameter . nil? @params [ alias_name ] = name else parameter . aliases << alias_name @params [ alias_name ] = parameter end end else rais...
Add a new parameter for this command
20,176
def method_missing ( name , * args , & block ) if args . empty? && ! block_given? if @params . key? ( name ) return @params [ name ] else active_params . each do | param | return param . send ( name ) if param . respond_to_missing? ( name ) end end end super end
If a parameter with the specified method name exists a call to that method will return the value of the parameter .
20,177
def reset super @params . values . uniq . each do | param | param . send ( :reset ) if param . is_a? Parameter end end
Resets this command to its initial state
20,178
def respond_to_missing? ( name , include_private = false ) @params . key? ( name ) || active_params . any? { | param | param . respond_to_missing? ( name ) } || super end
Checks whether a parameter with the given name exists for this command
20,179
def validations name = @name @klass . send ( :validates_each , name ) do | record , attr , value | record . send ( name ) . errors . each do | error | record . errors . add ( name , error ) end end end
Forward validations .
20,180
def on_any_path? ( paths ) path_found = false paths . each do | path | path_found = on_path? ( path ) ? true : path_found end return path_found end
a modification of the on path method to check if we are on any of the defined request or callback paths . tests each of the provided paths to see if we are on it .
20,181
def save self . queue . each do | style , file | path = self . path ( style ) self . storage . save ( file , path ) if file and path end self . purge . each do | path | self . storage . destroy ( path ) end @purge = [ ] @queue = { } end
Save an attachment .
20,182
def destroy if attached? self . storage . destroy ( self . path ) self . styles . each do | style , options | self . storage . destroy ( self . path ( style ) ) end end @purge = [ ] @queue = { } end
Destroy an attachment .
20,183
def url ( style = self . default ) path = self . path ( style ) host = self . host host = self . aliases [ path . hash % self . aliases . count ] unless self . aliases . empty? return "#{host}#{path}" end
Acesss the URL for an attachment .
20,184
def path ( style = self . default ) path = self . attached? ? @path . clone : @missing . clone path . gsub! ( / / , name . to_s ) path . gsub! ( / / , style . to_s ) path . gsub! ( / / , extension ( style ) . to_s ) path . gsub! ( / / , identifier ( style ) . to_s ) return path end
Access the path for an attachment .
20,185
def add ( client_id , ip_address ) @clients << { client_id : client_id , ip_address : ip_address } GameOverseer :: Services . client_connected ( client_id , ip_address ) GameOverseer :: Console . log ( "ClientManager> client with id '#{client_id}' connected" ) end
Add client to clients list
20,186
def remove ( client_id ) @clients . each do | hash | if hash [ :client_id ] == client_id @clients . delete ( hash ) GameOverseer :: Services . client_disconnected ( client_id ) GameOverseer :: Console . log ( "ClientManager> client with id '#{client_id}' disconnected" ) end end end
Removes client data and disconnects client
20,187
def create_table ( table_name , options = { } ) table_definition = TableDefinition . new table_definition . define_primary_keys ( options [ :primary_keys ] ) if options [ :primary_keys ] table_definition . define_partition_keys ( options [ :partition_keys ] ) if options [ :partition_keys ] table_definition . define_opt...
Creates a new table in the keyspace
20,188
def transmit ( client_id , message , reliable = false , channel = ChannelManager :: CHAT ) @server . send_packet ( client_id , message , reliable , channel ) end
send message to a specific client
20,189
def broadcast ( message , reliable = false , channel = ChannelManager :: CHAT ) @server . broadcast_packet ( message , reliable , channel ) end
send message to all connected clients
20,190
def bump ( oldversion , level ) major = minor = patch = 0 if oldversion =~ / \d \. \d \. \d / major = Regexp . last_match ( 1 ) . to_i minor = Regexp . last_match ( 2 ) . to_i patch = Regexp . last_match ( 3 ) . to_i end case level . to_sym when :major major += 1 minor = 0 patch = 0 when :minor minor += 1 patch = 0 whe...
Return a new version number based on
20,191
def expects ( & block ) builder = ExpectationBuilder . new builder . instance_eval ( & block ) parameter_validations . concat builder . parameter_validations parameters_to_filter . concat builder . parameters_to_filter end
Defines the input parameters expected for this API action .
20,192
def responds_with ( ** args , & block ) builder = FilterBuilder . new builder . instance_eval ( & block ) response_filters . concat ( builder . response_filters ) response_formatters . concat ( builder . response_formatters ) if args [ :unnested_hash ] response_formatters << lambda do | _ , response | if response . is_...
Defines the expected content and format of the response for this API action .
20,193
def really_continue? ( default_answer = 'Yes' ) return if FalkorLib . config [ :no_interaction ] pattern = ( default_answer =~ / /i ) ? '(Y|n)' : '(y|N)' answer = ask ( cyan ( "=> Do you really want to continue #{pattern}?" ) , default_answer ) exit 0 if answer =~ / /i end
Ask whether or not to really continue
20,194
def nice_execute ( cmd ) puts bold ( "[Running] #{cmd.gsub(/^\s*/, ' ')}" ) stdout , stderr , exit_status = Open3 . capture3 ( cmd ) unless stdout . empty? stdout . each_line do | line | print "** [out] #{line}" $stdout . flush end end unless stderr . empty? stderr . each_line do | line | $stderr . print red ( "** [err...
Execute a given command return exit code and print nicely stdout and stderr
20,195
def execute_in_dir ( path , cmd ) exit_status = 0 Dir . chdir ( path ) do exit_status = run %( #{cmd} ) end exit_status end
Execute in a given directory
20,196
def exec_or_exit ( cmd ) status = execute ( cmd ) if ( status . to_i . nonzero? ) error ( "The command '#{cmd}' failed with exit status #{status.to_i}" ) end status end
execute_in_dir Execute a given command - exit if status ! = 0
20,197
def select_from ( list , text = 'Select the index' , default_idx = 0 , raw_list = list ) error "list and raw_list differs in size" if list . size != raw_list . size l = list raw_l = raw_list if list . is_a? ( Array ) l = raw_l = { 0 => 'Exit' } list . each_with_index do | e , idx | l [ idx + 1 ] = e raw_l [ idx + 1 ] =...
Display a indexed list to select an i
20,198
def init_rvm ( rootdir = Dir . pwd , gemset = '' ) rvm_files = { :version => File . join ( rootdir , '.ruby-version' ) , :gemset => File . join ( rootdir , '.ruby-gemset' ) } unless File . exist? ( ( rvm_files [ :version ] ) . to_s ) v = select_from ( FalkorLib . config [ :rvm ] [ :rubies ] , "Select RVM ruby to config...
copy_from_template RVM init
20,199
def select_licence ( default_licence = FalkorLib :: Config :: Bootstrap :: DEFAULTS [ :metadata ] [ :license ] , _options = { } ) list_license = FalkorLib :: Config :: Bootstrap :: DEFAULTS [ :licenses ] . keys idx = list_license . index ( default_licence ) unless default_licence . nil? select_from ( list_license , 'Se...
select_forge select_licence Select a given licence for the project