Datasets:

ArXiv:
Tags:
License:
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
sequence
docstring
stringlengths
8
16k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
rails/rails
actionview/lib/action_view/renderer/renderer.rb
ActionView.Renderer.render_body
def render_body(context, options) if options.key?(:partial) [render_partial(context, options)] else StreamingTemplateRenderer.new(@lookup_context).render(context, options) end end
ruby
def render_body(context, options) if options.key?(:partial) [render_partial(context, options)] else StreamingTemplateRenderer.new(@lookup_context).render(context, options) end end
[ "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. Note that partials are not supported to be rendered with streaming, so in such cases, we just wrap them in an array.
[ "Render", "but", "returns", "a", "valid", "Rack", "body", ".", "If", "fibers", "are", "defined", "we", "return", "a", "streaming", "body", "that", "renders", "the", "template", "piece", "by", "piece", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/renderer/renderer.rb#L38-L44
train
rails/rails
activemodel/lib/active_model/attribute_methods.rb
ActiveModel.AttributeMethods.attribute_missing
def attribute_missing(match, *args, &block) __send__(match.target, match.attr_name, *args, &block) end
ruby
def attribute_missing(match, *args, &block) __send__(match.target, match.attr_name, *args, &block) end
[ "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.
[ "+", "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/attribute_methods.rb#L439-L441
train
rails/rails
activemodel/lib/active_model/attribute_methods.rb
ActiveModel.AttributeMethods.matched_attribute_method
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
ruby
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
[ "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.
[ "Returns", "a", "struct", "representing", "the", "matching", "attribute", "method", ".", "The", "struct", "s", "attributes", "are", "prefix", "base", "and", "suffix", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/attribute_methods.rb#L466-L469
train
rails/rails
activesupport/lib/active_support/inflector/methods.rb
ActiveSupport.Inflector.demodulize
def demodulize(path) path = path.to_s if i = path.rindex("::") path[(i + 2)..-1] else path end end
ruby
def demodulize(path) path = path.to_s if i = path.rindex("::") path[(i + 2)..-1] else path end end
[ "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. demodulize('ActiveSupport::Inflector::Inflections') # => "Inflections" demodulize('Inflections') # => "Inflections" demodulize('::Inflections') # => "Inflections" demodulize('') # => "" See also #deconstantize.
[ "Removes", "the", "module", "part", "from", "the", "expression", "in", "the", "string", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/inflector/methods.rb#L220-L227
train
rails/rails
activesupport/lib/active_support/inflector/methods.rb
ActiveSupport.Inflector.const_regexp
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
ruby
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
[ "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. const_regexp("Foo::Bar::Baz") # => "Foo(::Bar(::Baz)?)?" const_regexp("::") # => "::"
[ "Mounts", "a", "regular", "expression", "returned", "as", "a", "string", "to", "ease", "interpolation", "that", "will", "match", "part", "by", "part", "the", "given", "constant", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/inflector/methods.rb#L368-L378
train
rails/rails
activesupport/lib/active_support/inflector/methods.rb
ActiveSupport.Inflector.apply_inflections
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
ruby
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
[ "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+. If passed an optional +locale+ parameter, the uncountables will be found for that locale. apply_inflections('post', inflections.plurals, :en) # => "posts" apply_inflections('posts', inflections.singulars, :en) # => "post"
[ "Applies", "inflection", "rules", "for", "+", "singularize", "+", "and", "+", "pluralize", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/inflector/methods.rb#L387-L396
train
rails/rails
activesupport/lib/active_support/dependencies.rb
ActiveSupport.Dependencies.autoload_module!
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/dependencies.rb#L464-L472
train
rails/rails
activesupport/lib/active_support/xml_mini/rexml.rb
ActiveSupport.XmlMini_REXML.parse
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
ruby
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
[ "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. Same as XmlSimple::xml_in but doesn't shoot itself in the foot, and uses the defaults from Active Support. data:: XML Document string or IO to parse
[ "Parse", "an", "XML", "Document", "string", "or", "IO", "into", "a", "simple", "hash", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/xml_mini/rexml.rb#L20-L38
train
rails/rails
activerecord/lib/active_record/connection_handling.rb
ActiveRecord.ConnectionHandling.connects_to
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
ruby
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
[ "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+. This will create a connection handler for switching between connections, look up the config hash using the +database_key+ and finally establishes a connection to that config. class AnimalsModel < ApplicationRecord self.abstract_class = true connects_to database: { writing: :primary, reading: :primary_replica } end Returns an array of established connections.
[ "Connects", "a", "model", "to", "the", "databases", "specified", ".", "The", "+", "database", "+", "keyword", "takes", "a", "hash", "consisting", "of", "a", "+", "role", "+", "and", "a", "+", "database_key", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/connection_handling.rb#L68-L79
train
rails/rails
activerecord/lib/active_record/connection_handling.rb
ActiveRecord.ConnectionHandling.clear_query_caches_for_current_thread
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
ruby
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
[ "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.
[ "Clears", "the", "query", "cache", "for", "all", "connections", "associated", "with", "the", "current", "thread", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/connection_handling.rb#L187-L193
train
rails/rails
activerecord/lib/active_record/schema_dumper.rb
ActiveRecord.SchemaDumper.formatted_version
def formatted_version stringified = @version.to_s return stringified unless stringified.length == 14 stringified.insert(4, "_").insert(7, "_").insert(10, "_") end
ruby
def formatted_version stringified = @version.to_s return stringified unless stringified.length == 14 stringified.insert(4, "_").insert(7, "_").insert(10, "_") end
[ "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"
[ "turns", "20170404131909", "into", "2017_04_04_131909" ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/schema_dumper.rb#L59-L63
train
rails/rails
activerecord/lib/active_record/schema_dumper.rb
ActiveRecord.SchemaDumper.indexes
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
ruby
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
[ "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
[ "Keep", "it", "for", "indexing", "materialized", "views" ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/schema_dumper.rb#L171-L181
train
rails/rails
activesupport/lib/active_support/time_with_zone.rb
ActiveSupport.TimeWithZone.formatted_offset
def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) end
ruby
def formatted_offset(colon = true, alternate_utc_string = nil) utc? && alternate_utc_string || TimeZone.seconds_to_utc_offset(utc_offset, colon) end
[ "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. Time.zone = 'Eastern Time (US & Canada)' # => "Eastern Time (US & Canada)" Time.zone.now.formatted_offset(true) # => "-05:00" Time.zone.now.formatted_offset(false) # => "-0500" Time.zone = 'UTC' # => "UTC" Time.zone.now.formatted_offset(true, "0") # => "0"
[ "Returns", "a", "formatted", "string", "of", "the", "offset", "from", "UTC", "or", "an", "alternative", "string", "if", "the", "time", "zone", "is", "already", "UTC", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/time_with_zone.rb#L126-L128
train
rails/rails
activesupport/lib/active_support/time_with_zone.rb
ActiveSupport.TimeWithZone.advance
def advance(options) # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, # otherwise advance from #utc, for accuracy when moving across DST boundaries if options.values_at(:years, :weeks, :months, :days).any? method_missing(:advance, options) else utc.advance(options).in_time_zone(time_zone) end end
ruby
def advance(options) # If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time, # otherwise advance from #utc, for accuracy when moving across DST boundaries if options.values_at(:years, :weeks, :months, :days).any? method_missing(:advance, options) else utc.advance(options).in_time_zone(time_zone) end end
[ "def", "advance", "(", "options", ")", "# If we're advancing a value of variable length (i.e., years, weeks, months, days), advance from #time,", "# otherwise advance from #utc, for accuracy when moving across DST boundaries", "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. The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>, <tt>:seconds</tt>. If advancing by a value of variable length (i.e., years, weeks, months, days), move forward from #time, otherwise move forward from #utc, for accuracy when moving across DST boundaries. Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' now = Time.zone.now # => Sun, 02 Nov 2014 01:26:28 EDT -04:00 now.advance(seconds: 1) # => Sun, 02 Nov 2014 01:26:29 EDT -04:00 now.advance(minutes: 1) # => Sun, 02 Nov 2014 01:27:28 EDT -04:00 now.advance(hours: 1) # => Sun, 02 Nov 2014 01:26:28 EST -05:00 now.advance(days: 1) # => Mon, 03 Nov 2014 01:26:28 EST -05:00 now.advance(weeks: 1) # => Sun, 09 Nov 2014 01:26:28 EST -05:00 now.advance(months: 1) # => Tue, 02 Dec 2014 01:26:28 EST -05:00 now.advance(years: 1) # => Mon, 02 Nov 2015 01:26:28 EST -05:00
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/time_with_zone.rb#L402-L410
train
rails/rails
actionpack/lib/abstract_controller/base.rb
AbstractController.Base.process
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
ruby
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
[ "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. The actual method that is called is determined by calling #method_for_action. If no method can handle the action, then an AbstractController::ActionNotFound error is raised. ==== Returns * <tt>self</tt>
[ "Calls", "the", "action", "going", "through", "the", "entire", "action", "dispatch", "stack", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/abstract_controller/base.rb#L127-L137
train
rails/rails
activesupport/lib/active_support/array_inquirer.rb
ActiveSupport.ArrayInquirer.any?
def any?(*candidates) if candidates.none? super else candidates.any? do |candidate| include?(candidate.to_sym) || include?(candidate.to_s) end end end
ruby
def any?(*candidates) if candidates.none? super else candidates.any? do |candidate| include?(candidate.to_sym) || include?(candidate.to_s) end end end
[ "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. If +candidates+ collection is not given, method returns true. variants = ActiveSupport::ArrayInquirer.new([:phone, :tablet]) variants.any? # => true variants.any?(:phone, :tablet) # => true variants.any?('phone', 'desktop') # => true variants.any?(:desktop, :watch) # => false
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/array_inquirer.rb#L25-L33
train
rails/rails
activerecord/lib/active_record/integration.rb
ActiveRecord.Integration.cache_key
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
ruby
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
[ "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. Product.new.cache_key # => "products/new" Product.find(5).cache_key # => "products/5" If ActiveRecord::Base.cache_versioning is turned off, as it was in Rails 5.1 and earlier, the cache key will also include a version. Product.cache_versioning = false Product.find(5).cache_key # => "products/5-20071224150000" (updated_at available)
[ "Returns", "a", "stable", "cache", "key", "that", "can", "be", "used", "to", "identify", "this", "record", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/integration.rb#L72-L89
train
rails/rails
actionmailer/lib/action_mailer/mail_helper.rb
ActionMailer.MailHelper.format_paragraph
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
ruby
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
[ "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. my_text = 'Here is a sample text with more than 40 characters' format_paragraph(my_text, 25, 4) # => " Here is a sample text with\n more than 40 characters"
[ "Returns", "+", "text", "+", "wrapped", "at", "+", "len", "+", "columns", "and", "indented", "+", "indent", "+", "spaces", ".", "By", "default", "column", "length", "+", "len", "+", "equals", "72", "characters", "and", "indent", "+", "indent", "+", "equal", "two", "spaces", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionmailer/lib/action_mailer/mail_helper.rb#L55-L70
train
rails/rails
activerecord/lib/active_record/relation/batches.rb
ActiveRecord.Batches.find_in_batches
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
ruby
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
[ "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. Person.where("age > 21").find_in_batches do |group| sleep(50) # Make sure it doesn't get too crowded in there! group.each { |person| person.party_all_night! } end If you do not provide a block to #find_in_batches, it will return an Enumerator for chaining with other methods: Person.find_in_batches.with_index do |group, batch| puts "Processing group ##{batch}" group.each(&:recover_from_last_night!) end To be yielded each record one by one, use #find_each instead. ==== Options * <tt>:batch_size</tt> - Specifies the size of the batch. Defaults to 1000. * <tt>:start</tt> - Specifies the primary key value to start from, inclusive of the value. * <tt>:finish</tt> - Specifies the primary key value to end at, inclusive of the value. * <tt>:error_on_ignore</tt> - Overrides the application config to specify if an error should be raised when an order is present in the relation. Limits are honored, and if present there is no requirement for the batch size: it can be less than, equal to, or greater than the limit. The options +start+ and +finish+ are especially useful if you want multiple workers dealing with the same processing queue. You can make worker 1 handle all the records between id 1 and 9999 and worker 2 handle from 10000 and beyond by setting the +:start+ and +:finish+ option on each worker. # Let's process from record 10_000 on. Person.find_in_batches(start: 10_000) do |group| group.each { |person| person.party_all_night! } end NOTE: It's not possible to set the order. That is automatically set to ascending on the primary key ("id ASC") to make the batch ordering work. This also means that this method only works when the primary key is orderable (e.g. an integer or string). NOTE: By its nature, batch processing is subject to race conditions if other processes are modifying the database.
[ "Yields", "each", "batch", "of", "records", "that", "was", "found", "by", "the", "find", "options", "as", "an", "array", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/relation/batches.rb#L126-L138
train
rails/rails
activemodel/lib/active_model/error.rb
ActiveModel.Error.match?
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
ruby
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
[ "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+.
[ "See", "if", "error", "matches", "provided", "+", "attribute", "+", "+", "type", "+", "and", "+", "options", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/error.rb#L46-L58
train
rails/rails
actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb
ActionView.CollectionCaching.fetch_or_cache_partial
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
ruby
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
[ "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. `cached_partials` is a hash. If the value exists it represents the rendered partial from the cache otherwise `Hash#fetch` will take the value of its block. This method expects a block that will return the rendered partial. An example is to render all results for each element that was not found in the cache and store it as an array. Order it so that the first empty cache element in `cached_partials` corresponds to the first element in `rendered_partials`. If the partial is not already cached it will also be written back to the underlying cache store.
[ "order_by", "is", "an", "enumerable", "object", "containing", "keys", "of", "the", "cache", "all", "keys", "are", "passed", "in", "whether", "found", "already", "or", "not", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/renderer/partial_renderer/collection_caching.rb#L90-L101
train
rails/rails
activesupport/lib/active_support/callbacks.rb
ActiveSupport.Callbacks.run_callbacks
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 # Common case: no 'around' callbacks defined 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
ruby
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 # Common case: no 'around' callbacks defined 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
[ "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", "# Common case: no 'around' callbacks defined", "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. Calls the before and around callbacks in the order they were set, yields the block (if given one), and then runs the after callbacks in reverse order. If the callback chain was halted, returns +false+. Otherwise returns the result of the block, +nil+ if no callbacks have been set, or +true+ if callbacks have been set but no block is given. run_callbacks :save do save end -- As this method is used in many places, and often wraps large portions of user code, it has an additional design goal of minimizing its impact on the visible call stack. An exception from inside a :before or :after callback can be as noisy as it likes -- but when control has passed smoothly through and into the supplied block, we want as little evidence as possible that we were here.
[ "Runs", "the", "callbacks", "for", "the", "given", "event", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/callbacks.rb#L97-L142
train
rails/rails
railties/lib/rails/source_annotation_extractor.rb
Rails.SourceAnnotationExtractor.extract_annotations_from
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/railties/lib/rails/source_annotation_extractor.rb#L139-L147
train
rails/rails
actionpack/lib/action_controller/metal/params_wrapper.rb
ActionController.ParamsWrapper._wrapper_enabled?
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
ruby
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
[ "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.
[ "Checks", "if", "we", "should", "perform", "parameters", "wrapping", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/params_wrapper.rb#L275-L280
train
rails/rails
railties/lib/rails/console/app.rb
Rails.ConsoleMethods.new_session
def new_session app = Rails.application session = ActionDispatch::Integration::Session.new(app) yield session if block_given? # This makes app.url_for and app.foo_path available in the console session.extend(app.routes.url_helpers) session.extend(app.routes.mounted_helpers) session end
ruby
def new_session app = Rails.application session = ActionDispatch::Integration::Session.new(app) yield session if block_given? # This makes app.url_for and app.foo_path available in the console session.extend(app.routes.url_helpers) session.extend(app.routes.mounted_helpers) session end
[ "def", "new_session", "app", "=", "Rails", ".", "application", "session", "=", "ActionDispatch", "::", "Integration", "::", "Session", ".", "new", "(", "app", ")", "yield", "session", "if", "block_given?", "# This makes app.url_for and app.foo_path available in the console", "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.
[ "create", "a", "new", "session", ".", "If", "a", "block", "is", "given", "the", "new", "session", "will", "be", "yielded", "to", "the", "block", "before", "being", "returned", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/railties/lib/rails/console/app.rb#L19-L29
train
rails/rails
railties/lib/rails/console/app.rb
Rails.ConsoleMethods.reload!
def reload!(print = true) puts "Reloading..." if print Rails.application.reloader.reload! true end
ruby
def reload!(print = true) puts "Reloading..." if print Rails.application.reloader.reload! true end
[ "def", "reload!", "(", "print", "=", "true", ")", "puts", "\"Reloading...\"", "if", "print", "Rails", ".", "application", ".", "reloader", ".", "reload!", "true", "end" ]
reloads the environment
[ "reloads", "the", "environment" ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/railties/lib/rails/console/app.rb#L32-L36
train
rails/rails
actionview/lib/action_view/record_identifier.rb
ActionView.RecordIdentifier.dom_id
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
ruby
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
[ "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. dom_id(Post.find(45)) # => "post_45" dom_id(Post.new) # => "new_post" If you need to address multiple instances of the same class in the same view, you can prefix the dom_id: dom_id(Post.find(45), :edit) # => "edit_post_45" dom_id(Post.new, :custom) # => "custom_post"
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/record_identifier.rb#L89-L95
train
rails/rails
activesupport/lib/active_support/concern.rb
ActiveSupport.Concern.included
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/concern.rb#L129-L141
train
rails/rails
activesupport/lib/active_support/concern.rb
ActiveSupport.Concern.class_methods
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
ruby
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
[ "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. module Example extend ActiveSupport::Concern class_methods do def foo; puts 'foo'; end private def bar; puts 'bar'; end end end class Buzz include Example end Buzz.foo # => "foo" Buzz.bar # => private method 'bar' called for Buzz:Class(NoMethodError)
[ "Define", "class", "methods", "from", "given", "block", ".", "You", "can", "define", "private", "class", "methods", "as", "well", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/concern.rb#L163-L169
train
rails/rails
actionpack/lib/abstract_controller/caching.rb
AbstractController.Caching.cache
def cache(key, options = {}, &block) # :doc: if cache_configured? cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) else yield end end
ruby
def cache(key, options = {}, &block) # :doc: if cache_configured? cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) else yield end end
[ "def", "cache", "(", "key", ",", "options", "=", "{", "}", ",", "&", "block", ")", "# :doc:", "if", "cache_configured?", "cache_store", ".", "fetch", "(", "ActiveSupport", "::", "Cache", ".", "expand_cache_key", "(", "key", ",", ":controller", ")", ",", "options", ",", "block", ")", "else", "yield", "end", "end" ]
Convenience accessor.
[ "Convenience", "accessor", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/abstract_controller/caching.rb#L58-L64
train
rails/rails
activesupport/lib/active_support/message_verifier.rb
ActiveSupport.MessageVerifier.valid_message?
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
ruby
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
[ "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. verifier = ActiveSupport::MessageVerifier.new 's3Krit' signed_message = verifier.generate 'a private message' verifier.valid_message?(signed_message) # => true tampered_message = signed_message.chop # editing the message invalidates the signature verifier.valid_message?(tampered_message) # => false
[ "Checks", "if", "a", "signed", "message", "could", "have", "been", "generated", "by", "signing", "an", "object", "with", "the", "+", "MessageVerifier", "+", "s", "secret", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/message_verifier.rb#L122-L127
train
rails/rails
activesupport/lib/active_support/message_verifier.rb
ActiveSupport.MessageVerifier.verified
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
ruby
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
[ "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. verifier = ActiveSupport::MessageVerifier.new 's3Krit' signed_message = verifier.generate 'a private message' verifier.verified(signed_message) # => 'a private message' Returns +nil+ if the message was not signed with the same secret. other_verifier = ActiveSupport::MessageVerifier.new 'd1ff3r3nt-s3Krit' other_verifier.verified(signed_message) # => nil Returns +nil+ if the message is not Base64-encoded. invalid_message = "f--46a0120593880c733a53b6dad75b42ddc1c8996d" verifier.verified(invalid_message) # => nil Raises any error raised while decoding the signed message. incompatible_message = "test--dad7b06c94abba8d46a15fafaef56c327665d5ff" verifier.verified(incompatible_message) # => TypeError: incompatible marshal file format
[ "Decodes", "the", "signed", "message", "using", "the", "+", "MessageVerifier", "+", "s", "secret", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/message_verifier.rb#L150-L161
train
rails/rails
activesupport/lib/active_support/message_verifier.rb
ActiveSupport.MessageVerifier.generate
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
ruby
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
[ "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. The message is signed with the +MessageVerifier+'s secret. Without knowing the secret, the original value cannot be extracted from the message. verifier = ActiveSupport::MessageVerifier.new 's3Krit' verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772"
[ "Generates", "a", "signed", "message", "for", "the", "provided", "value", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/message_verifier.rb#L186-L189
train
rails/rails
activejob/lib/active_job/core.rb
ActiveJob.Core.serialize
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activejob/lib/active_job/core.rb#L92-L106
train
rails/rails
activejob/lib/active_job/core.rb
ActiveJob.Core.deserialize
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
ruby
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
[ "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+ ==== Examples class DeliverWebhookJob < ActiveJob::Base attr_writer :attempt_number def attempt_number @attempt_number ||= 0 end def serialize super.merge('attempt_number' => attempt_number + 1) end def deserialize(job_data) super self.attempt_number = job_data['attempt_number'] end rescue_from(Timeout::Error) do |exception| raise exception if attempt_number > 5 retry_job(wait: 10) end end
[ "Attaches", "the", "stored", "job", "data", "to", "the", "current", "instance", ".", "Receives", "a", "hash", "returned", "from", "+", "serialize", "+" ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activejob/lib/active_job/core.rb#L134-L145
train
rails/rails
actionpack/lib/action_dispatch/middleware/static.rb
ActionDispatch.FileHandler.match?
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
ruby
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
[ "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. Used by the +Static+ class to check the existence of a valid file in the server's +public/+ directory (see Static#call).
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_dispatch/middleware/static.rb#L30-L47
train
rails/rails
activesupport/lib/active_support/duration.rb
ActiveSupport.Duration.+
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/duration.rb#L238-L249
train
rails/rails
activesupport/lib/active_support/duration.rb
ActiveSupport.Duration.*
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
ruby
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
[ "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.
[ "Multiplies", "this", "Duration", "by", "a", "Numeric", "and", "returns", "a", "new", "Duration", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/duration.rb#L258-L266
train
rails/rails
activesupport/lib/active_support/duration.rb
ActiveSupport.Duration.%
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
ruby
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
[ "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.
[ "Returns", "the", "modulo", "of", "this", "Duration", "by", "another", "Duration", "or", "Numeric", ".", "Numeric", "values", "are", "treated", "as", "seconds", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/duration.rb#L283-L291
train
rails/rails
actionview/lib/action_view/lookup_context.rb
ActionView.LookupContext.locale=
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/lookup_context.rb#L307-L314
train
rails/rails
actionview/lib/action_view/template/resolver.rb
ActionView.Resolver.find_all
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
ruby
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
[ "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.
[ "Normalizes", "the", "arguments", "and", "passes", "it", "on", "to", "find_templates", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/template/resolver.rb#L117-L123
train
rails/rails
actionview/lib/action_view/template/resolver.rb
ActionView.Resolver.cached
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/template/resolver.rb#L151-L161
train
rails/rails
actionview/lib/action_view/template/resolver.rb
ActionView.PathResolver.extract_handler_and_format_and_variant
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) # default_format can return nil handler.default_format else nil end end # Template::Types[format] and handler.default_format can return nil [handler, format, variant] end
ruby
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) # default_format can return nil handler.default_format else nil end end # Template::Types[format] and handler.default_format can return nil [handler, format, variant] end
[ "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", ")", "# default_format can return nil", "handler", ".", "default_format", "else", "nil", "end", "end", "# Template::Types[format] and handler.default_format can return nil", "[", "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/template/resolver.rb#L275-L295
train
rails/rails
actionview/lib/action_view/renderer/streaming_template_renderer.rb
ActionView.StreamingTemplateRenderer.render_template
def render_template(view, template, layout_name = nil, locals = {}) #:nodoc: 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
ruby
def render_template(view, template, layout_name = nil, locals = {}) #:nodoc: 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
[ "def", "render_template", "(", "view", ",", "template", ",", "layout_name", "=", "nil", ",", "locals", "=", "{", "}", ")", "#:nodoc:", "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/renderer/streaming_template_renderer.rb#L46-L55
train
rails/rails
activerecord/lib/active_record/autosave_association.rb
ActiveRecord.AutosaveAssociation.record_changed?
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
ruby
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
[ "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.
[ "If", "the", "record", "is", "new", "or", "it", "has", "changed", "returns", "true", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/autosave_association.rb#L457-L461
train
rails/rails
activesupport/lib/active_support/inflector/transliterate.rb
ActiveSupport.Inflector.transliterate
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
ruby
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
[ "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 "?". transliterate('Ærøskøbing') # => "AEroskobing" Default approximations are provided for Western/Latin characters, e.g, "ø", "ñ", "é", "ß", etc. This method is I18n aware, so you can set up custom approximations for a locale. This can be useful, for example, to transliterate German's "ü" and "ö" to "ue" and "oe", or to add support for transliterating Russian to ASCII. In order to make your custom transliterations available, you must set them as the <tt>i18n.transliterate.rule</tt> i18n key: # Store the transliterations in locales/de.yml i18n: transliterate: rule: ü: "ue" ö: "oe" # Or set them using Ruby I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { 'ü' => 'ue', 'ö' => 'oe' } } }) The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that maps characters to ASCII approximations as shown above, or, for more complex requirements, a Proc: I18n.backend.store_translations(:de, i18n: { transliterate: { rule: ->(string) { MyTransliterator.transliterate(string) } } }) Now you can have different transliterations for each locale: transliterate('Jürgen', locale: :en) # => "Jurgen" transliterate('Jürgen', locale: :de) # => "Juergen"
[ "Replaces", "non", "-", "ASCII", "characters", "with", "an", "ASCII", "approximation", "or", "if", "none", "exists", "a", "replacement", "character", "which", "defaults", "to", "?", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/inflector/transliterate.rb#L59-L67
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.import
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
ruby
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
[ "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`. override_options - Hash @option override_options [Symbol] :attribute Override the attribute the error belongs to @option override_options [Symbol] :type Override type of the error.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L121-L128
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.slice!
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
ruby
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
[ "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. person.errors.keys # => [:name, :age, :gender, :city] person.errors.slice!(:age, :gender) # => { :name=>["cannot be nil"], :city=>["cannot be nil"] } person.errors.keys # => [:age, :gender]
[ "Removes", "all", "errors", "except", "the", "given", "keys", ".", "Returns", "a", "hash", "containing", "the", "removed", "errors", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L149-L161
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.where
def where(attribute, type = nil, **options) attribute, type, options = normalize_arguments(attribute, type, options) @errors.select { |error| error.match?(attribute, type, options) } end
ruby
def where(attribute, type = nil, **options) attribute, type, options = normalize_arguments(attribute, type, options) @errors.select { |error| error.match?(attribute, type, options) } end
[ "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+. Only supplied params will be matched. person.errors.where(:name) # => all name errors. person.errors.where(:name, :too_short) # => all name errors being too short person.errors.where(:name, :too_short, minimum: 2) # => all name errors being too short and minimum is 2
[ "Search", "for", "errors", "matching", "+", "attribute", "+", "+", "type", "+", "or", "+", "options", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L170-L175
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.delete
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
ruby
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
[ "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. person.errors[:name] # => ["cannot be nil"] person.errors.delete(:name) # => ["cannot be nil"] person.errors[:name] # => []
[ "Delete", "messages", "for", "+", "key", "+", ".", "Returns", "the", "deleted", "messages", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L196-L203
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.each
def each(&block) if block.arity == 1 @errors.each(&block) else ActiveSupport::Deprecation.warn(<<~MSG) Enumerating ActiveModel::Errors as a hash has been deprecated. In Rails 6.1, `errors` is an array of Error objects, therefore it should be accessed by a block with a single block parameter like this: person.errors.each do |error| error.full_message end You are passing a block expecting two parameters, so the old hash behavior is simulated. As this is deprecated, this will result in an ArgumentError in Rails 6.2. MSG @errors. sort { |a, b| a.attribute <=> b.attribute }. each { |error| yield error.attribute, error.message } end end
ruby
def each(&block) if block.arity == 1 @errors.each(&block) else ActiveSupport::Deprecation.warn(<<~MSG) Enumerating ActiveModel::Errors as a hash has been deprecated. In Rails 6.1, `errors` is an array of Error objects, therefore it should be accessed by a block with a single block parameter like this: person.errors.each do |error| error.full_message end You are passing a block expecting two parameters, so the old hash behavior is simulated. As this is deprecated, this will result in an ArgumentError in Rails 6.2. MSG @errors. sort { |a, b| a.attribute <=> b.attribute }. each { |error| yield error.attribute, error.message } end end
[ "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. person.errors.add(:name, :blank, message: "can't be blank") person.errors.each do |attribute, error| # Will yield :name and "can't be blank" end person.errors.add(:name, :not_specified, message: "must be specified") person.errors.each do |attribute, error| # Will yield :name and "can't be blank" # then yield :name and "must be specified" 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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L228-L250
train
rails/rails
activemodel/lib/active_model/errors.rb
ActiveModel.Errors.to_xml
def to_xml(options = {}) deprecation_removal_warning(:to_xml) to_a.to_xml({ root: "errors", skip_types: true }.merge!(options)) end
ruby
def to_xml(options = {}) deprecation_removal_warning(:to_xml) to_a.to_xml({ root: "errors", skip_types: true }.merge!(options)) end
[ "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. person.errors.add(:name, :blank, message: "can't be blank") person.errors.add(:name, :not_specified, message: "must be specified") person.errors.to_xml # => # <?xml version=\"1.0\" encoding=\"UTF-8\"?> # <errors> # <error>name can't be blank</error> # <error>name must be specified</error> # </errors>
[ "Returns", "an", "xml", "formatted", "representation", "of", "the", "Errors", "hash", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/errors.rb#L283-L286
train
rails/rails
activerecord/lib/active_record/migration.rb
ActiveRecord.Migration.revert
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
ruby
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
[ "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. The following migration will remove the table 'horses' and create the table 'apples' on the way up, and the reverse on the way down. class FixTLMigration < ActiveRecord::Migration[5.0] def change revert do create_table(:horses) do |t| t.text :content t.datetime :remind_at end end create_table(:apples) do |t| t.string :variety end end end Or equivalently, if +TenderloveMigration+ is defined as in the documentation for Migration: require_relative '20121212123456_tenderlove_migration' class FixupTLMigration < ActiveRecord::Migration[5.0] def change revert TenderloveMigration create_table(:apples) do |t| t.string :variety end end end This command can be nested.
[ "Reverses", "the", "migration", "commands", "for", "the", "given", "block", "and", "the", "given", "migrations", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/migration.rb#L682-L697
train
rails/rails
activerecord/lib/active_record/migration.rb
ActiveRecord.Migration.say_with_time
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/migration.rb#L847-L854
train
rails/rails
activerecord/lib/active_record/migration.rb
ActiveRecord.Migration.next_migration_number
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
ruby
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
[ "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.
[ "Determines", "the", "version", "number", "of", "the", "next", "migration", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/migration.rb#L945-L951
train
rails/rails
activerecord/lib/active_record/migration.rb
ActiveRecord.Migrator.run_without_lock
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
ruby
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
[ "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.
[ "Used", "for", "running", "a", "specific", "migration", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/migration.rb#L1255-L1262
train
rails/rails
activerecord/lib/active_record/migration.rb
ActiveRecord.Migrator.migrate_without_lock
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
ruby
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
[ "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.
[ "Used", "for", "running", "multiple", "migrations", "up", "to", "or", "down", "to", "a", "certain", "value", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/migration.rb#L1265-L1276
train
rails/rails
actionpack/lib/action_controller/metal/strong_parameters.rb
ActionController.Parameters.permit!
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
ruby
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
[ "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+. class Person < ActiveRecord::Base end params = ActionController::Parameters.new(name: "Francesco") params.permitted? # => false Person.new(params) # => ActiveModel::ForbiddenAttributesError params.permit! params.permitted? # => true Person.new(params) # => #<Person id: nil, name: "Francesco">
[ "Sets", "the", "+", "permitted", "+", "attribute", "to", "+", "true", "+", ".", "This", "can", "be", "used", "to", "pass", "mass", "assignment", ".", "Returns", "+", "self", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/strong_parameters.rb#L391-L400
train
rails/rails
actionpack/lib/action_controller/metal/strong_parameters.rb
ActionController.Parameters.require
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
ruby
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
[ "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. When passed a single key, if it exists and its associated value is either present or the singleton +false+, returns said value: ActionController::Parameters.new(person: { name: "Francesco" }).require(:person) # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false> Otherwise raises <tt>ActionController::ParameterMissing</tt>: ActionController::Parameters.new.require(:person) # ActionController::ParameterMissing: param is missing or the value is empty: person ActionController::Parameters.new(person: nil).require(:person) # ActionController::ParameterMissing: param is missing or the value is empty: person ActionController::Parameters.new(person: "\t").require(:person) # ActionController::ParameterMissing: param is missing or the value is empty: person ActionController::Parameters.new(person: {}).require(:person) # ActionController::ParameterMissing: param is missing or the value is empty: person When given an array of keys, the method tries to require each one of them in order. If it succeeds, an array with the respective return values is returned: params = ActionController::Parameters.new(user: { ... }, profile: { ... }) user_params, profile_params = params.require([:user, :profile]) Otherwise, the method re-raises the first exception found: params = ActionController::Parameters.new(user: {}, profile: {}) user_params, profile_params = params.require([:user, :profile]) # ActionController::ParameterMissing: param is missing or the value is empty: user Technically this method can be used to fetch terminal values: # CAREFUL params = ActionController::Parameters.new(person: { name: "Finn" }) name = params.require(:person).require(:name) # CAREFUL but take into account that at some point those ones have to be permitted: def person_params params.require(:person).permit(:name).tap do |person_params| person_params.require(:name) # SAFER end end for example.
[ "This", "method", "accepts", "both", "a", "single", "key", "and", "an", "array", "of", "keys", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/strong_parameters.rb#L452-L460
train
rails/rails
actionpack/lib/action_controller/metal/strong_parameters.rb
ActionController.Parameters.permitted_scalar_filter
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+[if]?\)\z/ next unless $~.pre_match == permitted_key params[key] = self[key] if permitted_scalar?(self[key]) end end
ruby
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+[if]?\)\z/ next unless $~.pre_match == permitted_key params[key] = self[key] if permitted_scalar?(self[key]) end end
[ "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. For example: puts self.keys #=> ["zipcode(90210i)"] params = {} permitted_scalar_filter(params, "zipcode") puts params.keys # => ["zipcode"]
[ "Adds", "existing", "keys", "to", "the", "params", "if", "their", "values", "are", "scalar", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/strong_parameters.rb#L933-L946
train
rails/rails
actionview/lib/action_view/rendering.rb
ActionView.Rendering.process
def process(*) #:nodoc: old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) super ensure I18n.config = old_config end
ruby
def process(*) #:nodoc: old_config, I18n.config = I18n.config, I18nProxy.new(I18n.config, lookup_context) super ensure I18n.config = old_config end
[ "def", "process", "(", "*", ")", "#:nodoc:", "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.
[ "Overwrite", "process", "to", "setup", "I18n", "proxy", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/rendering.rb#L37-L42
train
rails/rails
actionview/lib/action_view/rendering.rb
ActionView.Rendering._render_template
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
ruby
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
[ "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.
[ "Find", "and", "render", "a", "template", "based", "on", "the", "options", "given", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/rendering.rb#L109-L125
train
rails/rails
actionview/lib/action_view/rendering.rb
ActionView.Rendering._normalize_options
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
ruby
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
[ "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.
[ "Normalize", "options", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/rendering.rb#L157-L169
train
rails/rails
activejob/lib/active_job/enqueuing.rb
ActiveJob.Enqueuing.enqueue
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
ruby
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
[ "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. ==== Options * <tt>:wait</tt> - Enqueues the job with the specified delay * <tt>:wait_until</tt> - Enqueues the job at the time specified * <tt>:queue</tt> - Enqueues the job on the specified queue * <tt>:priority</tt> - Enqueues the job with the specified priority ==== Examples my_job_instance.enqueue my_job_instance.enqueue wait: 5.minutes my_job_instance.enqueue queue: :important my_job_instance.enqueue wait_until: Date.tomorrow.midnight my_job_instance.enqueue priority: 10
[ "Enqueues", "the", "job", "to", "be", "performed", "by", "the", "queue", "adapter", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activejob/lib/active_job/enqueuing.rb#L46-L78
train
rails/rails
activerecord/lib/active_record/fixtures.rb
ActiveRecord.FixtureSet.table_rows
def table_rows # allow a standard key to be used for doing defaults in YAML fixtures.delete("DEFAULTS") TableRows.new( table_name, model_class: model_class, fixtures: fixtures, config: config, ).to_hash end
ruby
def table_rows # allow a standard key to be used for doing defaults in YAML fixtures.delete("DEFAULTS") TableRows.new( table_name, model_class: model_class, fixtures: fixtures, config: config, ).to_hash end
[ "def", "table_rows", "# allow a standard key to be used for doing defaults in YAML", "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/fixtures.rb#L651-L661
train
rails/rails
activerecord/lib/active_record/fixtures.rb
ActiveRecord.FixtureSet.read_fixture_files
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
ruby
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
[ "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.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/fixtures.rb#L676-L689
train
rails/rails
activestorage/lib/active_storage/downloading.rb
ActiveStorage.Downloading.download_blob_to
def download_blob_to(file) #:doc: file.binmode blob.download { |chunk| file.write(chunk) } file.flush file.rewind end
ruby
def download_blob_to(file) #:doc: file.binmode blob.download { |chunk| file.write(chunk) } file.flush file.rewind end
[ "def", "download_blob_to", "(", "file", ")", "#:doc:", "file", ".", "binmode", "blob", ".", "download", "{", "|", "chunk", "|", "file", ".", "write", "(", "chunk", ")", "}", "file", ".", "flush", "file", ".", "rewind", "end" ]
Efficiently downloads blob data into the given file.
[ "Efficiently", "downloads", "blob", "data", "into", "the", "given", "file", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activestorage/lib/active_storage/downloading.rb#L35-L40
train
rails/rails
actionpack/lib/action_controller/metal/conditional_get.rb
ActionController.ConditionalGet.expires_in
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
ruby
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
[ "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. expires_in 20.minutes expires_in 3.hours, public: true expires_in 3.hours, public: true, must_revalidate: true This method will overwrite an existing Cache-Control header. See https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html for more possibilities. HTTP Cache-Control Extensions for Stale Content. See https://tools.ietf.org/html/rfc5861 It helps to cache an asset and serve it while is being revalidated and/or returning with an error. expires_in 3.hours, public: true, stale_while_revalidate: 60.seconds expires_in 3.hours, public: true, stale_while_revalidate: 60.seconds, stale_if_error: 5.minutes The method will also ensure an HTTP Date header for client compatibility.
[ "Sets", "an", "HTTP", "1", ".", "1", "Cache", "-", "Control", "header", ".", "Defaults", "to", "issuing", "a", "+", "private", "+", "instruction", "so", "that", "intermediate", "caches", "must", "not", "cache", "the", "response", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/conditional_get.rb#L238-L250
train
rails/rails
actionpack/lib/action_controller/metal/conditional_get.rb
ActionController.ConditionalGet.http_cache_forever
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
ruby
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
[ "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. You can use this method when you have an HTTP response that never changes, and the browser and proxies should cache it indefinitely. * +public+: By default, HTTP responses are private, cached only on the user's web browser. To allow proxies to cache the response, set +true+ to indicate that they can serve the cached response to all users.
[ "Cache", "or", "yield", "the", "block", ".", "The", "cache", "is", "supposed", "to", "never", "expire", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/conditional_get.rb#L267-L273
train
rails/rails
activestorage/lib/active_storage/previewer.rb
ActiveStorage.Previewer.draw
def draw(*argv) #:doc: open_tempfile do |file| instrument :preview, key: blob.key do capture(*argv, to: file) end yield file end end
ruby
def draw(*argv) #:doc: open_tempfile do |file| instrument :preview, key: blob.key do capture(*argv, to: file) end yield file end end
[ "def", "draw", "(", "*", "argv", ")", "#:doc:", "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. Use this method to shell out to a system library (e.g. muPDF or FFmpeg) for preview image generation. The resulting tempfile can be used as the +:io+ value in an attachable Hash: def preview download_blob_to_tempfile do |input| draw "my-drawing-command", input.path, "--format", "png", "-" do |output| yield io: output, filename: "#{blob.filename.base}.png", content_type: "image/png" end end end The output tempfile is opened in the directory returned by #tmpdir.
[ "Executes", "a", "system", "command", "capturing", "its", "binary", "output", "in", "a", "tempfile", ".", "Yields", "the", "tempfile", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activestorage/lib/active_storage/previewer.rb#L46-L54
train
rails/rails
actionpack/lib/action_controller/metal/rendering.rb
ActionController.Rendering.render_to_string
def render_to_string(*) result = super if result.respond_to?(:each) string = +"" result.each { |r| string << r } string else result end end
ruby
def render_to_string(*) result = super if result.respond_to?(:each) string = +"" result.each { |r| string << r } string else result end end
[ "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.
[ "Overwrite", "render_to_string", "because", "body", "can", "now", "be", "set", "to", "a", "Rack", "body", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/rendering.rb#L40-L49
train
rails/rails
actionpack/lib/action_controller/metal/rendering.rb
ActionController.Rendering._normalize_options
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
ruby
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
[ "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.
[ "Normalize", "both", "text", "and", "status", "options", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/rendering.rb#L89-L101
train
rails/rails
actionpack/lib/action_controller/metal/rendering.rb
ActionController.Rendering._process_options
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
ruby
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
[ "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.
[ "Process", "controller", "specific", "options", "as", "status", "content", "-", "type", "and", "location", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/rendering.rb#L112-L120
train
rails/rails
actionpack/lib/action_dispatch/middleware/remote_ip.rb
ActionDispatch.RemoteIp.call
def call(env) req = ActionDispatch::Request.new env req.remote_ip = GetIp.new(req, check_ip, proxies) @app.call(req.env) end
ruby
def call(env) req = ActionDispatch::Request.new env req.remote_ip = GetIp.new(req, check_ip, proxies) @app.call(req.env) end
[ "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. The +ip_spoofing_check+ option is on by default. When on, an exception is raised if it looks like the client is trying to lie about its own IP address. It makes sense to turn off this check on sites aimed at non-IP clients (like WAP devices), or behind proxies that set headers in an incorrect or confusing way (like AWS ELB). The +custom_proxies+ argument can take an Array of string, IPAddr, or Regexp objects which will be used instead of +TRUSTED_PROXIES+. If a single string, IPAddr, or Regexp object is provided, it will be used in addition to +TRUSTED_PROXIES+. Any proxy setup will put the value you want in the middle (or at the beginning) of the X-Forwarded-For list, with your proxy servers after it. If your proxies aren't removed, pass them in via the +custom_proxies+ parameter. That way, the middleware will ignore those IP addresses, and return the one that you want. Since the IP address may not be needed, we store the object here without calculating the IP to keep from slowing down the majority of requests. For those requests that do need to know the IP, the GetIp#calculate_ip method will calculate the memoized client IP address.
[ "Create", "a", "new", "+", "RemoteIp", "+", "middleware", "instance", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_dispatch/middleware/remote_ip.rb#L78-L82
train
rails/rails
activemodel/lib/active_model/validations/with.rb
ActiveModel.Validations.validates_with
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
ruby
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
[ "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. class Person include ActiveModel::Validations validate :instance_validations def instance_validations validates_with MyValidator end end Please consult the class method documentation for more information on creating your own validator. You may also pass it multiple classes, like so: class Person include ActiveModel::Validations validate :instance_validations, on: :create def instance_validations validates_with MyValidator, MyOtherValidator end end Standard configuration options (<tt>:on</tt>, <tt>:if</tt> and <tt>:unless</tt>), which are available on the class version of +validates_with+, should instead be placed on the +validates+ method as these are applied and tested in the callback. If you pass any additional configuration options, they will be passed to the class and available as +options+, please refer to the class version of this method for more information.
[ "Passes", "the", "record", "off", "to", "the", "class", "or", "classes", "specified", "and", "allows", "them", "to", "add", "errors", "based", "on", "more", "complex", "conditions", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activemodel/lib/active_model/validations/with.rb#L137-L145
train
rails/rails
actionview/lib/action_view/template.rb
ActionView.Template.render
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
ruby
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
[ "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. This method is instrumented as "!render_template.action_view". Notice that we use a bang in this instrumentation because you don't want to consume this in production. This is only slow if it's being listened to.
[ "Render", "a", "template", ".", "If", "the", "template", "was", "not", "compiled", "yet", "it", "is", "done", "exactly", "before", "rendering", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/template.rb#L182-L189
train
rails/rails
actionview/lib/action_view/template.rb
ActionView.Template.compile!
def compile!(view) return if @compiled # Templates can be used concurrently in threaded environments # so compilation and any instance variable modification must # be synchronized @compile_mutex.synchronize do # Any thread holding this lock will be compiling the template needed # by the threads waiting. So re-check the @compiled flag to avoid # re-compilation return if @compiled mod = view.compiled_method_container instrument("!compile_template") do compile(mod) end @compiled = true end end
ruby
def compile!(view) return if @compiled # Templates can be used concurrently in threaded environments # so compilation and any instance variable modification must # be synchronized @compile_mutex.synchronize do # Any thread holding this lock will be compiling the template needed # by the threads waiting. So re-check the @compiled flag to avoid # re-compilation return if @compiled mod = view.compiled_method_container instrument("!compile_template") do compile(mod) end @compiled = true end end
[ "def", "compile!", "(", "view", ")", "return", "if", "@compiled", "# Templates can be used concurrently in threaded environments", "# so compilation and any instance variable modification must", "# be synchronized", "@compile_mutex", ".", "synchronize", "do", "# Any thread holding this lock will be compiling the template needed", "# by the threads waiting. So re-check the @compiled flag to avoid", "# re-compilation", "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.
[ "Compile", "a", "template", ".", "This", "method", "ensures", "a", "template", "is", "compiled", "just", "once", "and", "removes", "the", "source", "after", "it", "is", "compiled", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionview/lib/action_view/template.rb#L270-L290
train
rails/rails
activerecord/lib/active_record/persistence.rb
ActiveRecord.Persistence.reload
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
ruby
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
[ "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. This method finds the record by its primary key (which could be assigned manually) and modifies the receiver in-place: account = Account.new # => #<Account id: nil, email: nil> account.id = 1 account.reload # Account Load (1.2ms) SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1 [["id", 1]] # => #<Account id: 1, email: 'account@example.com'> Attributes are reloaded from the database, and caches busted, in particular the associations cache and the QueryCache. If the record no longer exists in the database ActiveRecord::RecordNotFound is raised. Otherwise, in addition to the in-place modification the method returns +self+ for convenience. The optional <tt>:lock</tt> flag option allows you to lock the reloaded record: reload(lock: true) # reload with pessimistic locking Reloading is commonly used in test suites to test something is actually written to the database, or when some action modifies the corresponding row in the database but not the object in memory: assert account.deposit!(25) assert_equal 25, account.credit # check it is updated in memory assert_equal 25, account.reload.credit # check it is also persisted Another common use case is optimistic locking handling: def with_optimistic_retry begin yield rescue ActiveRecord::StaleObjectError begin # Reload lock_version in particular. reload rescue ActiveRecord::RecordNotFound # If the record is gone there is nothing to do. else retry end end end
[ "Reloads", "the", "record", "from", "the", "database", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/persistence.rb#L802-L815
train
rails/rails
actionpack/lib/action_controller/metal/request_forgery_protection.rb
ActionController.RequestForgeryProtection.masked_authenticity_token
def masked_authenticity_token(session, form_options: {}) # :doc: 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
ruby
def masked_authenticity_token(session, form_options: {}) # :doc: 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
[ "def", "masked_authenticity_token", "(", "session", ",", "form_options", ":", "{", "}", ")", "# :doc:", "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.
[ "Creates", "a", "masked", "version", "of", "the", "authenticity", "token", "that", "varies", "on", "each", "request", ".", "The", "masking", "is", "used", "to", "mitigate", "SSL", "attacks", "like", "BREACH", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L320-L334
train
rails/rails
actionpack/lib/action_controller/metal/request_forgery_protection.rb
ActionController.RequestForgeryProtection.valid_authenticity_token?
def valid_authenticity_token?(session, encoded_masked_token) # :doc: 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 # encoded_masked_token is invalid Base64 return false end # See if it's actually a masked token or not. In order to # deploy this code, we should be able to handle any unmasked # tokens that we've issued without error. if masked_token.length == AUTHENTICITY_TOKEN_LENGTH # This is actually an unmasked token. This is expected if # you have just upgraded to masked tokens, but should stop # happening shortly after installing this gem. 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 # Token is malformed. end end
ruby
def valid_authenticity_token?(session, encoded_masked_token) # :doc: 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 # encoded_masked_token is invalid Base64 return false end # See if it's actually a masked token or not. In order to # deploy this code, we should be able to handle any unmasked # tokens that we've issued without error. if masked_token.length == AUTHENTICITY_TOKEN_LENGTH # This is actually an unmasked token. This is expected if # you have just upgraded to masked tokens, but should stop # happening shortly after installing this gem. 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 # Token is malformed. end end
[ "def", "valid_authenticity_token?", "(", "session", ",", "encoded_masked_token", ")", "# :doc:", "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", "# encoded_masked_token is invalid Base64", "return", "false", "end", "# See if it's actually a masked token or not. In order to", "# deploy this code, we should be able to handle any unmasked", "# tokens that we've issued without error.", "if", "masked_token", ".", "length", "==", "AUTHENTICITY_TOKEN_LENGTH", "# This is actually an unmasked token. This is expected if", "# you have just upgraded to masked tokens, but should stop", "# happening shortly after installing this gem.", "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", "# Token is malformed.", "end", "end" ]
Checks the client's masked token to see if it matches the session token. Essentially the inverse of +masked_authenticity_token+.
[ "Checks", "the", "client", "s", "masked", "token", "to", "see", "if", "it", "matches", "the", "session", "token", ".", "Essentially", "the", "inverse", "of", "+", "masked_authenticity_token", "+", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L339-L368
train
rails/rails
actionpack/lib/action_controller/metal/request_forgery_protection.rb
ActionController.RequestForgeryProtection.valid_request_origin?
def valid_request_origin? # :doc: if forgery_protection_origin_check # We accept blank origin headers because some user agents don't send it. raise InvalidAuthenticityToken, NULL_ORIGIN_MESSAGE if request.origin == "null" request.origin.nil? || request.origin == request.base_url else true end end
ruby
def valid_request_origin? # :doc: if forgery_protection_origin_check # We accept blank origin headers because some user agents don't send it. raise InvalidAuthenticityToken, NULL_ORIGIN_MESSAGE if request.origin == "null" request.origin.nil? || request.origin == request.base_url else true end end
[ "def", "valid_request_origin?", "# :doc:", "if", "forgery_protection_origin_check", "# We accept blank origin headers because some user agents don't send it.", "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.
[ "Checks", "if", "the", "request", "originated", "from", "the", "same", "origin", "by", "looking", "at", "the", "Origin", "header", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/action_controller/metal/request_forgery_protection.rb#L441-L449
train
rails/rails
activerecord/lib/active_record/transactions.rb
ActiveRecord.Transactions.remember_transaction_record_state
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
ruby
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
[ "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.
[ "Save", "the", "new", "record", "state", "and", "id", "of", "a", "record", "so", "it", "can", "be", "restored", "later", "if", "a", "transaction", "fails", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/transactions.rb#L385-L396
train
rails/rails
activerecord/lib/active_record/transactions.rb
ActiveRecord.Transactions.sync_with_transaction_state
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
ruby
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
[ "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. The <tt>@transaction_state</tt> variable stores the states of the associated transaction. This relies on the fact that a transaction can only be in one rollback or commit (otherwise a list of states would be required). Each Active Record object inside of a transaction carries that transaction's TransactionState. This method checks to see if the ActiveRecord object's state reflects the TransactionState, and rolls back or commits the Active Record object as appropriate.
[ "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", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activerecord/lib/active_record/transactions.rb#L481-L493
train
rails/rails
activesupport/lib/active_support/security_utils.rb
ActiveSupport.SecurityUtils.fixed_length_secure_compare
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
ruby
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
[ "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. The values compared should be of fixed length, such as strings that have already been processed by HMAC. Raises in case of length mismatch.
[ "Constant", "time", "string", "comparison", "for", "fixed", "length", "strings", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/security_utils.rb#L11-L19
train
rails/rails
activesupport/lib/active_support/security_utils.rb
ActiveSupport.SecurityUtils.secure_compare
def secure_compare(a, b) fixed_length_secure_compare(::Digest::SHA256.digest(a), ::Digest::SHA256.digest(b)) && a == b end
ruby
def secure_compare(a, b) fixed_length_secure_compare(::Digest::SHA256.digest(a), ::Digest::SHA256.digest(b)) && a == b end
[ "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. The values are first processed by SHA256, so that we don't leak length info via timing attacks.
[ "Constant", "time", "string", "comparison", "for", "variable", "length", "strings", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/security_utils.rb#L26-L28
train
rails/rails
activesupport/lib/active_support/lazy_load_hooks.rb
ActiveSupport.LazyLoadHooks.on_load
def on_load(name, options = {}, &block) @loaded[name].each do |base| execute_hook(name, base, options, block) end @load_hooks[name] << [block, options] end
ruby
def on_load(name, options = {}, &block) @loaded[name].each do |base| execute_hook(name, base, options, block) end @load_hooks[name] << [block, options] end
[ "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. Options: * <tt>:yield</tt> - Yields the object that run_load_hooks to +block+. * <tt>:run_once</tt> - Given +block+ will run only once.
[ "Declares", "a", "block", "that", "will", "be", "executed", "when", "a", "Rails", "component", "is", "fully", "loaded", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/activesupport/lib/active_support/lazy_load_hooks.rb#L41-L47
train
rails/rails
actionpack/lib/abstract_controller/rendering.rb
AbstractController.Rendering.view_assigns
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
ruby
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
[ "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.
[ "This", "method", "should", "return", "a", "hash", "with", "assigns", ".", "You", "can", "overwrite", "this", "configuration", "per", "controller", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/abstract_controller/rendering.rb#L64-L72
train
rails/rails
actionpack/lib/abstract_controller/rendering.rb
AbstractController.Rendering._normalize_render
def _normalize_render(*args, &block) # :nodoc: options = _normalize_args(*args, &block) _process_variant(options) _normalize_options(options) options end
ruby
def _normalize_render(*args, &block) # :nodoc: options = _normalize_args(*args, &block) _process_variant(options) _normalize_options(options) options end
[ "def", "_normalize_render", "(", "*", "args", ",", "&", "block", ")", "# :nodoc:", "options", "=", "_normalize_args", "(", "args", ",", "block", ")", "_process_variant", "(", "options", ")", "_normalize_options", "(", "options", ")", "options", "end" ]
Normalize args and options.
[ "Normalize", "args", "and", "options", "." ]
85a8bc644be69908f05740a5886ec19cd3679df5
https://github.com/rails/rails/blob/85a8bc644be69908f05740a5886ec19cd3679df5/actionpack/lib/abstract_controller/rendering.rb#L116-L121
train

Dataset is imported from CodeXGLUE and pre-processed using their script.

Where to find in Semeru:

The dataset can be found at /nfs/semeru/semeru_datasets/code_xglue/code-to-text/ruby in Semeru

CodeXGLUE -- Code-To-Text

Task Definition

The task is to generate natural language comments for a code, and evaluted by smoothed bleu-4 score.

Dataset

The dataset we use comes from CodeSearchNet and we filter the dataset as the following:

  • Remove examples that codes cannot be parsed into an abstract syntax tree.
  • Remove examples that #tokens of documents is < 3 or >256
  • Remove examples that documents contain special tokens (e.g. <img ...> or https:...)
  • Remove examples that documents are not English.

Data Format

After preprocessing dataset, you can obtain three .jsonl files, i.e. train.jsonl, valid.jsonl, test.jsonl

For each file, each line in the uncompressed file represents one function. One row is illustrated below.

  • repo: the owner/repo

  • path: the full path to the original file

  • func_name: the function or method name

  • original_string: the raw string before tokenization or parsing

  • language: the programming language

  • code/function: the part of the original_string that is code

  • code_tokens/function_tokens: tokenized version of code

  • docstring: the top-level comment or docstring, if it exists in the original string

  • docstring_tokens: tokenized version of docstring

Data Statistic

Programming Language Training Dev Test
Ruby 24,927 1,400 1,261

Reference

@article{husain2019codesearchnet,
  title={Codesearchnet challenge: Evaluating the state of semantic code search},
  author={Husain, Hamel and Wu, Ho-Hsiang and Gazit, Tiferet and Allamanis, Miltiadis and Brockschmidt, Marc},
  journal={arXiv preprint arXiv:1909.09436},
  year={2019}
}
Downloads last month
1
Edit dataset card