idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
7,000
def to_s ary = [ ] @data . keys . sort . each do | section | ary << "[ #{section} ]\n" @data [ section ] . keys . each do | key | ary << "#{key}=#{@data[section][key]}\n" end ary << "\n" end ary . join end
Get the parsable form of the current configuration
7,001
def each @data . each do | section , hash | hash . each do | key , value | yield [ section , key , value ] end end end
For a block .
7,002
def insert_before ( child1 , child2 ) if child1 . kind_of? String child1 = XPath . first ( self , child1 ) child1 . parent . insert_before child1 , child2 else ind = index ( child1 ) child2 . parent . delete ( child2 ) if child2 . parent @children [ ind , 0 ] = child2 child2 . parent = self end self end
Inserts an child before another child
7,003
def index ( child ) count = - 1 @children . find { | i | count += 1 ; i . hash == child . hash } count end
Fetches the index of a given child
7,004
def replace_child ( to_replace , replacement ) @children . map! { | c | c . equal? ( to_replace ) ? replacement : c } to_replace . parent = nil replacement . parent = self end
Replaces one child with another making sure the nodelist is correct
7,005
def deep_clone cl = clone ( ) each do | child | if child . kind_of? Parent cl << child . deep_clone else cl << child . clone end end cl end
Deeply clones this object . This creates a complete duplicate of this Parent including all descendants .
7,006
def write writer , indent = - 1 , transitive = false , ie_hack = false Kernel . warn ( "#{self.class.name}.write is deprecated" ) indent ( writer , indent ) writer << START . sub ( / \\ /u , '' ) writer << @target writer << ' ' writer << @content writer << STOP . sub ( / \\ /u , '' ) end
Constructs a new Instruction
7,007
def valid? ( argument ) if argument . nil? and options [ :required ] raise Templater :: TooFewArgumentsError elsif not argument . nil? if options [ :as ] == :hash and not argument . is_a? ( Hash ) raise Templater :: MalformattedArgumentError , "Expected the argument to be a Hash, but was '#{argument.inspect}'" elsif op...
Checks if the given argument is valid according to this description
7,008
def open_socket ( host , port ) return Timeout . timeout ( @open_timeout , Net :: OpenTimeout ) { if defined? SOCKSSocket and ENV [ "SOCKS_SERVER" ] @passive = true sock = SOCKSSocket . open ( host , port ) else sock = TCPSocket . open ( host , port ) end io = BufferedSocket . new ( sock ) io . read_timeout = @read_tim...
Constructs a socket with + host + and + port + .
7,009
def transfercmd ( cmd , rest_offset = nil ) if @passive host , port = makepasv conn = open_socket ( host , port ) if @resume and rest_offset resp = sendcmd ( "REST " + rest_offset . to_s ) if resp [ 0 ] != ?3 raise FTPReplyError , resp end end resp = sendcmd ( cmd ) resp = getresp if resp [ 0 ] == ?2 if resp [ 0 ] != ?...
Constructs a connection for transferring data
7,010
def getbinaryfile ( remotefile , localfile = File . basename ( remotefile ) , blocksize = DEFAULT_BLOCKSIZE ) result = nil if localfile if @resume rest_offset = File . size? ( localfile ) f = open ( localfile , "a" ) else rest_offset = nil f = open ( localfile , "w" ) end elsif ! block_given? result = "" end begin f . ...
Retrieves + remotefile + in binary mode storing the result in + localfile + . If + localfile + is nil returns retrieved data . If a block is supplied it is passed the retrieved data in + blocksize + chunks .
7,011
def nlst ( dir = nil ) cmd = "NLST" if dir cmd = cmd + " " + dir end files = [ ] retrlines ( cmd ) do | line | files . push ( line ) end return files end
Returns an array of filenames in the remote directory .
7,012
def rename ( fromname , toname ) resp = sendcmd ( "RNFR " + fromname ) if resp [ 0 ] != ?3 raise FTPReplyError , resp end voidcmd ( "RNTO " + toname ) end
Renames a file on the server .
7,013
def delete ( filename ) resp = sendcmd ( "DELE " + filename ) if resp [ 0 , 3 ] == "250" return elsif resp [ 0 ] == ?5 raise FTPPermError , resp else raise FTPReplyError , resp end end
Deletes a file on the server .
7,014
def start ( env = ENV , stdin = $stdin , stdout = $stdout ) sock = WEBrick :: CGI :: Socket . new ( @config , env , stdin , stdout ) req = HTTPRequest . new ( @config ) res = HTTPResponse . new ( @config ) unless @config [ :NPH ] or defined? ( MOD_RUBY ) def res . setup_header unless @header [ "status" ] phrase = HTTPS...
Starts the CGI process with the given environment + env + and standard input and output + stdin + and + stdout + .
7,015
def remove ( name ) public_generators . delete ( name . to_sym ) private_generators . delete ( name . to_sym ) end
Remove the generator with the given name from the manifold
7,016
def run_cli ( destination_root , name , version , args ) Templater :: CLI :: Manifold . run ( destination_root , self , name , version , args ) end
A Shortcut method for invoking the command line interface provided with Templater .
7,017
def djb_hash ( str , len ) hash = 5381 for i in ( 0 .. len ) hash = ( ( hash << 5 ) + hash ) + str [ i ] . to_i end return hash end
use djb hash function to generate temp object id
7,018
def has_name? ( other , ns = nil ) if ns return ( namespace ( ) == ns and name ( ) == other ) elsif other . include? ":" return fully_expanded_name == other else return name == other end end
Compares names optionally WITH namespaces
7,019
def each if @header @header . each { | k , v | value = @header [ k ] yield ( k , value . empty? ? nil : value . join ( ", " ) ) } end end
Iterates over the request headers
7,020
def fixup ( ) begin body { | chunk | } rescue HTTPStatus :: Error => ex @logger . error ( "HTTPRequest#fixup: #{ex.class} occurred." ) @keep_alive = false rescue => ex @logger . error ( ex ) @keep_alive = false end end
Consumes any remaining body and updates keep - alive status
7,021
def format ( format_string , params ) format_string . gsub ( / \% \{ \} / ) { param , spec = $1 , $2 case spec [ 0 ] when ?e , ?i , ?n , ?o raise AccessLogError , "parameter is required for \"#{spec}\"" unless param ( param = params [ spec ] [ param ] ) ? escape ( param ) : "-" when ?t params [ spec ] . strftime ( para...
Formats + params + according to + format_string + which is described in setup_params .
7,022
def run_with_threads thread_pool . gather_history if options . job_stats == :history yield thread_pool . join if options . job_stats stats = thread_pool . statistics puts "Maximum active threads: #{stats[:max_active_threads]}" puts "Total threads in play: #{stats[:total_threads_in_play]}" end ThreadHistoryDisplay . ne...
Run the given block with the thread startup and shutdown .
7,023
def standard_exception_handling yield rescue SystemExit raise rescue OptionParser :: InvalidOption => ex $stderr . puts ex . message exit ( false ) rescue Exception => ex display_error_message ( ex ) exit_because_of_exception ( ex ) end
Provide standard exception handling for the given block .
7,024
def display_prerequisites tasks . each do | t | puts "#{name} #{t.name}" t . prerequisites . each { | pre | puts " #{pre}" } end end
Display the tasks and prerequisites
7,025
def invocations return [ ] unless self . class . manifold self . class . invocations . map do | invocation | invocation . get ( self ) if match_options? ( invocation . options ) end . compact end
Finds and returns all templates whose options match the generator options .
7,026
def actions ( type = nil ) actions = type ? self . class . actions [ type ] : self . class . actions . values . flatten actions . inject ( [ ] ) do | actions , description | actions << description . compile ( self ) if match_options? ( description . options ) actions end end
Finds and returns all templates and files for this generators whose options match its options .
7,027
def all_actions ( type = nil ) all_actions = actions ( type ) all_actions += invocations . map { | i | i . all_actions ( type ) } all_actions . flatten end
Finds and returns all templates and files for this generators and any of those generators it invokes whose options match that generator s options .
7,028
def create_self_signed_cert ( bits , cn , comment ) rsa = OpenSSL :: PKey :: RSA . new ( bits ) { | p , n | case p when 0 ; $stderr . putc "." when 1 ; $stderr . putc "+" when 2 ; $stderr . putc "*" when 3 ; $stderr . putc "\n" else ; $stderr . putc "*" end } cert = OpenSSL :: X509 :: Certificate . new cert . version =...
Creates a self - signed certificate with the given number of + bits + the issuer + cn + and a + comment + to be stored in the certificate .
7,029
def listen ( address , port ) listeners = Utils :: create_listeners ( address , port , @logger ) if @config [ :SSLEnable ] unless ssl_context @ssl_context = setup_ssl_context ( @config ) @logger . info ( "\n" + @config [ :SSLCertificate ] . to_text ) end listeners . collect! { | svr | ssvr = :: OpenSSL :: SSL :: SSLSer...
Updates + listen + to enable SSL when the SSL configuration is active .
7,030
def initialize_log ( log ) close if @log if log . respond_to? ( :write ) @log = log elsif File . exist? ( log ) @log = open ( log , ( File :: WRONLY | File :: APPEND ) ) @log . sync = true else FileUtils . mkdir_p ( File . dirname ( log ) ) unless File . directory? ( File . dirname ( log ) ) @log = open ( log , ( File ...
Readies a log for writing .
7,031
def << ( string = nil ) message = "" message << delimiter message << string if string message << "\n" unless message [ - 1 ] == ?\n @buffer << message flush if @auto_flush message end
Appends a message to the log . The methods yield to an optional block and the output of this block will be appended to the message .
7,032
def write ( string ) length = string . length while 0 < length IO :: select ( nil , [ @sock ] ) @dumplog . log_dump ( '>' , string [ - length .. - 1 ] ) if @options . has_key? ( "Dump_log" ) length -= @sock . syswrite ( string [ - length .. - 1 ] ) end end
Write + string + to the host .
7,033
def cmd ( options ) match = @options [ "Prompt" ] time_out = @options [ "Timeout" ] fail_eof = @options [ "FailEOF" ] if options . kind_of? ( Hash ) string = options [ "String" ] match = options [ "Match" ] if options . has_key? ( "Match" ) time_out = options [ "Timeout" ] if options . has_key? ( "Timeout" ) fail_eof =...
Send a command to the host .
7,034
def login ( options , password = nil ) login_prompt = / \z /n password_prompt = / \z /n if options . kind_of? ( Hash ) username = options [ "Name" ] password = options [ "Password" ] login_prompt = options [ "LoginPrompt" ] if options [ "LoginPrompt" ] password_prompt = options [ "PasswordPrompt" ] if options [ "Passwo...
Login to the host with a given username and password .
7,035
def normalize_path ( path ) raise "abnormal path `#{path}'" if path [ 0 ] != ?/ ret = path . dup ret . gsub! ( %r{ }o , '/' ) while ret . sub! ( %r' \. \Z ' , '/' ) ; end while ret . sub! ( %r' \. \. \. \. \Z ' , '/' ) ; end raise "abnormal path `#{path}'" if %r{ \. \. \Z } =~ ret ret end
Normalizes a request path . Raises an exception if the path cannot be normalized .
7,036
def load_mime_types ( file ) open ( file ) { | io | hash = Hash . new io . each { | line | next if / / =~ line line . chomp! mimetype , ext0 = line . split ( / \s / , 2 ) next unless ext0 next if ext0 . empty? ext0 . split ( / \s / ) . each { | ext | hash [ ext ] = mimetype } } hash } end
Loads Apache - compatible mime . types in + file + .
7,037
def parse_range_header ( ranges_specifier ) if / / =~ ranges_specifier byte_range_set = split_header_value ( $1 ) byte_range_set . collect { | range_spec | case range_spec when / \d \d / then $1 . to_i .. $2 . to_i when / \d / then $1 . to_i .. - 1 when / \d / then - ( $1 . to_i ) .. - 1 else return nil end } end end
Parses a Range header value + ranges_specifier +
7,038
def parse_qvalues ( value ) tmp = [ ] if value parts = value . split ( / \s / ) parts . each { | part | if m = %r{ \s \s \d \. \d } . match ( part ) val = m [ 1 ] q = ( m [ 2 ] or 1 ) . to_f tmp . push ( [ val , q ] ) end } tmp = tmp . sort_by { | val , q | - q } tmp . collect! { | val , q | val } end return tmp end
Parses q values in + value + as used in Accept headers .
7,039
def parse_query ( str ) query = Hash . new if str str . split ( / / ) . each { | x | next if x . empty? key , val = x . split ( / / , 2 ) key = unescape_form ( key ) val = unescape_form ( val . to_s ) val = FormData . new ( val ) val . name = key if query . has_key? ( key ) query [ key ] . append_data ( val ) next end ...
Parses the query component of a URI in + str +
7,040
def escape_path ( str ) result = "" str . scan ( %r{ } ) . each { | i | result << "/" << _escape ( i [ 0 ] , UNESCAPED_PCHAR ) } return result end
Escapes path + str +
7,041
def partition ( & block ) resolve result = @items . partition ( & block ) [ FileList . new . import ( result [ 0 ] ) , FileList . new . import ( result [ 1 ] ) , ] end
FileList version of partition . Needed because the nested arrays should be FileLists in this version .
7,042
def add_matching ( pattern ) FileList . glob ( pattern ) . each do | fn | self << fn unless excluded_from_list? ( fn ) end end
Add matching glob patterns .
7,043
def value unless complete? stat :sleeping_on , :item_id => object_id @mutex . synchronize do stat :has_lock_on , :item_id => object_id chore stat :releasing_lock_on , :item_id => object_id end end error? ? raise ( @error ) : @result end
Create a promise to do the chore specified by the block . Return the value of this promise .
7,044
def chore if complete? stat :found_completed , :item_id => object_id return end stat :will_execute , :item_id => object_id begin @result = @block . call ( * @args ) rescue Exception => e @error = e end stat :did_execute , :item_id => object_id discard end
Perform the chore promised
7,045
def []= ( key , val ) unless val @header . delete key . downcase return val end @header [ key . downcase ] = [ val ] end
Sets the header field corresponding to the case - insensitive key .
7,046
def each_header block_given? or return enum_for ( __method__ ) @header . each do | k , va | yield k , va . join ( ', ' ) end end
Iterates for each header names and values .
7,047
def read_body ( dest = nil , & block ) if @read raise IOError , "#{self.class}\#read_body called twice" if dest or block return @body end to = procdest ( dest , block ) stream_check if @body_exist read_body_0 to @body = to else @body = nil end @read = true @body end
Gets entity body . If the block given yields it to + block + . The body is provided in fragments as it is read in from the socket .
7,048
def follow_redirection request = nil , result = nil , & block url = headers [ :location ] if url !~ / / url = URI . parse ( args [ :url ] ) . merge ( url ) . to_s end args [ :url ] = url if request if request . max_redirects == 0 raise MaxRedirectsReached end args [ :password ] = request . password args [ :user ] = req...
Follow a redirection
7,049
def parse_cookie cookie_content out = { } CGI :: Cookie :: parse ( cookie_content ) . each do | key , cookie | unless [ 'expires' , 'path' ] . include? key out [ CGI :: escape ( key ) ] = cookie . value [ 0 ] ? ( CGI :: escape ( cookie . value [ 0 ] ) || '' ) : '' end end out end
Parse a cookie value and return its content in an Hash
7,050
def [] ( task_name , scopes = nil ) task_name = task_name . to_s self . lookup ( task_name , scopes ) or enhance_with_matching_rule ( task_name ) or synthesize_file_task ( task_name ) or fail "Don't know how to build task '#{task_name}'" end
Find a matching task for + task_name + .
7,051
def run ( sock ) while true res = HTTPResponse . new ( @config ) req = HTTPRequest . new ( @config ) server = self begin timeout = @config [ :RequestTimeout ] while timeout > 0 break if IO . select ( [ sock ] , nil , nil , 0.5 ) timeout = 0 if @status != :Running timeout -= 0.5 end raise HTTPStatus :: EOFError if timeo...
Creates a new HTTP server according to + config +
7,052
def service ( req , res ) if req . unparsed_uri == "*" if req . request_method == "OPTIONS" do_OPTIONS ( req , res ) raise HTTPStatus :: OK end raise HTTPStatus :: NotFound , "`#{req.unparsed_uri}' not found." end servlet , options , script_name , path_info = search_servlet ( req . path ) raise HTTPStatus :: NotFound ,...
Services + req + and fills in + res +
7,053
def mount ( dir , servlet , * options ) @logger . debug ( sprintf ( "%s is mounted on %s." , servlet . inspect , dir ) ) @mount_tab [ dir ] = [ servlet , options ] end
Mounts + servlet + on + dir + passing + options + to the servlet at creation time
7,054
def search_servlet ( path ) script_name , path_info = @mount_tab . scan ( path ) servlet , options = @mount_tab [ script_name ] if servlet [ servlet , options , script_name , path_info ] end end
Finds a servlet for + path +
7,055
def virtual_host ( server ) @virtual_hosts << server @virtual_hosts = @virtual_hosts . sort_by { | s | num = 0 num -= 4 if s [ :BindAddress ] num -= 2 if s [ :Port ] num -= 1 if s [ :ServerName ] num } end
Adds + server + as a virtual host .
7,056
def lookup_server ( req ) @virtual_hosts . find { | s | ( s [ :BindAddress ] . nil? || req . addr [ 3 ] == s [ :BindAddress ] ) && ( s [ :Port ] . nil? || req . port == s [ :Port ] ) && ( ( s [ :ServerName ] . nil? || req . host == s [ :ServerName ] ) || ( ! s [ :ServerAlias ] . nil? && s [ :ServerAlias ] . find { | h ...
Finds the appropriate virtual host to handle + req +
7,057
def access_log ( config , req , res ) param = AccessLog :: setup_params ( config , req , res ) @config [ :AccessLog ] . each { | logger , fmt | logger << AccessLog :: format ( fmt + "\n" , param ) } end
Logs + req + and + res + in the access logs . + config + is used for the server name .
7,058
def set_non_blocking ( io ) flag = File :: NONBLOCK if defined? ( Fcntl :: F_GETFL ) flag |= io . fcntl ( Fcntl :: F_GETFL ) end io . fcntl ( Fcntl :: F_SETFL , flag ) end
Sets IO operations on + io + to be non - blocking
7,059
def set_close_on_exec ( io ) if defined? ( Fcntl :: FD_CLOEXEC ) io . fcntl ( Fcntl :: F_SETFD , Fcntl :: FD_CLOEXEC ) end end
Sets the close on exec flag for + io +
7,060
def su ( user ) if defined? ( Etc ) pw = Etc . getpwnam ( user ) Process :: initgroups ( user , pw . gid ) Process :: Sys :: setgid ( pw . gid ) Process :: Sys :: setuid ( pw . uid ) else warn ( "WEBrick::Utils::su doesn't work on this platform" ) end end
Changes the process s uid and gid to the ones of + user +
7,061
def random_string ( len ) rand_max = RAND_CHARS . bytesize ret = "" len . times { ret << RAND_CHARS [ rand ( rand_max ) ] } ret end
Generates a random string of length + len +
7,062
def timeout ( seconds , exception = Timeout :: Error ) return yield if seconds . nil? or seconds . zero? id = TimeoutHandler . register ( seconds , exception ) begin yield ( seconds ) ensure TimeoutHandler . cancel ( id ) end end
Executes the passed block and raises + exception + if execution takes more than + seconds + .
7,063
def makedirs ( path ) route = [ ] File . split ( path ) . each do | dir | route << dir current_dir = File . join ( route ) if @created [ current_dir ] . nil? @created [ current_dir ] = true $stderr . puts "Creating Directory #{current_dir}" if @verbose @ftp . mkdir ( current_dir ) rescue nil end end end
Create an FTP uploader targeting the directory + path + on + host + using the given account and password . + path + will be the root path of the uploader . Create the directory + path + in the uploader root path .
7,064
def file ( name ) File . open ( name , "rb" ) { | f | buf = "" while f . read ( 16384 , buf ) update buf end } self end
updates the digest with the contents of a given file _name_ and returns self .
7,065
def authorize_url ( params = nil ) return nil if self . token . nil? params = ( params || { } ) . merge ( :oauth_token => self . token ) build_authorize_url ( consumer . authorize_url , params ) end
Generate an authorization URL for user authorization
7,066
def get_access_token ( options = { } , * arguments ) response = consumer . token_request ( consumer . http_method , ( consumer . access_token_url? ? consumer . access_token_url : consumer . access_token_path ) , self , options , * arguments ) OAuth :: AccessToken . from_hash ( consumer , response ) end
exchange for AccessToken on server
7,067
def build_authorize_url ( base_url , params ) uri = URI . parse ( base_url . to_s ) queries = { } queries = Hash [ URI . decode_www_form ( uri . query ) ] if uri . query queries . merge! ( params ) if params uri . query = URI . encode_www_form ( queries ) if ! queries . empty? uri . to_s end
construct an authorization url
7,068
def signature_base_string base = [ method , normalized_uri , normalized_parameters ] base . map { | v | escape ( v ) } . join ( "&" ) end
See 9 . 1 in specs
7,069
def signed_uri ( with_oauth = true ) if signed? if with_oauth params = parameters else params = non_oauth_parameters end [ uri , normalize ( params ) ] * "?" else STDERR . puts "This request has not yet been signed!" end end
URI including OAuth parameters
7,070
def oauth_header ( options = { } ) header_params_str = oauth_parameters . map { | k , v | "#{k}=\"#{escape(v)}\"" } . join ( ', ' ) realm = "realm=\"#{options[:realm]}\", " if options [ :realm ] "OAuth #{realm}#{header_params_str}" end
Authorization header for OAuth
7,071
def create_signed_request ( http_method , path , token = nil , request_options = { } , * arguments ) request = create_http_request ( http_method , path , * arguments ) sign! ( request , token , request_options ) request end
Creates and signs an http request . It s recommended to use the Token classes to set this up correctly
7,072
def token_request ( http_method , path , token = nil , request_options = { } , * arguments ) request_options [ :token_request ] ||= true response = request ( http_method , path , token , request_options , * arguments ) case response . code . to_i when ( 200 .. 299 ) if block_given? yield response . body else CGI . pars...
Creates a request and parses the result as url_encoded . This is used internally for the RequestToken and AccessToken requests .
7,073
def sign! ( request , token = nil , request_options = { } ) request . oauth! ( http , self , token , options . merge ( request_options ) ) end
Sign the Request object . Use this if you have an externally generated http request object you want to sign .
7,074
def signature_base_string ( request , token = nil , request_options = { } ) request . signature_base_string ( http , self , token , options . merge ( request_options ) ) end
Return the signature_base_string
7,075
def create_http_request ( http_method , path , * arguments ) http_method = http_method . to_sym if [ :post , :put , :patch ] . include? ( http_method ) data = arguments . shift end uri = URI . parse ( site ) path = uri . path + path if uri . path && uri . path != '/' && uri . host == http . address headers = arguments ...
create the http request object for a given http_method and path
7,076
def escape ( value ) _escape ( value . to_s . to_str ) rescue ArgumentError _escape ( value . to_s . to_str . force_encoding ( Encoding :: UTF_8 ) ) end
Escape + value + by URL encoding all non - reserved character .
7,077
def normalize ( params ) params . sort . map do | k , values | if values . is_a? ( Array ) values << nil if values . empty? values . sort . collect do | v | [ escape ( k ) , escape ( v ) ] * "=" end elsif values . is_a? ( Hash ) normalize_nested_query ( values , k ) else [ escape ( k ) , escape ( values ) ] * "=" end e...
Normalize a + Hash + of parameter values . Parameters are sorted by name using lexicographical byte value ordering . If two or more parameters share the same name they are sorted by their value . Parameters are concatenated in their sorted order into a single string . For each parameter the name is separated from the c...
7,078
def create_consumer creds = generate_credentials Consumer . new ( creds [ 0 ] , creds [ 1 ] , { :site => base_url , :request_token_path => request_token_path , :authorize_path => authorize_path , :access_token_path => access_token_path } ) end
mainly for testing purposes
7,079
def convert_hoptoad_keys_to_graylog2 ( hash ) if hash [ 'short_message' ] . to_s . empty? if hash . has_key? ( 'error_class' ) && hash . has_key? ( 'error_message' ) hash [ 'short_message' ] = hash . delete ( 'error_class' ) + ': ' + hash . delete ( 'error_message' ) end end end
Converts Hoptoad - specific keys in +
7,080
def parent ( * args ) return @parent if args . empty? key = args . shift @parent = Gretel :: Crumb . new ( context , key , * args ) end
Sets or gets the parent breadcrumb . If you supply a parent key and optional arguments it will set the parent . If nothing is supplied it will return the parent if this has been set .
7,081
def method_missing ( method , * args , & block ) if method =~ / \? / options [ $1 . to_sym ] . present? else options [ method ] end end
Enables accessors and predicate methods for values in the + options + hash . This can be used to pass information to links when rendering breadcrumbs manually .
7,082
def with_breadcrumb ( key , * args , & block ) original_renderer = @_gretel_renderer @_gretel_renderer = Gretel :: Renderer . new ( self , key , * args ) yield @_gretel_renderer = original_renderer end
Yields a block where inside the block you have a different breadcrumb than outside .
7,083
def render ( options ) options = options_for_render ( options ) links = links_for_render ( options ) LinkCollection . new ( context , links , options ) end
Renders the breadcrumbs HTML .
7,084
def options_for_render ( options = { } ) style = options_for_style ( options [ :style ] || DEFAULT_OPTIONS [ :style ] ) DEFAULT_OPTIONS . merge ( style ) . merge ( options ) end
Returns merged options for rendering breadcrumbs .
7,085
def links_for_render ( options = { } ) out = links . dup if options [ :autoroot ] && out . map ( & :key ) . exclude? ( :root ) && Gretel :: Crumbs . crumb_defined? ( :root ) out . unshift * Gretel :: Crumb . new ( context , :root ) . links end if options [ :link_current_to_request_path ] && out . any? && request out . ...
Array of links with applied options .
7,086
def links @links ||= if @breadcrumb_key . present? Gretel :: Crumbs . reload_if_needed crumb = Gretel :: Crumb . new ( context , breadcrumb_key , * breadcrumb_args ) links = crumb . links . dup links . unshift * parent_links_for ( crumb ) links else [ ] end end
Array of links for the path of the breadcrumb . Also reloads the breadcrumb configuration if needed .
7,087
def parent_links_for ( crumb ) links = [ ] while crumb = crumb . parent links . unshift * crumb . links end links end
Returns parent links for the crumb .
7,088
def reset! instance_variables . each { | var | remove_instance_variable var } constants . each do | c | c = const_get ( c ) c . reset! if c . respond_to? ( :reset! ) end end
Resets all instance variables and calls + reset! + on all child modules and classes . Used for testing .
7,089
def extract FileUtils . mkdir_p source_dir opts = { } if tarball == "-" opts [ :input ] = $stdin . read end tarball_extract = Mixlib :: ShellOut . new ( "tar xzf #{tarball} -C #{source_dir}" , opts ) tarball_extract . logger = Pkgr . logger tarball_extract . run_command tarball_extract . error! end
Extract the given tarball to the target directory
7,090
def update_config if File . exist? ( config_file ) Pkgr . debug "Loading #{distribution.slug} from #{config_file}." @config = Config . load_file ( config_file , distribution . slug ) . merge ( config ) Pkgr . debug "Found .pkgr.yml file. Updated config is now: #{config.inspect}" distribution . config = @config if @conf...
Update existing config with the one from . pkgr . yml file if any
7,091
def check raise Errors :: ConfigurationInvalid , config . errors . join ( "; " ) unless config . valid? distribution . check end
Check configuration and verifies that the current distribution s requirements are satisfied
7,092
def setup Dir . chdir ( build_dir ) do distribution . templates . each do | template | template . install ( config . sesame ) end end end
Setup the build directory structure
7,093
def compile begin FileUtils . mkdir_p ( app_home_dir ) rescue Errno :: EACCES => e Pkgr . logger . warn "Can't create #{app_home_dir.inspect}, which may be needed by some buildpacks." end FileUtils . mkdir_p ( compile_cache_dir ) FileUtils . mkdir_p ( compile_env_dir ) if buildpacks_for_app . size > 0 run_hook config ....
Pass the app through the buildpack
7,094
def write_init FileUtils . mkdir_p scaling_dir Dir . chdir ( scaling_dir ) do distribution . initializers_for ( config . name , procfile_entries ) . each do | ( process , file ) | process_config = config . dup process_config . process_name = process . name process_config . process_command = process . command file . ins...
Write startup scripts .
7,095
def setup_crons crons_dir = File . join ( "/" , distribution . crons_dir ) config . crons . map! do | cron_path | Cron . new ( File . expand_path ( cron_path , config . home ) , File . join ( crons_dir , File . basename ( cron_path ) ) ) end config . crons . each do | cron | puts "--- end end
Write cron files
7,096
def package ( remaining_attempts = 3 ) app_package = Mixlib :: ShellOut . new ( fpm_command ) app_package . logger = Pkgr . logger app_package . run_command app_package . error! begin verify rescue Mixlib :: ShellOut :: ShellCommandFailed => e if remaining_attempts > 0 package ( remaining_attempts - 1 ) else raise end ...
Launch the FPM command that will generate the package .
7,097
def buildpacks_for_app raise "#{source_dir} does not exist" unless File . directory? ( source_dir ) @buildpacks_for_app ||= begin mode , buildpacks = distribution . buildpacks case mode when :custom buildpacks . find_all do | buildpack | buildpack . setup ( config . edge , config . home ) buildpack . detect ( source_di...
Buildpacks detected for the app if any . If multiple buildpacks are explicitly specified all are used
7,098
def validate_options ( valid_option_keys , options ) options . keys . each do | key | unless valid_option_keys . include? key . to_sym raise ArgumentError , "Invalid option `#{key}`" end end end
Takes in a list of valid option keys and a hash of options . If one of the keys in the hash is invalid an ArgumentError will be raised .
7,099
def to_hash Hash [ self . class . fields . keys . map do | field_name | [ field_name . to_s , serialized_field ( field_name ) ] end . select { | k , v | ! v . nil? } ] end
Takes in a hash containing all the attributes required to initialize the object .