idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
2,300
def list ( * args ) params = arguments ( args ) . params response = if ( user = params . delete ( 'user' ) ) get_request ( "/users/#{user}/gists" , params ) elsif args . map ( & :to_s ) . include? ( 'public' ) get_request ( "/gists/public" , params ) else get_request ( "/gists" , params ) end return response unless block_given? response . each { | el | yield el } end
List a user s gists
2,301
def get ( * args ) arguments ( args , required : [ :id ] ) if ( sha = arguments . params . delete ( 'sha' ) ) get_request ( "/gists/#{arguments.id}/#{sha}" ) else get_request ( "/gists/#{arguments.id}" , arguments . params ) end end
Get a single gist
2,302
def client @client ||= :: OAuth2 :: Client . new ( client_id , client_secret , { :site => current_options . fetch ( :site ) { Github . site } , :authorize_url => 'login/oauth/authorize' , :token_url => 'login/oauth/access_token' , :ssl => { :verify => false } } ) end
Setup OAuth2 instance
2,303
def create ( * args ) arguments ( args , required : [ :org_name ] ) do assert_required %w[ name ] end params = arguments . params params [ "accept" ] ||= PREVIEW_MEDIA post_request ( "/orgs/#{arguments.org_name}/projects" , params ) end
Create a new project for the specified repo
2,304
def call ( current_options , params ) unless HTTP_METHODS . include? ( action ) raise ArgumentError , "unknown http method: #{method}" end puts "EXECUTED: #{action} - #{path} with PARAMS: #{params.request_params}" if ENV [ 'DEBUG' ] request_options = params . options connection_options = current_options . merge ( request_options ) conn = connection ( api , connection_options ) self . path = Utils :: Url . normalize ( self . path ) if conn . path_prefix != '/' && self . path . index ( conn . path_prefix ) != 0 self . path = ( conn . path_prefix + self . path ) . gsub ( / \/ \/ / , '/' ) end response = conn . send ( action ) do | request | case action . to_sym when * ( HTTP_METHODS - METHODS_WITH_BODIES ) request . body = params . data if params . key? ( 'data' ) if params . key? ( 'encoder' ) request . params . params_encoder ( params . encoder ) end request . url ( self . path , params . request_params ) when * METHODS_WITH_BODIES request . url ( self . path , connection_options [ :query ] || { } ) request . body = params . data unless params . empty? end end ResponseWrapper . new ( response , api ) end
Create a new Request
2,305
def get ( * args ) raise_authentication_error unless authenticated? arguments ( args , required : [ :id ] ) get_request ( "/authorizations/#{arguments.id}" , arguments . params ) end
Get a single authorization
2,306
def create ( * args ) raise_authentication_error unless authenticated? arguments ( args ) do assert_required :note , :scopes end post_request ( '/authorizations' , arguments . params ) end
Create a new authorization
2,307
def update ( * args ) raise_authentication_error unless authenticated? arguments ( args , required : [ :id ] ) patch_request ( "/authorizations/#{arguments.id}" , arguments . params ) end
Update an existing authorization
2,308
def delete ( * args ) raise_authentication_error unless authenticated? arguments ( args , required : [ :id ] ) delete_request ( "/authorizations/#{arguments.id}" , arguments . params ) end
Delete an authorization
2,309
def list ( * args ) arguments ( args ) params = arguments . params response = if ( ( user_name = params . delete ( 'user' ) ) && ( repo_name = params . delete ( 'repo' ) ) ) get_request ( "/repos/#{user_name}/#{repo_name}/notifications" , params ) else get_request ( '/notifications' , params ) end return response unless block_given? response . each { | el | yield el } end
List your notifications
2,310
def mark ( * args ) arguments ( args ) params = arguments . params if ( ( user_name = params . delete ( 'user' ) ) && ( repo_name = params . delete ( 'repo' ) ) ) put_request ( "/repos/#{user_name}/#{repo_name}/notifications" , params ) elsif ( thread_id = params . delete ( "id" ) ) patch_request ( "/notifications/threads/#{thread_id}" , params ) else put_request ( '/notifications' , params ) end end
Mark as read
2,311
def page_request ( path , params = { } ) if params [ PARAM_PER_PAGE ] == NOT_FOUND params [ PARAM_PER_PAGE ] = default_page_size end if params [ PARAM_PAGE ] && params [ PARAM_PAGE ] == NOT_FOUND params [ PARAM_PAGE ] = default_page end current_api . get_request ( path , ParamsHash . new ( params ) ) end
Perform http get request with pagination parameters
2,312
def say ( * args ) params = arguments ( * args ) . params params [ :s ] = args . shift unless args . empty? params [ 'raw' ] = true get_request ( '/octocat' , params ) end
Generate ASCII octocat with speech bubble .
2,313
def each body_parts = self . body . respond_to? ( :each ) ? self . body : [ self . body ] return body_parts . to_enum unless block_given? body_parts . each { | part | yield ( part ) } end
Iterate over each resource inside the body
2,314
def api_methods_in ( klass ) methods = klass . send ( :instance_methods , false ) - [ :actions ] methods . sort . each_with_object ( [ ] ) do | method_name , accumulator | unless method_name . to_s . include? ( 'with' ) || method_name . to_s . include? ( 'without' ) accumulator << method_name end accumulator end end
Finds api methods in a class
2,315
def default_options ( options = { } ) headers = default_headers . merge ( options [ :headers ] || { } ) headers . merge! ( { USER_AGENT => options [ :user_agent ] } ) { headers : headers , ssl : options [ :ssl ] , url : options [ :endpoint ] } end
Create default connection options
2,316
def connection ( api , options = { } ) connection_options = default_options ( options ) connection_options . merge! ( builder : stack ( options . merge! ( api : api ) ) ) if options [ :connection_options ] connection_options . deep_merge! ( options [ :connection_options ] ) end if ENV [ 'DEBUG' ] p "Connection options : \n" pp connection_options end Faraday . new ( connection_options ) end
Creates http connection
2,317
def update ( * args ) arguments ( args , required : [ :id ] ) do permit VALID_KEY_PARAM_NAMES end patch_request ( "/user/keys/#{arguments.id}" , arguments . params ) end
Update a public key for the authenticated user
2,318
def parse ( media ) version = 'v3' media . sub! ( / / , "" ) media = media . include? ( '+' ) ? media . split ( '+' ) [ 0 ] : media version , media = media . split ( '.' ) if media . include? ( '.' ) media_type = lookup_media ( media ) "application/vnd.github.#{version}.#{media_type}" end
Parse media type param
2,319
def create ( * args ) arguments ( args , required : [ :org_name ] ) do assert_required REQUIRED_PARAMS end post_request ( "/orgs/#{arguments.org_name}/hooks" , arguments . params ) end
Create a hook
2,320
def create ( * args ) arguments ( args , required : [ :user , :repo ] ) do permit VALID_MILESTONE_INPUTS assert_required %w[ title ] end post_request ( "/repos/#{arguments.user}/#{arguments.repo}/milestones" , arguments . params ) end
Create a milestone
2,321
def get ( * args ) arguments ( args , required : [ :user , :repo , :ref ] ) validate_reference arguments . ref params = arguments . params get_request ( "/repos/#{arguments.user}/#{arguments.repo}/git/refs/#{arguments.ref}" , params ) end
Get a reference
2,322
def create ( * args ) arguments ( args , required : [ :user , :repo ] ) do permit VALID_REF_PARAM_NAMES assert_required REQUIRED_REF_PARAMS end params = arguments . params validate_reference params [ 'ref' ] post_request ( "/repos/#{arguments.user}/#{arguments.repo}/git/refs" , params ) end
Create a reference
2,323
def update ( * args ) arguments ( args , required : [ :user , :repo , :ref ] ) do permit VALID_REF_PARAM_NAMES assert_required %w[ sha ] end patch_request ( "/repos/#{arguments.user}/#{arguments.repo}/git/refs/#{arguments.ref}" , arguments . params ) end
Update a reference
2,324
def delete ( * args ) arguments ( args , required : [ :user , :repo , :ref ] ) params = arguments . params delete_request ( "/repos/#{arguments.user}/#{arguments.repo}/git/refs/#{arguments.ref}" , params ) end
Delete a reference
2,325
def available_locales_set @@available_locales_set ||= available_locales . inject ( Set . new ) do | set , locale | set << locale . to_s << locale . to_sym end end
Caches the available locales list as both strings and symbols in a Set so that we can have faster lookups to do the available locales enforce check .
2,326
def missing_interpolation_argument_handler @@missing_interpolation_argument_handler ||= lambda do | missing_key , provided_hash , string | raise MissingInterpolationArgument . new ( missing_key , provided_hash , string ) end end
Returns the current handler for situations when interpolation argument is missing . MissingInterpolationArgument will be raised by default .
2,327
def translate ( key = nil , * , throw : false , raise : false , locale : nil , ** options ) locale ||= config . locale raise Disabled . new ( 't' ) if locale == false enforce_available_locales! ( locale ) backend = config . backend result = catch ( :exception ) do if key . is_a? ( Array ) key . map { | k | backend . translate ( locale , k , options ) } else backend . translate ( locale , key , options ) end end if result . is_a? ( MissingTranslation ) handle_exception ( ( throw && :throw || raise && :raise ) , result , locale , key , options ) else result end end
Translates pluralizes and interpolates a given key using a given locale scope and default as well as interpolation values .
2,328
def exists? ( key , _locale = nil , locale : _locale ) locale ||= config . locale raise Disabled . new ( 'exists?' ) if locale == false raise I18n :: ArgumentError if key . is_a? ( String ) && key . empty? config . backend . exists? ( locale , key ) end
Returns true if a translation exists for a given key otherwise returns false .
2,329
def localize ( object , locale : nil , format : nil , ** options ) locale ||= config . locale raise Disabled . new ( 'l' ) if locale == false enforce_available_locales! ( locale ) format ||= :default config . backend . localize ( locale , object , format , options ) end
Localizes certain objects such as dates and numbers to local formatting .
2,330
def normalize_keys ( locale , key , scope , separator = nil ) separator ||= I18n . default_separator keys = [ ] keys . concat normalize_key ( locale , separator ) keys . concat normalize_key ( scope , separator ) keys . concat normalize_key ( key , separator ) keys end
Merges the given locale key and scope into a single array of keys . Splits keys that contain dots into multiple keys . Makes sure all keys are Symbols .
2,331
def enforce_available_locales! ( locale ) if locale != false && config . enforce_available_locales raise I18n :: InvalidLocale . new ( locale ) if ! locale_available? ( locale ) end end
Raises an InvalidLocale exception when the passed locale is not available .
2,332
def generate ( site ) @site = site collections . each do | name , meta | Jekyll . logger . info "Jekyll Feed:" , "Generating feed for #{name}" ( meta [ "categories" ] + [ nil ] ) . each do | category | path = feed_path ( :collection => name , :category => category ) next if file_exists? ( path ) @site . pages << make_page ( path , :collection => name , :category => category ) end end end
Main plugin action called by Jekyll - core
2,333
def normalize_posts_meta ( hash ) hash [ "posts" ] ||= { } hash [ "posts" ] [ "path" ] ||= config [ "path" ] hash [ "posts" ] [ "categories" ] ||= config [ "categories" ] config [ "path" ] ||= hash [ "posts" ] [ "path" ] hash end
Special case the posts collection which for ease of use and backwards compatability can be configured via top - level keys or directly as a collection
2,334
def all ( query ) return to_enum ( :all , query ) unless block_given? if @hash . include? query yield @hash [ query ] return end case query when String optimize_if_necessary! @regexes . each do | regex | match = regex . match ( query ) next unless match @regex_counts [ regex ] += 1 value = @hash [ regex ] if value . respond_to? :call yield value . call ( match ) else yield value end end when Numeric @ranges . each do | range | yield @hash [ range ] if range . cover? query end when Regexp @hash . each do | key , val | yield val if key . is_a? ( String ) && query =~ key end end end
Return everything that matches the query .
2,335
def custom_reader ( key ) default_proc . call ( self , key ) if default_proc && ! key? ( key ) value = regular_reader ( convert_key ( key ) ) yield value if block_given? value end
Retrieves an attribute set in the Mash . Will convert any key passed in to a string before retrieving .
2,336
def custom_writer ( key , value , convert = true ) key_as_symbol = ( key = convert_key ( key ) ) . to_sym log_built_in_message ( key_as_symbol ) if log_collision? ( key_as_symbol ) regular_writer ( key , convert ? convert_value ( value ) : value ) end
Sets an attribute in the Mash . Key will be converted to a string before it is set and Hashes will be converted into Mashes for nesting purposes .
2,337
def initializing_reader ( key ) ck = convert_key ( key ) regular_writer ( ck , self . class . new ) unless key? ( ck ) regular_reader ( ck ) end
This is the bang method reader it will return a new Mash if there isn t a value already assigned to the key requested .
2,338
def underbang_reader ( key ) ck = convert_key ( key ) if key? ( ck ) regular_reader ( ck ) else self . class . new end end
This is the under bang method reader it will return a temporary new Mash if there isn t a value already assigned to the key requested .
2,339
def deep_update ( other_hash , & blk ) other_hash . each_pair do | k , v | key = convert_key ( k ) if v . is_a? ( :: Hash ) && key? ( key ) && regular_reader ( key ) . is_a? ( Mash ) custom_reader ( key ) . deep_update ( v , & blk ) else value = convert_value ( v , true ) value = convert_value ( yield ( key , self [ k ] , value ) , true ) if blk && key? ( k ) custom_writer ( key , value , false ) end end self end
Recursively merges this mash with the passed in hash merging each hash in the hierarchy .
2,340
def _update_counts_after_update self . class . after_commit_counter_cache . each do | counter | counter_cache_name_was = counter . counter_cache_name_for ( counter . previous_model ( self ) ) counter_cache_name = counter . counter_cache_name_for ( self ) if counter . first_level_relation_changed? ( self ) || ( counter . delta_column && counter . attribute_changed? ( self , counter . delta_column ) ) || counter_cache_name != counter_cache_name_was counter . change_counter_cache ( self , :increment => true , :counter_column => counter_cache_name ) counter . change_counter_cache ( self , :increment => false , :was => true , :counter_column => counter_cache_name_was ) end end end
called by after_update callback
2,341
def destroyed_for_counter_culture? if respond_to? ( :paranoia_destroyed? ) paranoia_destroyed? elsif defined? ( Discard :: Model ) && self . class . include? ( Discard :: Model ) discarded? else false end end
check if record is soft - deleted
2,342
def change_counter_cache ( obj , options ) change_counter_column = options . fetch ( :counter_column ) { counter_cache_name_for ( obj ) } id_to_change = foreign_key_value ( obj , relation , options [ :was ] ) id_to_change = foreign_key_values . call ( id_to_change ) if foreign_key_values if id_to_change && change_counter_column delta_magnitude = if delta_column ( options [ :was ] ? attribute_was ( obj , delta_column ) : obj . public_send ( delta_column ) ) || 0 else counter_delta_magnitude_for ( obj ) end operator = options [ :increment ] ? '+' : '-' quoted_column = model . connection . quote_column_name ( change_counter_column ) updates = [ ] updates << "#{quoted_column} = COALESCE(#{quoted_column}, 0) #{operator} #{delta_magnitude}" if touch current_time = obj . send ( :current_time_from_proper_timezone ) timestamp_columns = obj . send ( :timestamp_attributes_for_update_in_model ) timestamp_columns << touch if touch != true timestamp_columns . each do | timestamp_column | updates << "#{timestamp_column} = '#{current_time.to_formatted_s(:db)}'" end end klass = relation_klass ( relation , source : obj , was : options [ :was ] ) primary_key = relation_primary_key ( relation , source : obj , was : options [ :was ] ) if @with_papertrail instance = klass . where ( primary_key => id_to_change ) . first if instance if instance . paper_trail . respond_to? ( :save_with_version ) current_time = obj . send ( :current_time_from_proper_timezone ) timestamp_columns = obj . send ( :timestamp_attributes_for_update_in_model ) timestamp_columns . each do | timestamp_column | instance . send ( "#{timestamp_column}=" , current_time ) end instance . paper_trail . save_with_version ( validate : false ) else instance . paper_trail . touch_with_version end end end klass . where ( primary_key => id_to_change ) . update_all updates . join ( ', ' ) end end
increments or decrements a counter cache
2,343
def foreign_key_value ( obj , relation , was = false ) relation = relation . is_a? ( Enumerable ) ? relation . dup : [ relation ] first_relation = relation . first if was first = relation . shift foreign_key_value = attribute_was ( obj , relation_foreign_key ( first ) ) klass = relation_klass ( first , source : obj , was : was ) if foreign_key_value value = klass . where ( "#{klass.table_name}.#{relation_primary_key(first, source: obj, was: was)} = ?" , foreign_key_value ) . first end else value = obj end while ! value . nil? && relation . size > 0 value = value . send ( relation . shift ) end return value . try ( relation_primary_key ( first_relation , source : obj , was : was ) . try ( :to_sym ) ) end
gets the value of the foreign key on the given relation
2,344
def relation_reflect ( relation ) relation = relation . is_a? ( Enumerable ) ? relation . dup : [ relation ] klass = model while relation . size > 0 cur_relation = relation . shift reflect = klass . reflect_on_association ( cur_relation ) raise "No relation #{cur_relation} on #{klass.name}" if reflect . nil? if relation . size > 0 klass = reflect . klass end end return reflect end
gets the reflect object on the given relation
2,345
def relation_klass ( relation , source : nil , was : false ) reflect = relation_reflect ( relation ) if reflect . options . key? ( :polymorphic ) raise "Can't work out relation's class without being passed object (relation: #{relation}, reflect: #{reflect})" if source . nil? raise "Can't work out polymorhpic relation's class with multiple relations yet" unless ( relation . is_a? ( Symbol ) || relation . length == 1 ) type_column = reflect . foreign_type . to_sym if was attribute_was ( source , type_column ) . try ( :constantize ) else source . public_send ( type_column ) . try ( :constantize ) end else reflect . klass end end
gets the class of the given relation
2,346
def relation_primary_key ( relation , source : nil , was : false ) reflect = relation_reflect ( relation ) klass = nil if reflect . options . key? ( :polymorphic ) raise "can't handle multiple keys with polymorphic associations" unless ( relation . is_a? ( Symbol ) || relation . length == 1 ) raise "must specify source for polymorphic associations..." unless source return relation_klass ( relation , source : source , was : was ) . try ( :primary_key ) end reflect . association_primary_key ( klass ) end
gets the primary key name of the given relation
2,347
def to_era ( format = "%o%E.%m.%d" , era_names : ERA_NAME_DEFAULTS ) raise EraJa :: DateOutOfRangeError unless era_convertible? @era_format = format . gsub ( / / , "%J%" ) str_time = strftime ( @era_format ) if @era_format =~ / / case when self . to_time < :: Time . mktime ( 1912 , 7 , 30 ) str_time = era_year ( year - 1867 , :meiji , era_names ) when self . to_time < :: Time . mktime ( 1926 , 12 , 25 ) str_time = era_year ( year - 1911 , :taisho , era_names ) when self . to_time < :: Time . mktime ( 1989 , 1 , 8 ) str_time = era_year ( year - 1925 , :showa , era_names ) when self . to_time < :: Time . mktime ( 2019 , 5 , 1 ) str_time = era_year ( year - 1988 , :heisei , era_names ) else str_time = era_year ( year - 2018 , :reiwa , era_names ) end end str_time . gsub ( / \d / ) { to_kanzi ( $1 ) } end
Convert to Japanese era .
2,348
def abs_thresholds ( scale , max_value ) at = [ ] scale . each { | v | at . push ( v * max_value ) } return at end
Produce a thresholds array containing absolute values based on supplied percentages applied to a literal max value .
2,349
def open? ProcTable . ps . any? { | p | p . comm == path } rescue ArgumentError false end
Is the detected dependency currently open?
2,350
def get_application_default scope = nil , options = { } creds = DefaultCredentials . from_env ( scope , options ) || DefaultCredentials . from_well_known_path ( scope , options ) || DefaultCredentials . from_system_default_path ( scope , options ) return creds unless creds . nil? unless GCECredentials . on_gce? options GCECredentials . unmemoize_all raise NOT_FOUND_ERROR end GCECredentials . new end
Obtains the default credentials implementation to use in this environment .
2,351
def extract_directives ( header ) processed_header = String . new ( "" ) directives = [ ] header . lines . each_with_index do | line , index | if directive = line [ DIRECTIVE_PATTERN , 1 ] name , * args = Shellwords . shellwords ( directive ) if respond_to? ( "process_#{name}_directive" , true ) directives << [ index + 1 , name , * args ] line = "\n" end end processed_header << line end processed_header . chomp! processed_header << "\n" if processed_header . length > 0 && header [ - 1 ] == "\n" return processed_header , directives end
Returns an Array of directive structures . Each structure is an Array with the line number as the first element the directive name as the second element followed by any arguments .
2,352
def log_level = ( level ) if level . is_a? ( Integer ) @logger . level = level else @logger . level = Logger . const_get ( level . to_s . upcase ) end end
Set logger level with constant or symbol .
2,353
def with_logger if env = manifest . environment old_logger = env . logger env . logger = @logger end yield ensure env . logger = old_logger if env end
Sub out environment logger with our rake task logger that writes to stderr .
2,354
def register_pipeline ( name , proc = nil , & block ) proc ||= block self . config = hash_reassoc ( config , :pipeline_exts ) do | pipeline_exts | pipeline_exts . merge ( ".#{name}" . freeze => name . to_sym ) end self . config = hash_reassoc ( config , :pipelines ) do | pipelines | pipelines . merge ( name . to_sym => proc ) end end
Registers a pipeline that will be called by call_processor method .
2,355
def prepend_path ( path ) self . config = hash_reassoc ( config , :paths ) do | paths | path = File . expand_path ( path , config [ :root ] ) . freeze paths . unshift ( path ) end end
Prepend a path to the paths list .
2,356
def append_path ( path ) self . config = hash_reassoc ( config , :paths ) do | paths | path = File . expand_path ( path , config [ :root ] ) . freeze paths . push ( path ) end end
Append a path to the paths list .
2,357
def depend_on ( path ) if environment . absolute_path? ( path ) && environment . stat ( path ) @dependencies << environment . build_file_digest_uri ( path ) else resolve ( path ) end nil end
depend_on allows you to state a dependency on a file without including it .
2,358
def base64_asset_data_uri ( asset ) data = Rack :: Utils . escape ( EncodingUtils . base64 ( asset . source ) ) "data:#{asset.content_type};base64,#{data}" end
Returns a Base64 - encoded data URI .
2,359
def optimize_svg_for_uri_escaping! ( svg ) svg . gsub! ( / \? \? /m , '' ) svg . gsub! ( / \s / , ' ' ) svg . gsub! ( '> <' , '><' ) svg . gsub! ( / \w / , "\\1='\\2'" ) svg . strip! end
Optimizes an SVG for being URI - escaped .
2,360
def optimize_quoted_uri_escapes! ( escaped ) escaped . gsub! ( '%3D' , '=' ) escaped . gsub! ( '%3A' , ':' ) escaped . gsub! ( '%2F' , '/' ) escaped . gsub! ( '%27' , "'" ) escaped . tr! ( '+' , ' ' ) end
Un - escapes characters in the given URI - escaped string that do not need escaping in - quoted data URIs .
2,361
def compile ( * args ) unless environment raise Error , "manifest requires environment for compilation" end filenames = [ ] concurrent_exporters = [ ] assets_to_export = Concurrent :: Array . new find ( * args ) do | asset | assets_to_export << asset end assets_to_export . each do | asset | mtime = Time . now . iso8601 files [ asset . digest_path ] = { 'logical_path' => asset . logical_path , 'mtime' => mtime , 'size' => asset . bytesize , 'digest' => asset . hexdigest , 'integrity' => DigestUtils . hexdigest_integrity_uri ( asset . hexdigest ) } assets [ asset . logical_path ] = asset . digest_path filenames << asset . filename promise = nil exporters_for_asset ( asset ) do | exporter | next if exporter . skip? ( logger ) if promise . nil? promise = Concurrent :: Promise . new ( executor : executor ) { exporter . call } concurrent_exporters << promise . execute else concurrent_exporters << promise . then { exporter . call } end end end concurrent_exporters . each ( & :wait! ) save filenames end
Compile asset to directory . The asset is written to a fingerprinted filename like application - 2e8e9a7c6b0aafa0c9bdeec90ea30213 . js . An entry is also inserted into the manifest file .
2,362
def remove ( filename ) path = File . join ( dir , filename ) gzip = "#{path}.gz" logical_path = files [ filename ] [ 'logical_path' ] if assets [ logical_path ] == filename assets . delete ( logical_path ) end files . delete ( filename ) FileUtils . rm ( path ) if File . exist? ( path ) FileUtils . rm ( gzip ) if File . exist? ( gzip ) save logger . info "Removed #{filename}" nil end
Removes file from directory and from manifest . filename must be the name with any directory path .
2,363
def clean ( count = 2 , age = 3600 ) asset_versions = files . group_by { | _ , attrs | attrs [ 'logical_path' ] } asset_versions . each do | logical_path , versions | current = assets [ logical_path ] versions . reject { | path , _ | path == current } . sort_by { | _ , attrs | Time . parse ( attrs [ 'mtime' ] ) } . reverse . each_with_index . drop_while { | ( _ , attrs ) , index | _age = [ 0 , Time . now - Time . parse ( attrs [ 'mtime' ] ) ] . max _age < age || index < count } . each { | ( path , _ ) , _ | remove ( path ) } end end
Cleanup old assets in the compile directory . By default it will keep the latest version 2 backups and any created within the past hour .
2,364
def save data = json_encode ( @data ) FileUtils . mkdir_p File . dirname ( @filename ) PathUtils . atomic_write ( @filename ) do | f | f . write ( data ) end end
Persist manfiest back to FS
2,365
def exporters_for_asset ( asset ) exporters = [ Exporters :: FileExporter ] environment . exporters . each do | mime_type , exporter_list | next unless asset . content_type next unless environment . match_mime_type? asset . content_type , mime_type exporter_list . each do | exporter | exporters << exporter end end exporters . uniq! exporters . each do | exporter | yield exporter . new ( asset : asset , environment : environment , directory : dir ) end end
Given an asset finds all exporters that match its mime - type .
2,366
def call ( env ) start_time = Time . now . to_f time_elapsed = lambda { ( ( Time . now . to_f - start_time ) * 1000 ) . to_i } unless ALLOWED_REQUEST_METHODS . include? env [ 'REQUEST_METHOD' ] return method_not_allowed_response end msg = "Served asset #{env['PATH_INFO']} -" path = Rack :: Utils . unescape ( env [ 'PATH_INFO' ] . to_s . sub ( / \/ / , '' ) ) unless path . valid_encoding? return bad_request_response ( env ) end if fingerprint = path_fingerprint ( path ) path = path . sub ( "-#{fingerprint}" , '' ) end if forbidden_request? ( path ) return forbidden_response ( env ) end if fingerprint if_match = fingerprint elsif env [ 'HTTP_IF_MATCH' ] if_match = env [ 'HTTP_IF_MATCH' ] [ / \w / , 1 ] end if env [ 'HTTP_IF_NONE_MATCH' ] if_none_match = env [ 'HTTP_IF_NONE_MATCH' ] [ / \w / , 1 ] end asset = find_asset ( path ) if asset . nil? status = :not_found elsif fingerprint && asset . etag != fingerprint status = :not_found elsif if_match && asset . etag != if_match status = :precondition_failed elsif if_none_match && asset . etag == if_none_match status = :not_modified else status = :ok end case status when :ok logger . info "#{msg} 200 OK (#{time_elapsed.call}ms)" ok_response ( asset , env ) when :not_modified logger . info "#{msg} 304 Not Modified (#{time_elapsed.call}ms)" not_modified_response ( env , if_none_match ) when :not_found logger . info "#{msg} 404 Not Found (#{time_elapsed.call}ms)" not_found_response ( env ) when :precondition_failed logger . info "#{msg} 412 Precondition Failed (#{time_elapsed.call}ms)" precondition_failed_response ( env ) end rescue Exception => e logger . error "Error compiling asset #{path}:" logger . error "#{e.class.name}: #{e.message}" case File . extname ( path ) when ".js" logger . info "#{msg} 500 Internal Server Error\n\n" return javascript_exception_response ( e ) when ".css" logger . info "#{msg} 500 Internal Server Error\n\n" return css_exception_response ( e ) else raise end end
call implements the Rack 1 . x specification which accepts an env Hash and returns a three item tuple with the status code headers and body .
2,367
def ok_response ( asset , env ) if head_request? ( env ) [ 200 , headers ( env , asset , 0 ) , [ ] ] else [ 200 , headers ( env , asset , asset . length ) , asset ] end end
Returns a 200 OK response tuple
2,368
def thumbnail ( options = { } ) options = { geometry : nil , strip : false } . merge ( options ) geometry = convert_to_geometry ( options [ :geometry ] ) thumbnail = image thumbnail = thumbnail . thumb ( geometry ) if geometry thumbnail = thumbnail . strip if options [ :strip ] thumbnail end
Get a thumbnail job object given a geometry and whether to strip image profiles and comments .
2,369
def thumbnail_dimensions ( geometry ) dimensions = ThumbnailDimensions . new ( geometry , image . width , image . height ) { width : dimensions . width , height : dimensions . height } end
Intelligently works out dimensions for a thumbnail of this image based on the Dragonfly geometry string .
2,370
def reposition_parts! reload . parts . each_with_index do | part , index | part . update_columns position : index end end
Repositions the child page_parts that belong to this page . This ensures that they are in the correct 0 1 2 3 4 ... etc order .
2,371
def path ( path_separator : ' - ' , ancestors_first : true ) return title if root? chain = ancestors_first ? self_and_ancestors : self_and_ancestors . reverse chain . map ( & :title ) . join ( path_separator ) end
Returns the full path to this page . This automatically prints out this page title and all parent page titles . The result is joined by the path_separator argument .
2,372
def site_bar_switch_link link_to_if ( admin? , t ( '.switch_to_your_website' , site_bar_translate_locale_args ) , refinery . root_path ( site_bar_translate_locale_args ) , 'data-turbolinks' => false ) do link_to t ( '.switch_to_your_website_editor' , site_bar_translate_locale_args ) , Refinery :: Core . backend_path , 'data-turbolinks' => false end end
Generates the link to determine where the site bar switch button returns to .
2,373
def image_fu ( image , geometry = nil , options = { } ) return nil if image . blank? thumbnail_args = options . slice ( :strip ) thumbnail_args [ :geometry ] = geometry if geometry image_tag_args = ( image . thumbnail_dimensions ( geometry ) rescue { } ) image_tag_args [ :alt ] = image . respond_to? ( :title ) ? image . title : image . image_name image_tag ( image . thumbnail ( thumbnail_args ) . url , image_tag_args . merge ( options ) ) end
image_fu is a helper for inserting an image that has been uploaded into a template . Say for example that we had a
2,374
def decorate ( object , options = { } ) return nil if object . nil? Worker . new ( decorator_class , object ) . call ( options . reverse_merge ( default_options ) ) end
Creates a decorator factory .
2,375
def method_missing ( method , * args , & block ) return super unless strategy . allowed? method object . send ( method , * args , & block ) . decorate end
Proxies missing query methods to the source class if the strategy allows .
2,376
def use ( * modules ) modules . to_a . flatten . compact . map do | object | mod = get_module ( object ) mod . setup ( @model_class ) if mod . respond_to? ( :setup ) @model_class . send ( :include , mod ) unless uses? object end end
Lets you specify the addon modules to use with FriendlyId .
2,377
def normalize_friendly_id ( value ) value = value . to_s . parameterize value = value [ 0 ... friendly_id_config . slug_limit ] if friendly_id_config . slug_limit value end
Process the given value to make it suitable for use as a slug .
2,378
def friendly_id ( base = nil , options = { } , & block ) yield friendly_id_config if block_given? friendly_id_config . dependent = options . delete :dependent friendly_id_config . use options . delete :use friendly_id_config . send :set , base ? options . merge ( :base => base ) : options include Model end
Configure FriendlyId s behavior in a model .
2,379
def find ( * args ) id = args . first return super if args . count != 1 || id . unfriendly_id? first_by_friendly_id ( id ) . tap { | result | return result unless result . nil? } return super if potential_primary_key? ( id ) raise_not_found_exception id end
Finds a record using the given id .
2,380
def valid_for_deletion? return false if ( id . nil? || sync_token . nil? ) id . to_i > 0 && ! sync_token . to_s . empty? && sync_token . to_i >= 0 end
To delete an account Intuit requires we provide Id and SyncToken fields
2,381
def get begin easy . http_request ( request . base_url . to_s , request . options . fetch ( :method , :get ) , sanitize ( request . options ) ) rescue Ethon :: Errors :: InvalidOption => e help = provide_help ( e . message . match ( / \s \w / ) [ 1 ] ) raise $! , "#{$!}#{help}" , $! . backtrace end set_callback easy end
Fabricated easy .
2,382
def set_callback if request . streaming? response = nil easy . on_headers do | easy | response = Response . new ( Ethon :: Easy :: Mirror . from_easy ( easy ) . options ) request . execute_headers_callbacks ( response ) end request . on_body . each do | callback | easy . on_body do | chunk , easy | callback . call ( chunk , response ) end end else easy . on_headers do | easy | request . execute_headers_callbacks ( Response . new ( Ethon :: Easy :: Mirror . from_easy ( easy ) . options ) ) end end request . on_progress . each do | callback | easy . on_progress do | dltotal , dlnow , ultotal , ulnow , easy | callback . call ( dltotal , dlnow , ultotal , ulnow , response ) end end easy . on_complete do | easy | request . finish ( Response . new ( easy . mirror . options ) ) Typhoeus :: Pool . release ( easy ) if hydra && ! hydra . queued_requests . empty? hydra . dequeue_many end end end
Sets on_complete callback on easy in order to be able to track progress .
2,383
def url easy = EasyFactory . new ( self ) . get url = easy . url Typhoeus :: Pool . release ( easy ) url end
Creates a new request .
2,384
def fuzzy_hash_eql? ( left , right ) return true if ( left == right ) ( left . count == right . count ) && left . inject ( true ) do | res , kvp | res && ( kvp [ 1 ] == right [ kvp [ 0 ] ] ) end end
Checks if two hashes are equal or not discarding first - level hash order .
2,385
def set_defaults default_user_agent = Config . user_agent || Typhoeus :: USER_AGENT options [ :headers ] = { 'User-Agent' => default_user_agent } . merge ( options [ :headers ] || { } ) options [ :headers ] [ 'Expect' ] ||= '' options [ :verbose ] = Typhoeus :: Config . verbose if options [ :verbose ] . nil? && ! Typhoeus :: Config . verbose . nil? options [ :maxredirs ] ||= 50 options [ :proxy ] = Typhoeus :: Config . proxy unless options . has_key? ( :proxy ) || Typhoeus :: Config . proxy . nil? end
Sets default header and verbose when turned on .
2,386
def and_return ( response = nil , & block ) new_response = ( response . nil? ? block : response ) responses . push ( * new_response ) end
Specify what should be returned when this expectation is hit .
2,387
def response ( request ) response = responses . fetch ( @response_counter , responses . last ) if response . respond_to? ( :call ) response = response . call ( request ) end @response_counter += 1 response . mock = @from || true response end
Return the response . When there are multiple responses they are returned one by one .
2,388
def options_match? ( request ) ( options ? options . all? { | k , v | request . original_options [ k ] == v || request . options [ k ] == v } : true ) end
Check whether the options matches the request options . I checks options and original options .
2,389
def url_match? ( request_url ) case base_url when String base_url == request_url when Regexp base_url === request_url when nil true else false end end
Check whether the base_url matches the request url . The base_url can be a string regex or nil . String and regexp are checked nil is always true else false .
2,390
def list_order ( f , attribute , options ) if is_association? ( f , attribute ) && ! options [ :collection ] begin options [ :collection ] = to_class ( attribute ) . for_fae_index rescue NameError raise "Fae::MissingCollection: `#{attribute}` isn't an orderable class, define your order using the `collection` option." end end end
sets collection to class . for_fae_index if not defined
2,391
def set_prompt ( f , attribute , options ) options [ :prompt ] = 'Select One' if is_association? ( f , attribute ) && f . object . class . reflect_on_association ( attribute ) . macro == :belongs_to && options [ :prompt ] . nil? && ! options [ :two_pane ] end
sets default prompt for pulldowns
2,392
def language_support ( f , attribute , options ) return if Fae . languages . blank? attribute_array = attribute . to_s . split ( '_' ) language_suffix = attribute_array . pop return unless Fae . languages . has_key? ( language_suffix . to_sym ) || Fae . languages . has_key? ( language_suffix ) label = attribute_array . push ( "(#{language_suffix})" ) . join ( ' ' ) . titleize options [ :label ] = label unless options [ :label ] . present? if options [ :wrapper_html ] . present? options [ :wrapper_html ] . deep_merge! ( { data : { language : language_suffix } } ) else options [ :wrapper_html ] = { data : { language : language_suffix } } end end
removes language suffix from label and adds data attr for languange nav
2,393
def update_cloneable_associations associations_for_cloning . each do | association | type = @klass . reflect_on_association ( association ) through_record = type . through_reflection if through_record . present? clone_join_relationships ( through_record . plural_name ) else clone_has_one_relationship ( association , type ) if type . macro == :has_one clone_has_many_relationships ( association ) if type . macro == :has_many end end end
set cloneable attributes and associations
2,394
def log_level ( level ) levels = { :debug => 0 , :info => 1 , :warn => 2 , :error => 3 , :fatal => 4 } unless levels . include? level raise ArgumentError , "Invalid log level: #{level.inspect}\n" "Expected one of: #{levels.keys.inspect}" end @options [ :logger ] . level = levels [ level ] end
Changes the Logger s log level .
2,395
def new_search ( * types , & block ) types . flatten! search = Search :: StandardSearch . new ( connection , setup_for_types ( types ) , Query :: StandardQuery . new ( types ) , @config ) search . build ( & block ) if block search end
Sessions are initialized with a Sunspot configuration and a Solr connection . Usually you will want to stick with the default arguments when instantiating your own sessions .
2,396
def new_more_like_this ( object , * types , & block ) types [ 0 ] ||= object . class mlt = Search :: MoreLikeThisSearch . new ( connection , setup_for_types ( types ) , Query :: MoreLikeThisQuery . new ( object , types ) , @config ) mlt . build ( & block ) if block mlt end
See Sunspot . new_more_like_this
2,397
def more_like_this ( object , * types , & block ) mlt = new_more_like_this ( object , * types , & block ) mlt . execute end
See Sunspot . more_like_this
2,398
def atomic_update ( clazz , updates = { } ) @adds += updates . keys . length indexer . add_atomic_update ( clazz , updates ) end
See Sunspot . atomic_update
2,399
def remove ( * objects , & block ) if block types = objects conjunction = Query :: Connective :: Conjunction . new if types . length == 1 conjunction . add_positive_restriction ( TypeField . instance , Query :: Restriction :: EqualTo , types . first ) else conjunction . add_positive_restriction ( TypeField . instance , Query :: Restriction :: AnyOf , types ) end dsl = DSL :: Scope . new ( conjunction , setup_for_types ( types ) ) Util . instance_eval_or_call ( dsl , & block ) indexer . remove_by_scope ( conjunction ) else objects . flatten! @deletes += objects . length objects . each do | object | indexer . remove ( object ) end end end
See Sunspot . remove