idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
0 | def render_body ( context , options ) if options . key? ( :partial ) [ render_partial ( context , options ) ] else StreamingTemplateRenderer . new ( @lookup_context ) . render ( context , options ) end end | Render but returns a valid Rack body . If fibers are defined we return a streaming body that renders the template piece by piece . |
1 | def attribute_missing ( match , * args , & block ) __send__ ( match . target , match . attr_name , * args , & block ) end | + attribute_missing + is like + method_missing + but for attributes . When + method_missing + is called we check to see if there is a matching attribute method . If so we tell + attribute_missing + to dispatch the attribute . This method can be overloaded to customize the behavior . |
2 | def matched_attribute_method ( method_name ) matches = self . class . send ( :attribute_method_matchers_matching , method_name ) matches . detect { | match | attribute_method? ( match . attr_name ) } end | Returns a struct representing the matching attribute method . The struct s attributes are prefix base and suffix . |
3 | def demodulize ( path ) path = path . to_s if i = path . rindex ( "::" ) path [ ( i + 2 ) .. - 1 ] else path end end | Removes the module part from the expression in the string . |
4 | def const_regexp ( camel_cased_word ) parts = camel_cased_word . split ( "::" ) return Regexp . escape ( camel_cased_word ) if parts . blank? last = parts . pop parts . reverse . inject ( last ) do | acc , part | part . empty? ? acc : "#{part}(::#{acc})?" end end | Mounts a regular expression returned as a string to ease interpolation that will match part by part the given constant . |
5 | def apply_inflections ( word , rules , locale = :en ) result = word . to_s . dup if word . empty? || inflections ( locale ) . uncountables . uncountable? ( result ) result else rules . each { | ( rule , replacement ) | break if result . sub! ( rule , replacement ) } result end end | Applies inflection rules for + singularize + and + pluralize + . |
6 | def autoload_module! ( into , const_name , qualified_name , path_suffix ) return nil unless base_path = autoloadable_module? ( path_suffix ) mod = Module . new into . const_set const_name , mod log ( "constant #{qualified_name} autoloaded (module autovivified from #{File.join(base_path, path_suffix)})" ) autoloaded_constants << qualified_name unless autoload_once_paths . include? ( base_path ) autoloaded_constants . uniq! mod end | Attempt to autoload the provided module name by searching for a directory matching the expected path suffix . If found the module is created and assigned to + into + s constants with the name + const_name + . Provided that the directory was loaded from a reloadable base path it is added to the set of constants that are to be unloaded . |
7 | def parse ( data ) if ! data . respond_to? ( :read ) data = StringIO . new ( data || "" ) end if data . eof? { } else silence_warnings { require "rexml/document" } unless defined? ( REXML :: Document ) doc = REXML :: Document . new ( data ) if doc . root merge_element! ( { } , doc . root , XmlMini . depth ) else raise REXML :: ParseException , "The document #{doc.to_s.inspect} does not have a valid root" end end end | Parse an XML Document string or IO into a simple hash . |
8 | def connects_to ( database : { } ) connections = [ ] database . each do | role , database_key | config_hash = resolve_config_for_connection ( database_key ) handler = lookup_connection_handler ( role . to_sym ) connections << handler . establish_connection ( config_hash ) end connections end | Connects a model to the databases specified . The + database + keyword takes a hash consisting of a + role + and a + database_key + . |
9 | def clear_query_caches_for_current_thread ActiveRecord :: Base . connection_handlers . each_value do | handler | handler . connection_pool_list . each do | pool | pool . connection . clear_query_cache if pool . active_connection? end end end | Clears the query cache for all connections associated with the current thread . |
10 | def formatted_version stringified = @version . to_s return stringified unless stringified . length == 14 stringified . insert ( 4 , "_" ) . insert ( 7 , "_" ) . insert ( 10 , "_" ) end | turns 20170404131909 into 2017_04_04_131909 |
11 | def indexes ( table , stream ) if ( indexes = @connection . indexes ( table ) ) . any? add_index_statements = indexes . map do | index | table_name = remove_prefix_and_suffix ( index . table ) . inspect " add_index #{([table_name] + index_parts(index)).join(', ')}" end stream . puts add_index_statements . sort . join ( "\n" ) stream . puts end end | Keep it for indexing materialized views |
12 | def formatted_offset ( colon = true , alternate_utc_string = nil ) utc? && alternate_utc_string || TimeZone . seconds_to_utc_offset ( utc_offset , colon ) end | Returns a formatted string of the offset from UTC or an alternative string if the time zone is already UTC . |
13 | def advance ( options ) if options . values_at ( :years , :weeks , :months , :days ) . any? method_missing ( :advance , options ) else utc . advance ( options ) . in_time_zone ( time_zone ) end end | Uses Date to provide precise Time calculations for years months and days according to the proleptic Gregorian calendar . The result is returned as a new TimeWithZone object . |
14 | def process ( action , * args ) @_action_name = action . to_s unless action_name = _find_action_name ( @_action_name ) raise ActionNotFound , "The action '#{action}' could not be found for #{self.class.name}" end @_response_body = nil process_action ( action_name , * args ) end | Calls the action going through the entire action dispatch stack . |
15 | def any? ( * candidates ) if candidates . none? super else candidates . any? do | candidate | include? ( candidate . to_sym ) || include? ( candidate . to_s ) end end end | Passes each element of + candidates + collection to ArrayInquirer collection . The method returns true if any element from the ArrayInquirer collection is equal to the stringified or symbolized form of any element in the + candidates + collection . |
16 | def cache_key if new_record? "#{model_name.cache_key}/new" else if cache_version "#{model_name.cache_key}/#{id}" else timestamp = max_updated_column_timestamp if timestamp timestamp = timestamp . utc . to_s ( cache_timestamp_format ) "#{model_name.cache_key}/#{id}-#{timestamp}" else "#{model_name.cache_key}/#{id}" end end end end | Returns a stable cache key that can be used to identify this record . |
17 | def format_paragraph ( text , len = 72 , indent = 2 ) sentences = [ [ ] ] text . split . each do | word | if sentences . first . present? && ( sentences . last + [ word ] ) . join ( " " ) . length > len sentences << [ word ] else sentences . last << word end end indentation = " " * indent sentences . map! { | sentence | "#{indentation}#{sentence.join(' ')}" } . join "\n" end | Returns + text + wrapped at + len + columns and indented + indent + spaces . By default column length + len + equals 72 characters and indent + indent + equal two spaces . |
18 | def find_in_batches ( start : nil , finish : nil , batch_size : 1000 , error_on_ignore : nil ) relation = self unless block_given? return to_enum ( :find_in_batches , start : start , finish : finish , batch_size : batch_size , error_on_ignore : error_on_ignore ) do total = apply_limits ( relation , start , finish ) . size ( total - 1 ) . div ( batch_size ) + 1 end end in_batches ( of : batch_size , start : start , finish : finish , load : true , error_on_ignore : error_on_ignore ) do | batch | yield batch . to_a end end | Yields each batch of records that was found by the find options as an array . |
19 | def match? ( attribute , type = nil , ** options ) if @attribute != attribute || ( type && @type != type ) return false end options . each do | key , value | if @options [ key ] != value return false end end true end | See if error matches provided + attribute + + type + and + options + . |
20 | def fetch_or_cache_partial ( cached_partials , template , order_by : ) order_by . each_with_object ( { } ) do | cache_key , hash | hash [ cache_key ] = if content = cached_partials [ cache_key ] build_rendered_template ( content , template ) else yield . tap do | rendered_partial | collection_cache . write ( cache_key , rendered_partial . body ) end end end end | order_by is an enumerable object containing keys of the cache all keys are passed in whether found already or not . |
21 | def run_callbacks ( kind ) callbacks = __callbacks [ kind . to_sym ] if callbacks . empty? yield if block_given? else env = Filters :: Environment . new ( self , false , nil ) next_sequence = callbacks . compile invoke_sequence = Proc . new do skipped = nil while true current = next_sequence current . invoke_before ( env ) if current . final? env . value = ! env . halted && ( ! block_given? || yield ) elsif current . skip? ( env ) ( skipped ||= [ ] ) << current next_sequence = next_sequence . nested next else next_sequence = next_sequence . nested begin target , block , method , * arguments = current . expand_call_template ( env , invoke_sequence ) target . send ( method , * arguments , & block ) ensure next_sequence = current end end current . invoke_after ( env ) skipped . pop . invoke_after ( env ) while skipped && skipped . first break env . value end end if next_sequence . final? next_sequence . invoke_before ( env ) env . value = ! env . halted && ( ! block_given? || yield ) next_sequence . invoke_after ( env ) env . value else invoke_sequence . call end end end | Runs the callbacks for the given event . |
22 | def extract_annotations_from ( file , pattern ) lineno = 0 result = File . readlines ( file , encoding : Encoding :: BINARY ) . inject ( [ ] ) do | list , line | lineno += 1 next list unless line =~ pattern list << Annotation . new ( lineno , $1 , $2 ) end result . empty? ? { } : { file => result } end | If + file + is the filename of a file that contains annotations this method returns a hash with a single entry that maps + file + to an array of its annotations . Otherwise it returns an empty hash . |
23 | def _wrapper_enabled? return false unless request . has_content_type? ref = request . content_mime_type . ref _wrapper_formats . include? ( ref ) && _wrapper_key && ! request . parameters . key? ( _wrapper_key ) end | Checks if we should perform parameters wrapping . |
24 | def new_session app = Rails . application session = ActionDispatch :: Integration :: Session . new ( app ) yield session if block_given? session . extend ( app . routes . url_helpers ) session . extend ( app . routes . mounted_helpers ) session end | create a new session . If a block is given the new session will be yielded to the block before being returned . |
25 | def reload! ( print = true ) puts "Reloading..." if print Rails . application . reloader . reload! true end | reloads the environment |
26 | def dom_id ( record , prefix = nil ) if record_id = record_key_for_dom_id ( record ) "#{dom_class(record, prefix)}#{JOIN}#{record_id}" else dom_class ( record , prefix || NEW ) end end | The DOM id convention is to use the singular form of an object or class with the id following an underscore . If no id is found prefix with new_ instead . |
27 | def included ( base = nil , & block ) if base . nil? if instance_variable_defined? ( :@_included_block ) if @_included_block . source_location != block . source_location raise MultipleIncludedBlocks end else @_included_block = block end else super end end | Evaluate given block in context of base class so that you can write class macros here . When you define more than one + included + block it raises an exception . |
28 | def class_methods ( & class_methods_module_definition ) mod = const_defined? ( :ClassMethods , false ) ? const_get ( :ClassMethods ) : const_set ( :ClassMethods , Module . new ) mod . module_eval ( & class_methods_module_definition ) end | Define class methods from given block . You can define private class methods as well . |
29 | def cache ( key , options = { } , & block ) if cache_configured? cache_store . fetch ( ActiveSupport :: Cache . expand_cache_key ( key , :controller ) , options , & block ) else yield end end | Convenience accessor . |
30 | def valid_message? ( signed_message ) return if signed_message . nil? || ! signed_message . valid_encoding? || signed_message . blank? data , digest = signed_message . split ( "--" ) data . present? && digest . present? && ActiveSupport :: SecurityUtils . secure_compare ( digest , generate_digest ( data ) ) end | Checks if a signed message could have been generated by signing an object with the + MessageVerifier + s secret . |
31 | def verified ( signed_message , purpose : nil , ** ) if valid_message? ( signed_message ) begin data = signed_message . split ( "--" ) [ 0 ] message = Messages :: Metadata . verify ( decode ( data ) , purpose ) @serializer . load ( message ) if message rescue ArgumentError => argument_error return if argument_error . message . include? ( "invalid base64" ) raise end end end | Decodes the signed message using the + MessageVerifier + s secret . |
32 | def generate ( value , expires_at : nil , expires_in : nil , purpose : nil ) data = encode ( Messages :: Metadata . wrap ( @serializer . dump ( value ) , expires_at : expires_at , expires_in : expires_in , purpose : purpose ) ) "#{data}--#{generate_digest(data)}" end | Generates a signed message for the provided value . |
33 | def serialize { "job_class" => self . class . name , "job_id" => job_id , "provider_job_id" => provider_job_id , "queue_name" => queue_name , "priority" => priority , "arguments" => serialize_arguments_if_needed ( arguments ) , "executions" => executions , "exception_executions" => exception_executions , "locale" => I18n . locale . to_s , "timezone" => Time . zone . try ( :name ) , "enqueued_at" => Time . now . utc . iso8601 } end | Creates a new job instance . Takes the arguments that will be passed to the perform method . Returns a hash with the job data that can safely be passed to the queuing adapter . |
34 | def deserialize ( job_data ) self . job_id = job_data [ "job_id" ] self . provider_job_id = job_data [ "provider_job_id" ] self . queue_name = job_data [ "queue_name" ] self . priority = job_data [ "priority" ] self . serialized_arguments = job_data [ "arguments" ] self . executions = job_data [ "executions" ] self . exception_executions = job_data [ "exception_executions" ] self . locale = job_data [ "locale" ] || I18n . locale . to_s self . timezone = job_data [ "timezone" ] || Time . zone . try ( :name ) self . enqueued_at = job_data [ "enqueued_at" ] end | Attaches the stored job data to the current instance . Receives a hash returned from + serialize + |
35 | def match? ( path ) path = :: Rack :: Utils . unescape_path path return false unless :: Rack :: Utils . valid_path? path path = :: Rack :: Utils . clean_path_info path paths = [ path , "#{path}#{ext}" , "#{path}/#{@index}#{ext}" ] if match = paths . detect { | p | path = File . join ( @root , p . b ) begin File . file? ( path ) && File . readable? ( path ) rescue SystemCallError false end } return :: Rack :: Utils . escape_path ( match ) . b end end | Takes a path to a file . If the file is found has valid encoding and has correct read permissions the return value is a URI - escaped string representing the filename . Otherwise false is returned . |
36 | def + ( other ) if Duration === other parts = @parts . dup other . parts . each do | ( key , value ) | parts [ key ] += value end Duration . new ( value + other . value , parts ) else seconds = @parts [ :seconds ] + other Duration . new ( value + other , @parts . merge ( seconds : seconds ) ) end end | Compares one Duration with another or a Numeric to this Duration . Numeric values are treated as seconds . Adds another Duration or a Numeric to this Duration . Numeric values are treated as seconds . |
37 | def * ( other ) if Scalar === other || Duration === other Duration . new ( value * other . value , parts . map { | type , number | [ type , number * other . value ] } ) elsif Numeric === other Duration . new ( value * other , parts . map { | type , number | [ type , number * other ] } ) else raise_type_error ( other ) end end | Multiplies this Duration by a Numeric and returns a new Duration . |
38 | def % ( other ) if Duration === other || Scalar === other Duration . build ( value % other . value ) elsif Numeric === other Duration . build ( value % other ) else raise_type_error ( other ) end end | Returns the modulo of this Duration by another Duration or Numeric . Numeric values are treated as seconds . |
39 | def locale = ( value ) if value config = I18n . config . respond_to? ( :original_config ) ? I18n . config . original_config : I18n . config config . locale = value end super ( default_locale ) end | Overload locale = to also set the I18n . locale . If the current I18n . config object responds to original_config it means that it has a copy of the original I18n configuration and it s acting as proxy which we need to skip . |
40 | def find_all ( name , prefix = nil , partial = false , details = { } , key = nil , locals = [ ] ) locals = locals . map ( & :to_s ) . sort! . freeze cached ( key , [ name , prefix , partial ] , details , locals ) do _find_all ( name , prefix , partial , details , key , locals ) end end | Normalizes the arguments and passes it on to find_templates . |
41 | def cached ( key , path_info , details , locals ) name , prefix , partial = path_info if key @cache . cache ( key , name , prefix , partial , locals ) do yield end else yield end end | Handles templates caching . If a key is given and caching is on always check the cache before hitting the resolver . Otherwise it always hits the resolver but if the key is present check if the resolver is fresher before returning it . |
42 | def extract_handler_and_format_and_variant ( path ) pieces = File . basename ( path ) . split ( "." ) pieces . shift extension = pieces . pop handler = Template . handler_for_extension ( extension ) format , variant = pieces . last . split ( EXTENSIONS [ :variants ] , 2 ) if pieces . last format = if format Template :: Types [ format ] &. ref else if handler . respond_to? ( :default_format ) handler . default_format else nil end end [ handler , format , variant ] end | Extract handler formats and variant from path . If a format cannot be found neither from the path or the handler we should return the array of formats given to the resolver . |
43 | def render_template ( view , template , layout_name = nil , locals = { } ) return [ super . body ] unless layout_name && template . supports_streaming? locals ||= { } layout = layout_name && find_layout ( layout_name , locals . keys , [ formats . first ] ) Body . new do | buffer | delayed_render ( buffer , template , layout , view , locals ) end end | For streaming instead of rendering a given a template we return a Body object that responds to each . This object is initialized with a block that knows how to render the template . |
44 | def record_changed? ( reflection , record , key ) record . new_record? || association_foreign_key_changed? ( reflection , record , key ) || record . will_save_change_to_attribute? ( reflection . foreign_key ) end | If the record is new or it has changed returns true . |
45 | def transliterate ( string , replacement = "?" , locale : nil ) raise ArgumentError , "Can only transliterate strings. Received #{string.class.name}" unless string . is_a? ( String ) I18n . transliterate ( ActiveSupport :: Multibyte :: Unicode . tidy_bytes ( string ) . unicode_normalize ( :nfc ) , replacement : replacement , locale : locale ) end | Replaces non - ASCII characters with an ASCII approximation or if none exists a replacement character which defaults to ? . |
46 | def import ( error , override_options = { } ) [ :attribute , :type ] . each do | key | if override_options . key? ( key ) override_options [ key ] = override_options [ key ] . to_sym end end @errors . append ( NestedError . new ( @base , error , override_options ) ) end | Imports one error Imported errors are wrapped as a NestedError providing access to original error object . If attribute or type needs to be overriden use override_options . |
47 | def slice! ( * keys ) deprecation_removal_warning ( :slice! ) keys = keys . map ( & :to_sym ) results = messages . dup . slice! ( * keys ) @errors . keep_if do | error | keys . include? ( error . attribute ) end results end | Removes all errors except the given keys . Returns a hash containing the removed errors . |
48 | def where ( attribute , type = nil , ** options ) attribute , type , options = normalize_arguments ( attribute , type , options ) @errors . select { | error | error . match? ( attribute , type , options ) } end | Search for errors matching + attribute + + type + or + options + . |
49 | def delete ( attribute , type = nil , ** options ) attribute , type , options = normalize_arguments ( attribute , type , options ) matches = where ( attribute , type , options ) matches . each do | error | @errors . delete ( error ) end matches . map ( & :message ) end | Delete messages for + key + . Returns the deleted messages . |
50 | def each ( & block ) if block . arity == 1 @errors . each ( & block ) else ActiveSupport :: Deprecation . warn ( <<~MSG ) MSG @errors . sort { | a , b | a . attribute <=> b . attribute } . each { | error | yield error . attribute , error . message } end end | Iterates through each error key value pair in the error messages hash . Yields the attribute and the error for that attribute . If the attribute has more than one error message yields once for each error message . |
51 | def to_xml ( options = { } ) deprecation_removal_warning ( :to_xml ) to_a . to_xml ( { root : "errors" , skip_types : true } . merge! ( options ) ) end | Returns an xml formatted representation of the Errors hash . |
52 | def revert ( * migration_classes ) run ( * migration_classes . reverse , revert : true ) unless migration_classes . empty? if block_given? if connection . respond_to? :revert connection . revert { yield } else recorder = command_recorder @connection = recorder suppress_messages do connection . revert { yield } end @connection = recorder . delegate recorder . replay ( self ) end end end | Reverses the migration commands for the given block and the given migrations . |
53 | def say_with_time ( message ) say ( message ) result = nil time = Benchmark . measure { result = yield } say "%.4fs" % time . real , :subitem say ( "#{result} rows" , :subitem ) if result . is_a? ( Integer ) result end | Outputs text along with how long it took to run its block . If the block returns an integer it assumes it is the number of rows affected . |
54 | def next_migration_number ( number ) if ActiveRecord :: Base . timestamped_migrations [ Time . now . utc . strftime ( "%Y%m%d%H%M%S" ) , "%.14d" % number ] . max else SchemaMigration . normalize_migration_number ( number ) end end | Determines the version number of the next migration . |
55 | def run_without_lock migration = migrations . detect { | m | m . version == @target_version } raise UnknownMigrationVersionError . new ( @target_version ) if migration . nil? result = execute_migration_in_transaction ( migration , @direction ) record_environment result end | Used for running a specific migration . |
56 | def migrate_without_lock if invalid_target? raise UnknownMigrationVersionError . new ( @target_version ) end result = runnable . each do | migration | execute_migration_in_transaction ( migration , @direction ) end record_environment result end | Used for running multiple migrations up to or down to a certain value . |
57 | def permit! each_pair do | key , value | Array . wrap ( value ) . flatten . each do | v | v . permit! if v . respond_to? :permit! end end @permitted = true self end | Sets the + permitted + attribute to + true + . This can be used to pass mass assignment . Returns + self + . |
58 | def require ( key ) return key . map { | k | require ( k ) } if key . is_a? ( Array ) value = self [ key ] if value . present? || value == false value else raise ParameterMissing . new ( key ) end end | This method accepts both a single key and an array of keys . |
59 | def permitted_scalar_filter ( params , permitted_key ) permitted_key = permitted_key . to_s if has_key? ( permitted_key ) && permitted_scalar? ( self [ permitted_key ] ) params [ permitted_key ] = self [ permitted_key ] end each_key do | key | next unless key =~ / \( \d \) \z / next unless $~ . pre_match == permitted_key params [ key ] = self [ key ] if permitted_scalar? ( self [ key ] ) end end | Adds existing keys to the params if their values are scalar . |
60 | def process ( * ) old_config , I18n . config = I18n . config , I18nProxy . new ( I18n . config , lookup_context ) super ensure I18n . config = old_config end | Overwrite process to setup I18n proxy . |
61 | def _render_template ( options ) variant = options . delete ( :variant ) assigns = options . delete ( :assigns ) context = view_context context . assign assigns if assigns lookup_context . variants = variant if variant rendered_template = context . in_rendering_context ( options ) do | renderer | renderer . render_to_object ( context , options ) end rendered_format = rendered_template . format || lookup_context . formats . first @rendered_format = Template :: Types [ rendered_format ] rendered_template . body end | Find and render a template based on the options given . |
62 | def _normalize_options ( options ) options = super ( options ) if options [ :partial ] == true options [ :partial ] = action_name end if ( options . keys & [ :partial , :file , :template ] ) . empty? options [ :prefixes ] ||= _prefixes end options [ :template ] ||= ( options [ :action ] || action_name ) . to_s options end | Normalize options . |
63 | def enqueue ( options = { } ) self . scheduled_at = options [ :wait ] . seconds . from_now . to_f if options [ :wait ] self . scheduled_at = options [ :wait_until ] . to_f if options [ :wait_until ] self . queue_name = self . class . queue_name_from_part ( options [ :queue ] ) if options [ :queue ] self . priority = options [ :priority ] . to_i if options [ :priority ] successfully_enqueued = false run_callbacks :enqueue do if scheduled_at self . class . queue_adapter . enqueue_at self , scheduled_at else self . class . queue_adapter . enqueue self end successfully_enqueued = true end if successfully_enqueued self else if self . class . return_false_on_aborted_enqueue false else ActiveSupport :: Deprecation . warn ( "Rails 6.1 will return false when the enqueuing is aborted. Make sure your code doesn't depend on it" " returning the instance of the job and set `config.active_job.return_false_on_aborted_enqueue = true`" " to remove the deprecations." ) self end end end | Enqueues the job to be performed by the queue adapter . |
64 | def table_rows fixtures . delete ( "DEFAULTS" ) TableRows . new ( table_name , model_class : model_class , fixtures : fixtures , config : config , ) . to_hash end | Returns a hash of rows to be inserted . The key is the table the value is a list of rows to insert to that table . |
65 | def read_fixture_files ( path ) yaml_files = Dir [ "#{path}/{**,*}/*.yml" ] . select { | f | :: File . file? ( f ) } + [ yaml_file_path ( path ) ] yaml_files . each_with_object ( { } ) do | file , fixtures | FixtureSet :: File . open ( file ) do | fh | self . model_class ||= fh . model_class if fh . model_class fh . each do | fixture_name , row | fixtures [ fixture_name ] = ActiveRecord :: Fixture . new ( row , model_class ) end end end end | Loads the fixtures from the YAML file at + path + . If the file sets the + model_class + and current instance value is not set it uses the file value . |
66 | def download_blob_to ( file ) file . binmode blob . download { | chunk | file . write ( chunk ) } file . flush file . rewind end | Efficiently downloads blob data into the given file . |
67 | def expires_in ( seconds , options = { } ) response . cache_control . merge! ( max_age : seconds , public : options . delete ( :public ) , must_revalidate : options . delete ( :must_revalidate ) , stale_while_revalidate : options . delete ( :stale_while_revalidate ) , stale_if_error : options . delete ( :stale_if_error ) , ) options . delete ( :private ) response . cache_control [ :extras ] = options . map { | k , v | "#{k}=#{v}" } response . date = Time . now unless response . date? end | Sets an HTTP 1 . 1 Cache - Control header . Defaults to issuing a + private + instruction so that intermediate caches must not cache the response . |
68 | def http_cache_forever ( public : false ) expires_in 100 . years , public : public yield if stale? ( etag : request . fullpath , last_modified : Time . new ( 2011 , 1 , 1 ) . utc , public : public ) end | Cache or yield the block . The cache is supposed to never expire . |
69 | def draw ( * argv ) open_tempfile do | file | instrument :preview , key : blob . key do capture ( * argv , to : file ) end yield file end end | Executes a system command capturing its binary output in a tempfile . Yields the tempfile . |
70 | def render_to_string ( * ) result = super if result . respond_to? ( :each ) string = + "" result . each { | r | string << r } string else result end end | Overwrite render_to_string because body can now be set to a Rack body . |
71 | def _normalize_options ( options ) _normalize_text ( options ) if options [ :html ] options [ :html ] = ERB :: Util . html_escape ( options [ :html ] ) end if options [ :status ] options [ :status ] = Rack :: Utils . status_code ( options [ :status ] ) end super end | Normalize both text and status options . |
72 | def _process_options ( options ) status , content_type , location = options . values_at ( :status , :content_type , :location ) self . status = status if status self . content_type = content_type if content_type headers [ "Location" ] = url_for ( location ) if location super end | Process controller specific options as status content - type and location . |
73 | def call ( env ) req = ActionDispatch :: Request . new env req . remote_ip = GetIp . new ( req , check_ip , proxies ) @app . call ( req . env ) end | Create a new + RemoteIp + middleware instance . |
74 | def validates_with ( * args , & block ) options = args . extract_options! options [ :class ] = self . class args . each do | klass | validator = klass . new ( options , & block ) validator . validate ( self ) end end | Passes the record off to the class or classes specified and allows them to add errors based on more complex conditions . |
75 | def render ( view , locals , buffer = ActionView :: OutputBuffer . new , & block ) instrument_render_template do compile! ( view ) view . _run ( method_name , self , locals , buffer , & block ) end rescue => e handle_render_error ( view , e ) end | Render a template . If the template was not compiled yet it is done exactly before rendering . |
76 | def compile! ( view ) return if @compiled @compile_mutex . synchronize do return if @compiled mod = view . compiled_method_container instrument ( "!compile_template" ) do compile ( mod ) end @compiled = true end end | Compile a template . This method ensures a template is compiled just once and removes the source after it is compiled . |
77 | def reload ( options = nil ) self . class . connection . clear_query_cache fresh_object = if options && options [ :lock ] self . class . unscoped { self . class . lock ( options [ :lock ] ) . find ( id ) } else self . class . unscoped { self . class . find ( id ) } end @attributes = fresh_object . instance_variable_get ( "@attributes" ) @new_record = false self end | Reloads the record from the database . |
78 | def masked_authenticity_token ( session , form_options : { } ) action , method = form_options . values_at ( :action , :method ) raw_token = if per_form_csrf_tokens && action && method action_path = normalize_action_path ( action ) per_form_csrf_token ( session , action_path , method ) else real_csrf_token ( session ) end one_time_pad = SecureRandom . random_bytes ( AUTHENTICITY_TOKEN_LENGTH ) encrypted_csrf_token = xor_byte_strings ( one_time_pad , raw_token ) masked_token = one_time_pad + encrypted_csrf_token Base64 . strict_encode64 ( masked_token ) end | Creates a masked version of the authenticity token that varies on each request . The masking is used to mitigate SSL attacks like BREACH . |
79 | def valid_authenticity_token? ( session , encoded_masked_token ) if encoded_masked_token . nil? || encoded_masked_token . empty? || ! encoded_masked_token . is_a? ( String ) return false end begin masked_token = Base64 . strict_decode64 ( encoded_masked_token ) rescue ArgumentError return false end if masked_token . length == AUTHENTICITY_TOKEN_LENGTH compare_with_real_token masked_token , session elsif masked_token . length == AUTHENTICITY_TOKEN_LENGTH * 2 csrf_token = unmask_token ( masked_token ) compare_with_real_token ( csrf_token , session ) || valid_per_form_csrf_token? ( csrf_token , session ) else false end end | Checks the client s masked token to see if it matches the session token . Essentially the inverse of + masked_authenticity_token + . |
80 | def valid_request_origin? if forgery_protection_origin_check raise InvalidAuthenticityToken , NULL_ORIGIN_MESSAGE if request . origin == "null" request . origin . nil? || request . origin == request . base_url else true end end | Checks if the request originated from the same origin by looking at the Origin header . |
81 | def remember_transaction_record_state @_start_transaction_state ||= { id : id , new_record : @new_record , destroyed : @destroyed , attributes : @attributes , frozen? : frozen? , level : 0 } @_start_transaction_state [ :level ] += 1 remember_new_record_before_last_commit end | Save the new record state and id of a record so it can be restored later if a transaction fails . |
82 | def sync_with_transaction_state if transaction_state = @transaction_state if transaction_state . fully_committed? force_clear_transaction_record_state elsif transaction_state . committed? clear_transaction_record_state elsif transaction_state . rolledback? force_restore_state = transaction_state . fully_rolledback? restore_transaction_record_state ( force_restore_state ) clear_transaction_record_state end end end | Updates the attributes on this particular Active Record object so that if it s associated with a transaction then the state of the Active Record object will be updated to reflect the current state of the transaction . |
83 | def fixed_length_secure_compare ( a , b ) raise ArgumentError , "string length mismatch." unless a . bytesize == b . bytesize l = a . unpack "C#{a.bytesize}" res = 0 b . each_byte { | byte | res |= byte ^ l . shift } res == 0 end | Constant time string comparison for fixed length strings . |
84 | def secure_compare ( a , b ) fixed_length_secure_compare ( :: Digest :: SHA256 . digest ( a ) , :: Digest :: SHA256 . digest ( b ) ) && a == b end | Constant time string comparison for variable length strings . |
85 | def on_load ( name , options = { } , & block ) @loaded [ name ] . each do | base | execute_hook ( name , base , options , block ) end @load_hooks [ name ] << [ block , options ] end | Declares a block that will be executed when a Rails component is fully loaded . |
86 | def view_assigns protected_vars = _protected_ivars variables = instance_variables variables . reject! { | s | protected_vars . include? s } variables . each_with_object ( { } ) { | name , hash | hash [ name . slice ( 1 , name . length ) ] = instance_variable_get ( name ) } end | This method should return a hash with assigns . You can overwrite this configuration per controller . |
87 | def _normalize_render ( * args , & block ) options = _normalize_args ( * args , & block ) _process_variant ( options ) _normalize_options ( options ) options end | Normalize args and options . |
88 | def to_s ( format = nil , options = nil ) case format when nil super ( ) when Integer , String super ( format ) when :phone ActiveSupport :: NumberHelper . number_to_phone ( self , options || { } ) when :currency ActiveSupport :: NumberHelper . number_to_currency ( self , options || { } ) when :percentage ActiveSupport :: NumberHelper . number_to_percentage ( self , options || { } ) when :delimited ActiveSupport :: NumberHelper . number_to_delimited ( self , options || { } ) when :rounded ActiveSupport :: NumberHelper . number_to_rounded ( self , options || { } ) when :human ActiveSupport :: NumberHelper . number_to_human ( self , options || { } ) when :human_size ActiveSupport :: NumberHelper . number_to_human_size ( self , options || { } ) when Symbol super ( ) else super ( format ) end end | Provides options for converting numbers into formatted strings . Options are provided for phone numbers currency percentage precision positional notation file size and pretty printing . |
89 | def default_hash ( env = ActiveRecord :: ConnectionHandling :: DEFAULT_ENV . call . to_s ) default = find_db_config ( env ) default . config if default end | Returns the config hash that corresponds with the environment |
90 | def find_db_config ( env ) configurations . find do | db_config | db_config . env_name == env . to_s || ( db_config . for_current_env? && db_config . spec_name == env . to_s ) end end | Returns a single DatabaseConfig object based on the requested environment . |
91 | def to_h configs = configurations . reverse . inject ( { } ) do | memo , db_config | memo . merge ( db_config . to_legacy_hash ) end Hash [ configs . to_a . reverse ] end | Returns the DatabaseConfigurations object as a Hash . |
92 | def deliver ( event ) info do perform_deliveries = event . payload [ :perform_deliveries ] if perform_deliveries "Delivered mail #{event.payload[:message_id]} (#{event.duration.round(1)}ms)" else "Skipped delivery of mail #{event.payload[:message_id]} as `perform_deliveries` is false" end end debug { event . payload [ :mail ] } end | An email was delivered . |
93 | def clean ( backtrace , kind = :silent ) filtered = filter_backtrace ( backtrace ) case kind when :silent silence ( filtered ) when :noise noise ( filtered ) else filtered end end | Returns the backtrace after all filters and silencers have been run against it . Filters run first then silencers . |
94 | def determine_template ( options ) keys = options . has_key? ( :locals ) ? options [ :locals ] . keys : [ ] if options . key? ( :body ) Template :: Text . new ( options [ :body ] ) elsif options . key? ( :plain ) Template :: Text . new ( options [ :plain ] ) elsif options . key? ( :html ) Template :: HTML . new ( options [ :html ] , formats . first ) elsif options . key? ( :file ) if File . exist? ( options [ :file ] ) Template :: RawFile . new ( options [ :file ] ) else ActiveSupport :: Deprecation . warn "render file: should be given the absolute path to a file" @lookup_context . with_fallbacks . find_template ( options [ :file ] , nil , false , keys , @details ) end elsif options . key? ( :inline ) handler = Template . handler_for_extension ( options [ :type ] || "erb" ) format = if handler . respond_to? ( :default_format ) handler . default_format else @lookup_context . formats . first end Template :: Inline . new ( options [ :inline ] , "inline template" , handler , locals : keys , format : format ) elsif options . key? ( :template ) if options [ :template ] . respond_to? ( :render ) options [ :template ] else @lookup_context . find_template ( options [ :template ] , options [ :prefixes ] , false , keys , @details ) end else raise ArgumentError , "You invoked render but did not give any of :partial, :template, :inline, :file, :plain, :html or :body option." end end | Determine the template to be rendered using the given options . |
95 | def render_template ( view , template , layout_name , locals ) render_with_layout ( view , template , layout_name , locals ) do | layout | instrument ( :template , identifier : template . identifier , layout : layout . try ( :virtual_path ) ) do template . render ( view , locals ) { | * name | view . _layout_for ( * name ) } end end end | Renders the given template . A string representing the layout can be supplied as well . |
96 | def _process_options ( options ) super if options [ :stream ] if request . version == "HTTP/1.0" options . delete ( :stream ) else headers [ "Cache-Control" ] ||= "no-cache" headers [ "Transfer-Encoding" ] = "chunked" headers . delete ( "Content-Length" ) end end end | Set proper cache control and transfer encoding when streaming |
97 | def _render_template ( options ) if options . delete ( :stream ) Rack :: Chunked :: Body . new view_renderer . render_body ( view_context , options ) else super end end | Call render_body if we are streaming instead of usual + render + . |
98 | def _layout_for_option ( name ) case name when String then _normalize_layout ( name ) when Proc then name when true then Proc . new { | lookup_context , formats | _default_layout ( lookup_context , formats , true ) } when :default then Proc . new { | lookup_context , formats | _default_layout ( lookup_context , formats , false ) } when false , nil then nil else raise ArgumentError , "String, Proc, :default, true, or false, expected for `layout'; you passed #{name.inspect}" end end | Determine the layout for a given name taking into account the name type . |
99 | def _default_layout ( lookup_context , formats , require_layout = false ) begin value = _layout ( lookup_context , formats ) if action_has_layout? rescue NameError => e raise e , "Could not render layout: #{e.message}" end if require_layout && action_has_layout? && ! value raise ArgumentError , "There was no default layout for #{self.class} in #{view_paths.inspect}" end _normalize_layout ( value ) end | Returns the default layout for this controller . Optionally raises an exception if the layout could not be found . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.