idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
4,600
def tag ( name ) tags . find { | tag | tag . tag_name . to_s == name . to_s } end
Convenience method to return the first tag object in the list of tag objects of that name
4,601
def tags ( name = nil ) list = stable_sort_by ( @tags + convert_ref_tags , & :tag_name ) return list unless name list . select { | tag | tag . tag_name . to_s == name . to_s } end
Returns a list of tags specified by + name + or all tags if + name + is not specified .
4,602
def has_tag? ( name ) tags . any? { | tag | tag . tag_name . to_s == name . to_s } end
Returns true if at least one tag by the name + name + was declared
4,603
def blank? ( only_visible_tags = true ) if only_visible_tags empty? && ! tags . any? { | tag | Tags :: Library . visible_tags . include? ( tag . tag_name . to_sym ) } else empty? && @tags . empty? && @ref_tags . empty? end end
Returns true if the docstring has no content that is visible to a template .
4,604
def convert_ref_tags list = @ref_tags . reject { | t | CodeObjects :: Proxy === t . owner } @ref_tag_recurse_count ||= 0 @ref_tag_recurse_count += 1 if @ref_tag_recurse_count > 2 log . error "#{@object.file}:#{@object.line}: Detected circular reference tag in " "`#{@object}', ignoring all reference tags for this object...
Maps valid reference tags
4,605
def parse_comments ( comments ) parser = self . class . parser parser . parse ( comments , object ) @all = parser . raw_text @unresolved_reference = parser . reference add_tag ( * parser . tags ) parser . text end
Parses out comments split by newlines into a new code object
4,606
def stable_sort_by ( list ) list . each_with_index . sort_by { | tag , i | [ yield ( tag ) , i ] } . map ( & :first ) end
A stable sort_by method .
4,607
def inheritance_tree ( include_mods = false ) return [ self ] unless include_mods [ self ] + mixins ( :instance , :class ) . map do | m | next if m == self next m unless m . respond_to? ( :inheritance_tree ) m . inheritance_tree ( true ) end . compact . flatten . uniq end
Returns the inheritance tree of mixins .
4,608
def child ( opts = { } ) if ! opts . is_a? ( Hash ) children . find { | o | o . name == opts . to_sym } else opts = SymbolHash [ opts ] children . find do | obj | opts . each do | meth , value | break false unless value . is_a? ( Array ) ? value . include? ( obj [ meth ] ) : obj [ meth ] == value end end end end
Looks for a child that matches the attributes specified by + opts + .
4,609
def meths ( opts = { } ) opts = SymbolHash [ :visibility => [ :public , :private , :protected ] , :scope => [ :class , :instance ] , :included => true ] . update ( opts ) opts [ :visibility ] = [ opts [ :visibility ] ] . flatten opts [ :scope ] = [ opts [ :scope ] ] . flatten ourmeths = children . select do | o | o . i...
Returns all methods that match the attributes specified by + opts + . If no options are provided returns all methods .
4,610
def included_meths ( opts = { } ) opts = SymbolHash [ :scope => [ :instance , :class ] ] . update ( opts ) [ opts [ :scope ] ] . flatten . map do | scope | mixins ( scope ) . inject ( [ ] ) do | list , mixin | next list if mixin . is_a? ( Proxy ) arr = mixin . meths ( opts . merge ( :scope => :instance ) ) . reject do ...
Returns methods included from any mixins that match the attributes specified by + opts + . If no options are specified returns all included methods .
4,611
def constants ( opts = { } ) opts = SymbolHash [ :included => true ] . update ( opts ) consts = children . select { | o | o . is_a? ConstantObject } consts + ( opts [ :included ] ? included_constants : [ ] ) end
Returns all constants in the namespace
4,612
def included_constants instance_mixins . inject ( [ ] ) do | list , mixin | if mixin . respond_to? :constants list += mixin . constants . reject do | o | child ( :name => o . name ) || list . find { | o2 | o2 . name == o . name } end else list end end end
Returns constants included from any mixins
4,613
def remove_cert ( cert ) der = cert . to_der query = %(DELETE FROM "tsettings" WHERE sha1 = #{blobify(sha1_from_der(der))};) begin db = SQLite3 :: Database . new ( @db_path ) db . execute ( query ) db . close rescue StandardError => e raise "[*] Error writing to SQLite database at #{@db_path}: #{e.message}" end end
performs uninstall based on sha1 hash provided in certfile
4,614
def impressionist_count ( options = { } ) options . reverse_merge! ( :filter => :request_hash , :start_date => nil , :end_date => Time . now ) imps = options [ :start_date ] . blank? ? impressions : impressions . where ( "created_at >= ? and created_at <= ?" , options [ :start_date ] , options [ :end_date ] ) if option...
end of ClassMethods
4,615
def impressionist_count ( options = { } ) options . reverse_merge! ( :filter => :request_hash , :start_date => nil , :end_date => Time . now ) imps = options [ :start_date ] . blank? ? impressions : impressions . between ( created_at : options [ :start_date ] .. options [ :end_date ] ) distinct = options [ :filter ] !=...
Overides impressionist_count in order to provide mongoid compability
4,616
def associative_create_statement ( query_params = { } ) filter = ActionDispatch :: Http :: ParameterFilter . new ( Rails . application . config . filter_parameters ) query_params . reverse_merge! ( :controller_name => controller_name , :action_name => action_name , :user_id => user_id , :request_hash => @impressionist_...
creates a statment hash that contains default values for creating an impression via an AR relation .
4,617
def unique_query ( unique_opts , impressionable = nil ) full_statement = direct_create_statement ( { } , impressionable ) unique_opts . reduce ( { } ) do | query , param | query [ param ] = full_statement [ param ] query end end
creates the query to check for uniqueness
4,618
def direct_create_statement ( query_params = { } , impressionable = nil ) query_params . reverse_merge! ( :impressionable_type => controller_name . singularize . camelize , :impressionable_id => impressionable . present? ? impressionable . id : params [ :id ] ) associative_create_statement ( query_params ) end
creates a statment hash that contains default values for creating an impression .
4,619
def capitalize_keys ( hsh ) capitalized_hash = { } hsh . each_pair { | k , v | capitalized_hash [ k . to_s . upcase ] = v } capitalized_hash end
Capitalizes the keys of a hash
4,620
def execute ( call_sig , req , metadata , opts = { } , & block ) operation = nil result = Gruf :: Timer . time do opts [ :return_op ] = true opts [ :metadata ] = metadata operation = send ( call_sig , req , opts , & block ) operation . execute end [ result , operation ] end
Execute the given request to the service
4,621
def request_object ( request_method , params = { } ) desc = rpc_desc ( request_method ) desc &. input ? desc . input . new ( params ) : nil end
Get the appropriate protobuf request message for the given request method on the service being called
4,622
def build_metadata ( metadata = { } ) unless opts [ :password ] . empty? username = opts . fetch ( :username , 'grpc' ) . to_s username = username . empty? ? '' : "#{username}:" auth_string = Base64 . encode64 ( "#{username}#{opts[:password]}" ) metadata [ :authorization ] = "Basic #{auth_string}" . tr ( "\n" , '' ) en...
Build a sanitized authenticated metadata hash for the given request
4,623
def build_operation ( options = { } ) double ( :operation , { execute : true , metadata : { } , trailing_metadata : { } , deadline : Time . now . to_i + 600 , cancelled? : false , execution_time : rand ( 1_000 .. 10_000 ) } . merge ( options ) ) end
Build a gRPC operation stub for testing
4,624
def run_server ( server ) grpc_server = server . server t = Thread . new { grpc_server . run } grpc_server . wait_till_running begin yield ensure grpc_server . stop sleep ( 0.1 ) until grpc_server . stopped? t . join end end
Runs a server
4,625
def add_field_error ( field_name , error_code , message = '' ) @field_errors << Errors :: Field . new ( field_name , error_code , message ) end
Initialize the error setting default values
4,626
def attach_to_call ( active_call ) metadata [ Gruf . error_metadata_key . to_sym ] = serialize if Gruf . append_server_errors_to_trailing_metadata return self if metadata . empty? || ! active_call || ! active_call . respond_to? ( :output_metadata ) if metadata . inspect . size > MAX_METADATA_SIZE code = METADATA_SIZE_E...
Update the trailing metadata on the given gRPC call including the error payload if configured to do so .
4,627
def to_h { code : code , app_code : app_code , message : message , field_errors : field_errors . map ( & :to_h ) , debug_info : debug_info . to_h } end
Return the error represented in Hash form
4,628
def serializer_class if Gruf . error_serializer Gruf . error_serializer . is_a? ( Class ) ? Gruf . error_serializer : Gruf . error_serializer . to_s . constantize else Gruf :: Serializers :: Errors :: Json end end
Return the error serializer being used for gruf
4,629
def server @server_mu . synchronize do @server ||= begin server_options = { pool_size : options . fetch ( :pool_size , Gruf . rpc_server_options [ :pool_size ] ) , max_waiting_requests : options . fetch ( :max_waiting_requests , Gruf . rpc_server_options [ :max_waiting_requests ] ) , poll_period : options . fetch ( :po...
Initialize the server and load and setup the services
4,630
def start! update_proc_title ( :starting ) server_thread = Thread . new do logger . info { "Starting gruf server at #{@hostname}..." } server . run end stop_server_thread = Thread . new do loop do break if @stop_server @stop_server_mu . synchronize { @stop_server_cv . wait ( @stop_server_mu , 10 ) } end logger . info {...
Start the gRPC server
4,631
def insert_interceptor_before ( before_class , interceptor_class , opts = { } ) raise ServerAlreadyStartedError if @started @interceptors . insert_before ( before_class , interceptor_class , opts ) end
Insert an interceptor before another in the currently registered order of execution
4,632
def insert_interceptor_after ( after_class , interceptor_class , opts = { } ) raise ServerAlreadyStartedError if @started @interceptors . insert_after ( after_class , interceptor_class , opts ) end
Insert an interceptor after another in the currently registered order of execution
4,633
def options opts = { } VALID_CONFIG_KEYS . each_key do | k | opts . merge! ( k => send ( k ) ) end opts end
Return the current configuration options as a Hash
4,634
def reset VALID_CONFIG_KEYS . each do | k , v | send ( ( k . to_s + '=' ) , v ) end self . interceptors = Gruf :: Interceptors :: Registry . new self . root_path = Rails . root . to_s . chomp ( '/' ) if defined? ( Rails ) if defined? ( Rails ) && Rails . logger self . logger = Rails . logger else require 'logger' self ...
Set the default configuration onto the extended class
4,635
def fallback! ( controller , entity ) throw ( :warden , scope : entity . name_underscore . to_sym ) if controller . send ( "current_#{entity.name_underscore}" ) . nil? end
Notifies the failure of authentication to Warden in the same Devise does . Does result in an HTTP 401 response in a Devise context .
4,636
def verify_host_key_option current_net_ssh = Net :: SSH :: Version :: CURRENT new_option_version = Net :: SSH :: Version [ 4 , 2 , 0 ] current_net_ssh >= new_option_version ? :verify_host_key : :paranoid end
Returns the correct host - key - verification option key to use depending on what version of net - ssh is in use . In net - ssh < = 4 . 1 the supported parameter is paranoid but in 4 . 2 it became verify_host_key
4,637
def create_new_connection ( options , & block ) if defined? ( @connection ) logger . debug ( "[SSH] shutting previous connection #{@connection}" ) @connection . close end @connection_options = options conn = Connection . new ( options , & block ) if defined? ( conn . platform . cisco_ios? ) && conn . platform . cisco_i...
Creates a new SSH Connection instance and save it for potential future reuse .
4,638
def perform_checksum_ruby ( method ) @ruby_checksum_fallback = true case method when :md5 res = Digest :: MD5 . new when :sha256 res = Digest :: SHA256 . new end res . update ( content ) res . hexdigest rescue TypeError => _ nil end
This pulls the content of the file to the machine running Train and uses Digest to perform the checksum . This is less efficient than using remote system binaries and can lead to incorrect results due to encoding .
4,639
def create_new_connection ( options , & block ) if @connection logger . debug ( "[WinRM] shutting previous connection #{@connection}" ) @connection . close end @connection_options = options @connection = Connection . new ( options , & block ) end
Creates a new WinRM Connection instance and save it for potential future reuse .
4,640
def in_family ( family ) if self . class == Train :: Platforms :: Family && @name == family fail "Unable to add family #{@name} to itself: '#{@name}.in_family(#{family})'" end family = Train :: Platforms . family ( family ) family . children [ self ] = @condition @families [ family ] = @condition @condition = nil self ...
Add a family connection . This will create a family if it does not exist and add a child relationship .
4,641
def sudo_wrap ( cmd ) return cmd unless @sudo return cmd if @user == 'root' res = ( @sudo_command || 'sudo' ) + ' ' res = "#{safe_string(@sudo_password + "\n")} | #{res}-S " unless @sudo_password . nil? res << @sudo_options . to_s + ' ' unless @sudo_options . nil? res + cmd end
wrap the cmd in a sudo command
4,642
def powershell_wrap ( cmd ) shell = @shell_command || 'powershell' script = "$ProgressPreference='SilentlyContinue';" + cmd script = script . encode ( 'UTF-16LE' , 'UTF-8' ) base64_script = Base64 . strict_encode64 ( script ) cmd = "#{shell} -NoProfile -EncodedCommand #{base64_script}" cmd end
Wrap the cmd in an encoded command to allow pipes and quotes
4,643
def scan top = Train :: Platforms . top_platforms top . each do | _name , plat | next unless instance_eval ( & plat . detect ) == true plat_result = scan_children ( plat ) next if plat_result . nil? @family_hierarchy << plat . name return get_platform ( plat_result ) end fail Train :: PlatformDetectionFailed , 'Sorry, ...
Main detect method to scan all platforms for a match
4,644
def add_platform_methods clean_name ( force : true ) unless @platform [ :name ] . nil? family_list = Train :: Platforms . families family_list . each_value do | k | next if respond_to? ( k . name + '?' ) define_singleton_method ( k . name + '?' ) do family_hierarchy . include? ( k . name ) end end @platform . each_key ...
Add generic family? and platform methods to an existing platform
4,645
def read_wmic res = @backend . run_command ( 'wmic os get * /format:list' ) if res . exit_status == 0 sys_info = { } res . stdout . lines . each { | line | m = / \s \s \s \s / . match ( line ) sys_info [ m [ 1 ] . to_sym ] = m [ 2 ] unless m . nil? || m [ 1 ] . nil? } @platform [ :release ] = sys_info [ :Version ] @pla...
reads os name and version from wmic
4,646
def read_wmic_cpu res = @backend . run_command ( 'wmic cpu get architecture /format:list' ) if res . exit_status == 0 sys_info = { } res . stdout . lines . each { | line | m = / \s \s \s \s / . match ( line ) sys_info [ m [ 1 ] . to_sym ] = m [ 2 ] unless m . nil? || m [ 1 ] . nil? } end arch_map = { 0 => 'i386' , 1 =>...
OSArchitecture from read_wmic does not match a normal standard For example x86_64 shows as 64 - bit
4,647
def windows_uuid uuid = windows_uuid_from_chef uuid = windows_uuid_from_machine_file if uuid . nil? uuid = windows_uuid_from_wmic if uuid . nil? uuid = windows_uuid_from_registry if uuid . nil? raise Train :: TransportError , 'Cannot find a UUID for your node.' if uuid . nil? uuid end
This method scans the target os for a unique uuid to use
4,648
def platform Train :: Platforms . name ( 'local-rot13' ) . in_family ( 'unix' ) Train :: Platforms . name ( 'local-rot13' ) . in_family ( 'windows' ) force_platform! ( 'local-rot13' , release : TrainPlugins :: LocalRot13 :: VERSION ) end
The method platform is called when platform detection is about to be performed . Train core defines a sophisticated system for platform detection but for most plugins you ll only ever run on the special platform for which you are targeting .
4,649
def uuid_from_command return unless @platform [ :uuid_command ] result = @backend . run_command ( @platform [ :uuid_command ] ) uuid_from_string ( result . stdout . chomp ) if result . exit_status . zero? && ! result . stdout . empty? end
This takes a command from the platform detect block to run . We expect the command to return a unique identifier which we turn into a UUID .
4,650
def uuid_from_string ( string ) hash = Digest :: SHA1 . new hash . update ( string ) ary = hash . digest . unpack ( 'NnnnnN' ) ary [ 2 ] = ( ary [ 2 ] & 0x0FFF ) | ( 5 << 12 ) ary [ 3 ] = ( ary [ 3 ] & 0x3FFF ) | 0x8000 '%08x-%04x-%04x-%04x-%04x%08x' % ary end
This hashes the passed string into SHA1 . Then it downgrades the 160bit SHA1 to a 128bit then we format it as a valid UUIDv5 .
4,651
def playlists ( limit : 20 , offset : 0 , ** options ) url = "browse/categories/#{@id}/playlists" "?limit=#{limit}&offset=#{offset}" options . each do | option , value | url << "&#{option}=#{value}" end response = RSpotify . get ( url ) return response if RSpotify . raw_response response [ 'playlists' ] [ 'items' ] . m...
Get a list of Spotify playlists tagged with a particular category .
4,652
def play ( device_id = nil , params = { } ) url = "me/player/play" url = device_id . nil? ? url : "#{url}?device_id=#{device_id}" User . oauth_put ( @user . id , url , params . to_json ) end
Play the user s currently active player or specific device If device_id is not passed the currently active spotify app will be triggered
4,653
def repeat ( device_id : nil , state : "context" ) url = "me/player/repeat" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User . oauth_put ( @user . id , url , { } ) end
Toggle the current user s player repeat status . If device_id is not passed the currently active spotify app will be triggered . If state is not passed the currently active context will be set to repeat .
4,654
def shuffle ( device_id : nil , state : true ) url = "me/player/shuffle" url += "?state=#{state}" url += "&device_id=#{device_id}" if device_id User . oauth_put ( @user . id , url , { } ) end
Toggle the current user s shuffle status . If device_id is not passed the currently active spotify app will be triggered . If state is not passed shuffle mode will be turned on .
4,655
def tracks ( limit : 50 , offset : 0 , market : nil ) last_track = offset + limit - 1 if @tracks_cache && last_track < 50 && ! RSpotify . raw_response return @tracks_cache [ offset .. last_track ] end url = "albums/#{@id}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify ....
Returns array of tracks from the album
4,656
def albums ( limit : 20 , offset : 0 , ** filters ) url = "artists/#{@id}/albums?limit=#{limit}&offset=#{offset}" filters . each do | filter_name , filter_value | url << "&#{filter_name}=#{filter_value}" end response = RSpotify . get ( url ) return response if RSpotify . raw_response response [ 'items' ] . map { | i | ...
Returns array of albums from artist
4,657
def top_tracks ( country ) return @top_tracks [ country ] unless @top_tracks [ country ] . nil? || RSpotify . raw_response response = RSpotify . get ( "artists/#{@id}/top-tracks?country=#{country}" ) return response if RSpotify . raw_response @top_tracks [ country ] = response [ 'tracks' ] . map { | t | Track . new t }...
Returns artist s 10 top tracks by country .
4,658
def tracks ( limit : 100 , offset : 0 , market : nil ) last_track = offset + limit - 1 if @tracks_cache && last_track < 100 && ! RSpotify . raw_response return @tracks_cache [ offset .. last_track ] end url = "#{@href}/tracks?limit=#{limit}&offset=#{offset}" url << "&market=#{market}" if market response = RSpotify . re...
Returns array of tracks from the playlist
4,659
def playlists ( limit : 20 , offset : 0 ) url = "users/#{@id}/playlists?limit=#{limit}&offset=#{offset}" response = RSpotify . resolve_auth_request ( @id , url ) return response if RSpotify . raw_response response [ 'items' ] . map { | i | Playlist . new i } end
Returns all playlists from user
4,660
def to_hash pairs = instance_variables . map do | var | [ var . to_s . delete ( '@' ) , instance_variable_get ( var ) ] end Hash [ pairs ] end
Returns a hash containing all user attributes
4,661
def devices url = "me/player/devices" response = RSpotify . resolve_auth_request ( @id , url ) return response if RSpotify . raw_response response [ 'devices' ] . map { | i | Device . new i } end
Returns the user s available devices
4,662
def relative_path path require 'pathname' full_path = Pathname . new ( path ) . realpath base_path = Pathname . new ( source_directory ) . realpath full_path . relative_path_from ( base_path ) . to_s end
Auxiliary methods Returns a relative path against source_directory .
4,663
def targets project_path = get_project_path return [ ] if project_path . nil? proj = Xcodeproj :: Project . open ( project_path ) proj . targets . map do | target | target . name end end
Returns project targets
4,664
def content file = @options [ 'template' ] || default_template if file file . sub! ( / \/ / , '' ) file = File . join ( site . source , '_templates' , file ) if file if File . exist? file parse_template File . open ( file ) . read . encode ( 'UTF-8' ) elsif @options [ 'template' ] abort "No #{@options['type']} template...
Load the user provided or default template for a new post or page .
4,665
def parse_template ( input ) if @config [ 'titlecase' ] @options [ 'title' ] . titlecase! end vars = @options . dup vars [ 'slug' ] = title_slug date = Time . parse ( vars [ 'date' ] || Time . now . iso8601 ) vars [ 'date' ] = date . iso8601 vars [ 'year' ] = date . year vars [ 'month' ] = date . strftime ( '%m' ) vars...
Render Liquid vars in YAML front - matter .
4,666
def title_slug value = ( @options [ 'slug' ] || @options [ 'title' ] ) . downcase value . gsub! ( / \x00 \x7F /u , '' ) value . gsub! ( / / , 'and' ) value . gsub! ( / / , '' ) value . gsub! ( / \W / , ' ' ) value . strip! value . gsub! ( ' ' , '-' ) value end
Returns a string which is url compatible .
4,667
def module_to_path ( mod , base = nil ) path = mod . gsub ( / \. / , :: File :: SEPARATOR ) + '.py' path = :: File . join ( base , path ) if base path end
Convert a Python dotted module name to a path .
4,668
def deregister ( io ) @lock . synchronize do monitor = @selectables . delete IO . try_convert ( io ) monitor . close ( false ) if monitor && ! monitor . closed? monitor end end
Deregister the given IO object from the selector
4,669
def select ( timeout = nil ) selected_monitors = Set . new @lock . synchronize do readers = [ @wakeup ] writers = [ ] @selectables . each do | io , monitor | readers << io if monitor . interests == :r || monitor . interests == :rw writers << io if monitor . interests == :w || monitor . interests == :rw monitor . readin...
Select which monitors are ready
4,670
def position = ( new_position ) raise ArgumentError , "negative position given" if new_position < 0 raise ArgumentError , "specified position exceeds capacity" if new_position > @capacity @mark = nil if @mark && @mark > new_position @position = new_position end
Set the position to the given value . New position must be less than limit . Preserves mark if it s less than the new position otherwise clears it .
4,671
def limit = ( new_limit ) raise ArgumentError , "negative limit given" if new_limit < 0 raise ArgumentError , "specified limit exceeds capacity" if new_limit > @capacity @position = new_limit if @position > new_limit @mark = nil if @mark && @mark > new_limit @limit = new_limit end
Set the limit to the given value . New limit must be less than capacity . Preserves limit and mark if they re less than the new limit otherwise sets position to the new limit and clears the mark .
4,672
def get ( length = remaining ) raise ArgumentError , "negative length given" if length < 0 raise UnderflowError , "not enough data in buffer" if length > @limit - @position result = @buffer [ @position ... length ] @position += length result end
Obtain the requested number of bytes from the buffer advancing the position . If no length is given all remaining bytes are consumed .
4,673
def put ( str ) raise TypeError , "expected String, got #{str.class}" unless str . respond_to? ( :to_str ) str = str . to_str raise OverflowError , "buffer is full" if str . length > @limit - @position @buffer [ @position ... str . length ] = str @position += str . length self end
Add a String to the buffer
4,674
def read_from ( io ) nbytes = @limit - @position raise OverflowError , "buffer is full" if nbytes . zero? bytes_read = IO . try_convert ( io ) . read_nonblock ( nbytes , exception : false ) return 0 if bytes_read == :wait_readable self << bytes_read bytes_read . length end
Perform a non - blocking read from the given IO object into the buffer Reads as much data as is immediately available and returns
4,675
def transaction ( force_sync = false , & block ) if @mutex . respond_to? ( :owned? ) force_sync = false if @mutex . locked? && @mutex . owned? else force_sync = false end if ! force_sync && ( @in_transaction || options [ :without_mutex ] ) block . call self else @mutex . synchronize do @in_transaction = true result = b...
Wraps block execution in a thread - safe transaction
4,676
def query = ( query ) raise ArgumentError , "Invalid URL: #{self.url}" unless self . url . respond_to? ( :query ) if query . kind_of? ( Hash ) query = build_query_from_hash ( query ) end query = query . to_s unless query . is_a? ( String ) self . url . query = query end
Sets the + query + from + url + . Raises an + ArgumentError + unless the + url + is valid .
4,677
def mass_assign ( args ) ATTRIBUTES . each { | key | send ( "#{key}=" , args [ key ] ) if args [ key ] } end
Expects a Hash of + args + to assign .
4,678
def normalize_url! ( url ) raise ArgumentError , "Invalid URL: #{url}" unless url . to_s =~ / / url . kind_of? ( URI ) ? url : URI ( url ) end
Expects a + url + validates its validity and returns a + URI + object .
4,679
def configure_record ( record , bytes ) byte = bytes . shift record . version = ( byte >> 3 ) & 31 record . first = ( byte >> 2 ) & 1 record . last = ( byte >> 1 ) & 1 record . chunked = byte & 1 record . type_format = ( bytes . shift >> 4 ) & 15 end
Shift out bitfields for the first fields .
4,680
def big_endian_lengths ( bytes ) lengths = [ ] lengths << [ :options , ( bytes . shift << 8 ) | bytes . shift ] lengths << [ :id , ( bytes . shift << 8 ) | bytes . shift ] lengths << [ :type , ( bytes . shift << 8 ) | bytes . shift ] lengths << [ :data , ( bytes . shift << 24 ) | ( bytes . shift << 16 ) | ( bytes . shi...
Fetch big - endian lengths .
4,681
def read_data ( record , bytes , attribute_set ) attribute , length = attribute_set content = bytes . slice! ( 0 , length ) . pack ( 'C*' ) if attribute == :data && record . type_format == BINARY content = StringIO . new ( content ) end record . send "#{attribute.to_s}=" , content bytes . slice! ( 0 , 4 - ( length & 3 ...
Read in padded data .
4,682
def decoded_gzip_body unless gzip = Zlib :: GzipReader . new ( StringIO . new ( raw_body ) ) raise ArgumentError , "Unable to create Zlib::GzipReader" end gzip . read ensure gzip . close if gzip end
Returns the gzip decoded response body .
4,683
def decoded_dime_body ( body = nil ) dime = Dime . new ( body || raw_body ) self . attachments = dime . binary_records dime . xml_records . first . data end
Returns the DIME decoded response body .
4,684
def load_lib_folder return false if Adhearsion . config . core . lib . nil? lib_folder = [ Adhearsion . config . core . root , Adhearsion . config . core . lib ] . join '/' return false unless File . directory? lib_folder $LOAD_PATH . unshift lib_folder Dir . chdir lib_folder do rbfiles = File . join "**" , "*.rb" Dir ...
Loads files in application lib folder
4,685
def tag ( label ) abort ArgumentError . new "Tag must be a String or Symbol" unless [ String , Symbol ] . include? ( label . class ) @tags << label end
Tag a call with an arbitrary label
4,686
def wait_for_end ( timeout = nil ) if end_reason end_reason else @end_blocker . wait ( timeout ) end rescue Celluloid :: ConditionError => e abort e end
Wait for the call to end . Returns immediately if the call has already ended else blocks until it does so .
4,687
def on_joined ( target = nil , & block ) register_event_handler Adhearsion :: Event :: Joined , * guards_for_target ( target ) do | event | block . call event end end
Registers a callback for when this call is joined to another call or a mixer
4,688
def on_unjoined ( target = nil , & block ) register_event_handler Adhearsion :: Event :: Unjoined , * guards_for_target ( target ) , & block end
Registers a callback for when this call is unjoined from another call or a mixer
4,689
def redirect ( to , headers = nil ) write_and_await_response Adhearsion :: Rayo :: Command :: Redirect . new ( to : to , headers : headers ) rescue Adhearsion :: ProtocolError => e abort e end
Redirect the call to some other target system .
4,690
def join ( target , options = { } ) logger . debug "Joining to #{target}" joined_condition = CountDownLatch . new ( 1 ) on_joined target do joined_condition . countdown! end unjoined_condition = CountDownLatch . new ( 1 ) on_unjoined target do unjoined_condition . countdown! end on_end do joined_condition . countdown! ...
Joins this call to another call or a mixer
4,691
def unjoin ( target = nil ) logger . info "Unjoining from #{target}" command = Adhearsion :: Rayo :: Command :: Unjoin . new join_options_with_target ( target ) write_and_await_response command rescue Adhearsion :: ProtocolError => e abort e end
Unjoins this call from another call or a mixer
4,692
def send_message ( body , options = { } ) logger . debug "Sending message: #{body}" client . send_message id , domain , body , options end
Sends a message to the caller
4,693
def execute_controller ( controller = nil , completion_callback = nil , & block ) raise ArgumentError , "Cannot supply a controller and a block at the same time" if controller && block_given? controller ||= CallController . new current_actor , & block logger . info "Executing controller #{controller.class}" controller ...
Execute a call controller asynchronously against this call .
4,694
def dump Dump . new timestamp : Time . now , call_counts : dump_call_counts , calls_by_route : dump_calls_by_route end
Create a point - time dump of process statistics
4,695
def invoke ( controller_class , metadata = nil ) controller = controller_class . new call , metadata controller . run end
Invoke another controller class within this controller returning to this context on completion .
4,696
def stop_all_components logger . info "Stopping all controller components" @active_components . each do | component | begin component . stop! rescue Adhearsion :: Rayo :: Component :: InvalidActionError end end end
Stop execution of all the components currently running in the controller .
4,697
def method_missing ( method_name , * args , & block ) config = Loquacious :: Configuration . for method_name , & block raise Adhearsion :: Configuration :: ConfigurationError . new "Invalid plugin #{method_name}" if config . nil? config end
Wrapper to access to a specific configuration object
4,698
def run if jruby? || cruby_with_readline? set_prompt Pry . config . command_prefix = "%" logger . info "Launching Adhearsion Console" @pry_thread = Thread . current pry logger . info "Adhearsion Console exiting" else logger . error "Unable to launch Adhearsion Console: This version of Ruby is using libedit. You must us...
Start the Adhearsion console
4,699
def dial ( to , options = { } ) options = options . dup options [ :to ] = to if options [ :timeout ] wait_timeout = options [ :timeout ] options [ :timeout ] = options [ :timeout ] * 1000 else wait_timeout = 60 end uri = client . new_call_uri options [ :uri ] = uri @dial_command = Adhearsion :: Rayo :: Command :: Dial ...
Dial out an existing outbound call