code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def rescue_from(*klasses, with: nil, &block) unless with if block_given? with = block else raise ArgumentError, "Need a handler. Pass the with: keyword argument or provide a block." end end klasses.each do |klass| key = if klass.is_a?(Module) && klass.respond_to?(:===) klass.name elsif klass.is_a?(String) klass else raise ArgumentError, "#{klass.inspect} must be an Exception class or a String referencing an Exception class" end # Put the new handler at the end because the list is read in reverse. self.rescue_handlers += [[key, with]] end end
Registers exception classes with a handler to be called by <tt>rescue_with_handler</tt>. <tt>rescue_from</tt> receives a series of exception classes or class names, and an exception handler specified by a trailing <tt>:with</tt> option containing the name of a method or a Proc object. Alternatively, a block can be given as the handler. Handlers that take one argument will be called with the exception, so that the exception can be inspected when dealing with it. Handlers are inherited. They are searched from right to left, from bottom to top, and up the hierarchy. The handler of the first class for which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if any. class ApplicationController < ActionController::Base rescue_from User::NotAuthorized, with: :deny_access # self defined exception rescue_from ActiveRecord::RecordInvalid, with: :show_errors rescue_from 'MyAppError::Base' do |exception| render xml: exception, status: 500 end private def deny_access ... end def show_errors(exception) exception.record.new_record? ? ... end end Exceptions raised inside exception handlers are not propagated up.
rescue_from
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/rescuable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/rescuable.rb
Apache-2.0
def secure_compare(a, b) a.bytesize == b.bytesize && fixed_length_secure_compare(a, b) end
Secure string comparison for strings of variable length. While a timing attack would not be able to discern the content of a secret compared via secure_compare, it is possible to determine the secret length. This should be considered when using secure_compare to compare weak, short secrets to user input.
secure_compare
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/security_utils.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/security_utils.rb
Apache-2.0
def method_added(event) # Only public methods are added as subscribers, and only if a notifier # has been set up. This means that subscribers will only be set up for # classes that call #attach_to. if public_method_defined?(event) && notifier add_event_subscriber(event) end end
Adds event subscribers for all new methods added to the class.
method_added
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/subscriber.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/subscriber.rb
Apache-2.0
def call(severity, timestamp, progname, msg) super(severity, timestamp, progname, "#{tags_text}#{msg}") end
This method is invoked when a log event occurs.
call
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/tagged_logging.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/tagged_logging.rb
Apache-2.0
def test_order ActiveSupport.test_order ||= :random end
Returns the order in which test cases are run. ActiveSupport::TestCase.test_order # => :random Possible values are +:random+, +:parallel+, +:alpha+, +:sorted+. Defaults to +:random+.
test_order
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
Apache-2.0
def parallelize(workers: :number_of_processors, with: :processes) workers = Concurrent.physical_processor_count if workers == :number_of_processors workers = ENV["PARALLEL_WORKERS"].to_i if ENV["PARALLEL_WORKERS"] return if workers <= 1 executor = case with when :processes Testing::Parallelization.new(workers) when :threads Minitest::Parallel::Executor.new(workers) else raise ArgumentError, "#{with} is not a supported parallelization executor." end self.lock_threads = false if defined?(self.lock_threads) && with == :threads Minitest.parallel_executor = executor parallelize_me! end
Parallelizes the test suite. Takes a +workers+ argument that controls how many times the process is forked. For each process a new database will be created suffixed with the worker number. test-database-0 test-database-1 If <tt>ENV["PARALLEL_WORKERS"]</tt> is set the workers argument will be ignored and the environment variable will be used instead. This is useful for CI environments, or other environments where you may need more workers than you do for local testing. If the number of workers is set to +1+ or fewer, the tests will not be parallelized. If +workers+ is set to +:number_of_processors+, the number of workers will be set to the actual core count on the machine you are on. The default parallelization method is to fork processes. If you'd like to use threads instead you can pass <tt>with: :threads</tt> to the +parallelize+ method. Note the threaded parallelization does not create multiple database and will not work with system tests at this time. parallelize(workers: :number_of_processors, with: :threads) The threaded parallelization uses minitest's parallel executor directly. The processes parallelization uses a Ruby DRb server.
parallelize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
Apache-2.0
def parallelize_setup(&block) ActiveSupport::Testing::Parallelization.after_fork_hook do |worker| yield worker end end
Set up hook for parallel testing. This can be used if you have multiple databases or any behavior that needs to be run after the process is forked but before the tests run. Note: this feature is not available with the threaded parallelization. In your +test_helper.rb+ add the following: class ActiveSupport::TestCase parallelize_setup do # create databases end end
parallelize_setup
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
Apache-2.0
def parallelize_teardown(&block) ActiveSupport::Testing::Parallelization.run_cleanup_hook do |worker| yield worker end end
Clean up hook for parallel testing. This can be used to drop databases if your app uses multiple write/read databases or other clean up before the tests finish. This runs before the forked process is closed. Note: this feature is not available with the threaded parallelization. In your +test_helper.rb+ add the following: class ActiveSupport::TestCase parallelize_teardown do # drop databases end end
parallelize_teardown
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/test_case.rb
Apache-2.0
def time @time ||= incorporate_utc_offset(@utc, utc_offset) end
Returns a <tt>Time</tt> instance that represents the time in +time_zone+.
time
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def utc @utc ||= incorporate_utc_offset(@time, -utc_offset) end
Returns a <tt>Time</tt> instance of the simultaneous time in the UTC timezone.
utc
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def in_time_zone(new_zone = ::Time.zone) return self if time_zone == new_zone utc.in_time_zone(new_zone) end
Returns the simultaneous time in <tt>Time.zone</tt>, or the specified zone.
in_time_zone
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def utc? zone == "UTC" || zone == "UCT" end
Returns true if the current time zone is set to UTC. Time.zone = 'UTC' # => 'UTC' Time.zone.now.utc? # => true Time.zone = 'Eastern Time (US & Canada)' # => 'Eastern Time (US & Canada)' Time.zone.now.utc? # => false
utc?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
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"
formatted_offset
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def inspect "#{time.strftime('%a, %d %b %Y %H:%M:%S.%9N')} #{zone} #{formatted_offset}" end
Returns a string of the object's date, time, zone, and offset from UTC. Time.zone.now.inspect # => "Thu, 04 Dec 2014 11:00:25.624541392 EST -05:00"
inspect
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def xmlschema(fraction_digits = 0) "#{time.strftime(PRECISIONS[fraction_digits.to_i])}#{formatted_offset(true, 'Z')}" end
Returns a string of the object's date and time in the ISO 8601 standard format. Time.zone.now.xmlschema # => "2014-12-04T11:02:37-05:00"
xmlschema
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def as_json(options = nil) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema(ActiveSupport::JSON::Encoding.time_precision) else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end
Coerces time to a string for JSON encoding. The default format is ISO 8601. You can get %Y/%m/%d %H:%M:%S +offset style by setting <tt>ActiveSupport::JSON::Encoding.use_standard_json_time_format</tt> to +false+. # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = true Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # => "2005-02-01T05:15:10.000-10:00" # With ActiveSupport::JSON::Encoding.use_standard_json_time_format = false Time.utc(2005,2,1,15,15,10).in_time_zone("Hawaii").to_json # => "2005/02/01 05:15:10 -1000"
as_json
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def to_s(format = :default) if format == :db utc.to_s(format) elsif formatter = ::Time::DATE_FORMATS[format] formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter) else "#{time.strftime("%Y-%m-%d %H:%M:%S")} #{formatted_offset(false, 'UTC')}" # mimicking Ruby Time#to_s format end end
Returns a string of the object's date and time. Accepts an optional <tt>format</tt>: * <tt>:default</tt> - default value, mimics Ruby Time#to_s format. * <tt>:db</tt> - format outputs time in UTC :db time. See Time#to_formatted_s(:db). * Any key in <tt>Time::DATE_FORMATS</tt> can be used. See active_support/core_ext/time/conversions.rb.
to_s
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def strftime(format) format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") getlocal(utc_offset).strftime(format) end
Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime, so that zone information is correct.
strftime
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def between?(min, max) utc.between?(min, max) end
Returns true if the current object's time is within the specified +min+ and +max+ time.
between?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def change(options) if options[:zone] && options[:offset] raise ArgumentError, "Can't change both :offset and :zone at the same time: #{options.inspect}" end new_time = time.change(options) if options[:zone] new_zone = ::Time.find_zone(options[:zone]) elsif options[:offset] new_zone = ::Time.find_zone(new_time.utc_offset) end new_zone ||= time_zone periods = new_zone.periods_for_local(new_time) self.class.new(nil, new_zone, new_time, periods.include?(period) ? period : nil) end
Returns a new +ActiveSupport::TimeWithZone+ where one or more of the elements have been changed according to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>) reset cascadingly, so if only the hour is passed, then minute, sec, usec and nsec is set to 0. If the hour and minute is passed, then sec, usec and nsec is set to 0. The +options+ parameter takes a hash with any of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:usec</tt>, <tt>:nsec</tt>, <tt>:offset</tt>, <tt>:zone</tt>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both. Similarly, pass either <tt>:zone</tt> or <tt>:offset</tt>, not both. t = Time.zone.now # => Fri, 14 Apr 2017 11:45:15.116992711 EST -05:00 t.change(year: 2020) # => Tue, 14 Apr 2020 11:45:15.116992711 EST -05:00 t.change(hour: 12) # => Fri, 14 Apr 2017 12:00:00.116992711 EST -05:00 t.change(min: 30) # => Fri, 14 Apr 2017 11:30:00.116992711 EST -05:00 t.change(offset: "-10:00") # => Fri, 14 Apr 2017 11:45:15.116992711 HST -10:00 t.change(zone: "Hawaii") # => Fri, 14 Apr 2017 11:45:15.116992711 HST -10:00
change
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
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.558049687 EDT -04:00 now.advance(seconds: 1) # => Sun, 02 Nov 2014 01:26:29.558049687 EDT -04:00 now.advance(minutes: 1) # => Sun, 02 Nov 2014 01:27:28.558049687 EDT -04:00 now.advance(hours: 1) # => Sun, 02 Nov 2014 01:26:28.558049687 EST -05:00 now.advance(days: 1) # => Mon, 03 Nov 2014 01:26:28.558049687 EST -05:00 now.advance(weeks: 1) # => Sun, 09 Nov 2014 01:26:28.558049687 EST -05:00 now.advance(months: 1) # => Tue, 02 Dec 2014 01:26:28.558049687 EST -05:00 now.advance(years: 1) # => Mon, 02 Nov 2015 01:26:28.558049687 EST -05:00
advance
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def to_a [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone] end
Returns Array of parts of Time in sequence of [seconds, minutes, hours, day, month, year, weekday, yearday, dst?, zone]. now = Time.zone.now # => Tue, 18 Aug 2015 02:29:27.485278555 UTC +00:00 now.to_a # => [27, 29, 2, 18, 8, 2015, 2, 230, false, "UTC"]
to_a
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def to_datetime @to_datetime ||= utc.to_datetime.new_offset(Rational(utc_offset, 86_400)) end
Returns an instance of DateTime with the timezone's UTC offset Time.zone.now.to_datetime # => Tue, 18 Aug 2015 02:32:20 +0000 Time.current.in_time_zone('Hawaii').to_datetime # => Mon, 17 Aug 2015 16:32:20 -1000
to_datetime
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def to_time if preserve_timezone @to_time_with_instance_offset ||= getlocal(utc_offset) else @to_time_with_system_offset ||= getlocal end end
Returns an instance of +Time+, either with the same UTC offset as +self+ or in the local system timezone depending on the setting of +ActiveSupport.to_time_preserves_timezone+.
to_time
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def is_a?(klass) klass == ::Time || super end
Say we're a Time to thwart type checking.
is_a?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def respond_to?(sym, include_priv = false) # ensure that we're not going to throw and rescue from NoMethodError in method_missing which is slow return false if sym.to_sym == :to_str super end
respond_to_missing? is not called in some cases, such as when type conversion is performed with Kernel#String
respond_to?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def respond_to_missing?(sym, include_priv) return false if sym.to_sym == :acts_like_date? time.respond_to?(sym, include_priv) end
Ensure proxy class responds to all methods that underlying time instance responds to.
respond_to_missing?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def method_missing(sym, *args, &block) wrap_with_time_zone time.__send__(sym, *args, &block) rescue NoMethodError => e raise e, e.message.sub(time.inspect, inspect), e.backtrace end
Send the missing method to +time+ instance, and wrap result in a new TimeWithZone with the existing +time_zone+.
method_missing
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/time_with_zone.rb
Apache-2.0
def _parse_binary(bin, entity) case entity["encoding"] when "base64" ::Base64.decode64(bin) else bin end end
TODO: Add support for other encodings
_parse_binary
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini.rb
Apache-2.0
def clear(options = nil) root_dirs = (Dir.children(cache_path) - GITKEEP_FILES) FileUtils.rm_r(root_dirs.collect { |f| File.join(cache_path, f) }) rescue Errno::ENOENT, Errno::ENOTEMPTY end
Deletes all items from the cache. In this case it deletes all the entries in the specified file store directory except for .keep or .gitkeep. Be careful which directory is specified in your config file when using +FileStore+ because everything in that directory will be deleted.
clear
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def cleanup(options = nil) options = merged_options(options) search_dir(cache_path) do |fname| entry = read_entry(fname, **options) delete_entry(fname, **options) if entry && entry.expired? end end
Preemptively iterates through all stored keys and removes the ones which have expired.
cleanup
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def increment(name, amount = 1, options = nil) modify_value(name, amount, options) end
Increments an already existing integer value that is stored in the cache. If the key is not found nothing is done.
increment
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def decrement(name, amount = 1, options = nil) modify_value(name, -amount, options) end
Decrements an already existing integer value that is stored in the cache. If the key is not found nothing is done.
decrement
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def lock_file(file_name, &block) if File.exist?(file_name) File.open(file_name, "r+") do |f| f.flock File::LOCK_EX yield ensure f.flock File::LOCK_UN end else yield end end
Lock a file for a block so only one process can modify it at a time.
lock_file
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def delete_empty_directories(dir) return if File.realpath(dir) == File.realpath(cache_path) if Dir.children(dir).empty? Dir.delete(dir) rescue nil delete_empty_directories(File.dirname(dir)) end end
Delete empty directories in the cache.
delete_empty_directories
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def ensure_cache_path(path) FileUtils.makedirs(path) unless File.exist?(path) end
Make sure a file path's directories exist.
ensure_cache_path
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def modify_value(name, amount, options) file_name = normalize_key(name, options) lock_file(file_name) do options = merged_options(options) if num = read(name, options) num = num.to_i + amount write(name, num, options) num end end end
Modifies the amount of an already existing integer value that is stored in the cache. If the key is not found nothing is done.
modify_value
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/file_store.rb
Apache-2.0
def clear(options = nil) synchronize do @data.clear @cache_size = 0 end end
Delete all data stored in a given cache store.
clear
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def cleanup(options = nil) options = merged_options(options) instrument(:cleanup, size: @data.size) do keys = synchronize { @data.keys } keys.each do |key| entry = @data[key] delete_entry(key, **options) if entry && entry.expired? end end end
Preemptively iterates through all stored keys and removes the ones which have expired.
cleanup
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def prune(target_size, max_time = nil) return if pruning? @pruning = true begin start_time = Concurrent.monotonic_time cleanup instrument(:prune, target_size, from: @cache_size) do keys = synchronize { @data.keys } keys.each do |key| delete_entry(key, **options) return if @cache_size <= target_size || (max_time && Concurrent.monotonic_time - start_time > max_time) end end ensure @pruning = false end end
To ensure entries fit within the specified memory prune the cache by removing the least recently accessed entries.
prune
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def increment(name, amount = 1, options = nil) modify_value(name, amount, options) end
Increment an integer value in the cache.
increment
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def decrement(name, amount = 1, options = nil) modify_value(name, -amount, options) end
Decrement an integer value in the cache.
decrement
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def delete_matched(matcher, options = nil) options = merged_options(options) instrument(:delete_matched, matcher.inspect) do matcher = key_matcher(matcher, options) keys = synchronize { @data.keys } keys.each do |key| delete_entry(key, **options) if key.match(matcher) end end end
Deletes cache entries if the cache key matches a given pattern.
delete_matched
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/memory_store.rb
Apache-2.0
def initialize(*addresses) addresses = addresses.flatten options = addresses.extract_options! super(options) unless [String, Dalli::Client, NilClass].include?(addresses.first.class) raise ArgumentError, "First argument must be an empty array, an array of hosts or a Dalli::Client instance." end if addresses.first.is_a?(Dalli::Client) @data = addresses.first else mem_cache_options = options.dup UNIVERSAL_OPTIONS.each { |name| mem_cache_options.delete(name) } @data = self.class.build_mem_cache(*(addresses + [mem_cache_options])) end end
Creates a new MemCacheStore object, with the given memcached server addresses. Each address is either a host name, or a host-with-port string in the form of "host_name:port". For example: ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229") If no addresses are provided, but ENV['MEMCACHE_SERVERS'] is defined, it will be used instead. Otherwise, MemCacheStore will connect to localhost:11211 (the default memcached port).
initialize
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def increment(name, amount = 1, options = nil) options = merged_options(options) instrument(:increment, name, amount: amount) do rescue_error_with nil do @data.with { |c| c.incr(normalize_key(name, options), amount, options[:expires_in]) } end end end
Increment a cached value. This method uses the memcached incr atomic operator and can only be used on values written with the :raw option. Calling it on a value not stored with :raw will initialize that value to zero.
increment
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def decrement(name, amount = 1, options = nil) options = merged_options(options) instrument(:decrement, name, amount: amount) do rescue_error_with nil do @data.with { |c| c.decr(normalize_key(name, options), amount, options[:expires_in]) } end end end
Decrement a cached value. This method uses the memcached decr atomic operator and can only be used on values written with the :raw option. Calling it on a value not stored with :raw will initialize that value to zero.
decrement
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def clear(options = nil) rescue_error_with(nil) { @data.with { |c| c.flush_all } } end
Clear the entire cache on all memcached servers. This method should be used with care when shared cache is being used.
clear
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def stats @data.with { |c| c.stats } end
Get the statistics from the memcached servers.
stats
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def read_entry(key, **options) rescue_error_with(nil) { deserialize_entry(@data.with { |c| c.get(key, options) }) } end
Read an entry from the cache.
read_entry
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def write_entry(key, entry, **options) method = options[:unless_exist] ? :add : :set value = options[:raw] ? entry.value.to_s : serialize_entry(entry) expires_in = options[:expires_in].to_i if options[:race_condition_ttl] && expires_in > 0 && !options[:raw] # Set the memcache expire a few minutes in the future to support race condition ttls on read expires_in += 5.minutes end rescue_error_with false do # The value "compress: false" prevents duplicate compression within Dalli. @data.with { |c| c.send(method, key, value, expires_in, **options, compress: false) } end end
Write an entry to the cache.
write_entry
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def read_multi_entries(names, **options) keys_to_names = names.index_by { |name| normalize_key(name, options) } raw_values = @data.with { |c| c.get_multi(keys_to_names.keys) } values = {} raw_values.each do |key, value| entry = deserialize_entry(value) unless entry.expired? || entry.mismatched?(normalize_version(keys_to_names[key], options)) values[keys_to_names[key]] = entry.value end end values end
Reads multiple entries from the cache implementation.
read_multi_entries
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def delete_entry(key, **options) rescue_error_with(false) { @data.with { |c| c.delete(key) } } end
Delete an entry from the cache.
delete_entry
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def normalize_key(key, options) key = super if key key = key.dup.force_encoding(Encoding::ASCII_8BIT) key = key.gsub(ESCAPE_KEY_CHARS) { |match| "%#{match.getbyte(0).to_s(16).upcase}" } key = "#{key[0, 213]}:md5:#{ActiveSupport::Digest.hexdigest(key)}" if key.size > 250 end key end
Memcache keys are binaries. So we need to force their encoding to binary before applying the regular expression to ensure we are escaping all characters properly.
normalize_key
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/mem_cache_store.rb
Apache-2.0
def with_local_cache use_temporary_local_cache(LocalStore.new) { yield } end
Use a local cache for the duration of block.
with_local_cache
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/strategy/local_cache.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/strategy/local_cache.rb
Apache-2.0
def middleware @middleware ||= Middleware.new( "ActiveSupport::Cache::Strategy::LocalCache", local_cache_key) end
Middleware class can be inserted as a Rack handler to be local cache for the duration of request.
middleware
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/strategy/local_cache.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/cache/strategy/local_cache.rb
Apache-2.0
def mon_enter mon_try_enter || ActiveSupport::Dependencies.interlock.permit_concurrent_loads { super } end
Enters an exclusive section, but allows dependency loading while blocked
mon_enter
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/load_interlock_aware_monitor.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/load_interlock_aware_monitor.rb
Apache-2.0
def raw_state # :nodoc: synchronize do threads = @sleeping.keys | @sharing.keys | @waiting.keys threads |= [@exclusive_thread] if @exclusive_thread data = {} threads.each do |thread| purpose, compatible = @waiting[thread] data[thread] = { thread: thread, sharing: @sharing[thread], exclusive: @exclusive_thread == thread, purpose: purpose, compatible: compatible, waiting: !!@waiting[thread], sleeper: @sleeping[thread], } end # NB: Yields while holding our *internal* synchronize lock, # which is supposed to be used only for a few instructions at # a time. This allows the caller to inspect additional state # without things changing out from underneath, but would have # disastrous effects upon normal operation. Fortunately, this # method is only intended to be called when things have # already gone wrong. yield data end end
We track Thread objects, instead of just using counters, because we need exclusive locks to be reentrant, and we need to be able to upgrade share locks to exclusive.
raw_state
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def start_exclusive(purpose: nil, compatible: [], no_wait: false) synchronize do unless @exclusive_thread == Thread.current if busy_for_exclusive?(purpose) return false if no_wait yield_shares(purpose: purpose, compatible: compatible, block_share: true) do wait_for(:start_exclusive) { busy_for_exclusive?(purpose) } end end @exclusive_thread = Thread.current end @exclusive_depth += 1 true end end
Returns false if +no_wait+ is set and the lock is not immediately available. Otherwise, returns true after the lock has been acquired. +purpose+ and +compatible+ work together; while this thread is waiting for the exclusive lock, it will yield its share (if any) to any other attempt whose +purpose+ appears in this attempt's +compatible+ list. This allows a "loose" upgrade, which, being less strict, prevents some classes of deadlocks. For many resources, loose upgrades are sufficient: if a thread is awaiting a lock, it is not running any other code. With +purpose+ matching, it is possible to yield only to other threads whose activity will not interfere.
start_exclusive
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def stop_exclusive(compatible: []) synchronize do raise "invalid unlock" if @exclusive_thread != Thread.current @exclusive_depth -= 1 if @exclusive_depth == 0 @exclusive_thread = nil if eligible_waiters?(compatible) yield_shares(compatible: compatible, block_share: true) do wait_for(:stop_exclusive) { @exclusive_thread || eligible_waiters?(compatible) } end end @cv.broadcast end end end
Relinquish the exclusive lock. Must only be called by the thread that called start_exclusive (and currently holds the lock).
stop_exclusive
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def exclusive(purpose: nil, compatible: [], after_compatible: [], no_wait: false) if start_exclusive(purpose: purpose, compatible: compatible, no_wait: no_wait) begin yield ensure stop_exclusive(compatible: after_compatible) end end end
Execute the supplied block while holding the Exclusive lock. If +no_wait+ is set and the lock is not immediately available, returns +nil+ without yielding. Otherwise, returns the result of the block. See +start_exclusive+ for other options.
exclusive
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def sharing start_sharing begin yield ensure stop_sharing end end
Execute the supplied block while holding the Share lock.
sharing
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def yield_shares(purpose: nil, compatible: [], block_share: false) loose_shares = previous_wait = nil synchronize do if loose_shares = @sharing.delete(Thread.current) if previous_wait = @waiting[Thread.current] purpose = nil unless purpose == previous_wait[0] compatible &= previous_wait[1] end compatible |= [false] unless block_share @waiting[Thread.current] = [purpose, compatible] end @cv.broadcast end begin yield ensure synchronize do wait_for(:yield_shares) { @exclusive_thread && @exclusive_thread != Thread.current } if previous_wait @waiting[Thread.current] = previous_wait else @waiting.delete Thread.current end @sharing[Thread.current] = loose_shares if loose_shares end end end
Temporarily give up all held Share locks while executing the supplied block, allowing any +compatible+ exclusive lock request to proceed.
yield_shares
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/concurrency/share_lock.rb
Apache-2.0
def ms(&block) 1000 * realtime(&block) end
Benchmark realtime in milliseconds. Benchmark.realtime { User.all } # => 8.0e-05 Benchmark.ms { User.all } # => 0.074
ms
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/benchmark.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/benchmark.rb
Apache-2.0
def sum(identity = nil, &block) if identity _original_sum_with_required_identity(identity, &block) elsif block_given? map(&block).sum(identity) else inject(:+) || 0 end end
:startdoc: Calculates a sum from the elements. payments.sum { |p| p.price * p.tax_rate } payments.sum(&:price) The latter is a shortcut for: payments.inject(0) { |sum, p| sum + p.price } It can also calculate the sum without the use of a block. [5, 15, 10].sum # => 30 ['foo', 'bar'].sum # => "foobar" [[1, 2], [3, 1, 5]].sum # => [1, 2, 3, 1, 5] The default sum of an empty list is zero. You can override this default: [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
sum
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def index_by if block_given? result = {} each { |elem| result[yield(elem)] = elem } result else to_enum(:index_by) { size if respond_to?(:size) } end end
Convert an enumerable to a hash, using the block result as the key and the element as the value. people.index_by(&:login) # => { "nextangle" => <Person ...>, "chade-" => <Person ...>, ...} people.index_by { |person| "#{person.first_name} #{person.last_name}" } # => { "Chade- Fowlersburg-e" => <Person ...>, "David Heinemeier Hansson" => <Person ...>, ...}
index_by
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def index_with(default = INDEX_WITH_DEFAULT) if block_given? result = {} each { |elem| result[elem] = yield(elem) } result elsif default != INDEX_WITH_DEFAULT result = {} each { |elem| result[elem] = default } result else to_enum(:index_with) { size if respond_to?(:size) } end end
Convert an enumerable to a hash, using the element as the key and the block result as the value. post = Post.new(title: "hey there", body: "what's up?") %i( title body ).index_with { |attr_name| post.public_send(attr_name) } # => { title: "hey there", body: "what's up?" } If an argument is passed instead of a block, it will be used as the value for all elements: %i( created_at updated_at ).index_with(Time.now) # => { created_at: 2020-03-09 22:31:47, updated_at: 2020-03-09 22:31:47 }
index_with
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def many? cnt = 0 if block_given? any? do |element| cnt += 1 if yield element cnt > 1 end else any? { (cnt += 1) > 1 } end end
Returns +true+ if the enumerable has more than 1 element. Functionally equivalent to <tt>enum.to_a.size > 1</tt>. Can be called with a block too, much like any?, so <tt>people.many? { |p| p.age > 26 }</tt> returns +true+ if more than one person is over 26.
many?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def excluding(*elements) elements.flatten!(1) reject { |element| elements.include?(element) } end
Returns a copy of the enumerable excluding the specified elements. ["David", "Rafael", "Aaron", "Todd"].excluding "Aaron", "Todd" # => ["David", "Rafael"] ["David", "Rafael", "Aaron", "Todd"].excluding %w[ Aaron Todd ] # => ["David", "Rafael"] {foo: 1, bar: 2, baz: 3}.excluding :bar # => {foo: 1, baz: 3}
excluding
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def pluck(*keys) if keys.many? map { |element| keys.map { |key| element[key] } } else key = keys.first map { |element| element[key] } end end
Extract the given key from each element in the enumerable. [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"] [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pluck(:id, :name) # => [[1, "David"], [2, "Rafael"]]
pluck
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def pick(*keys) return if none? if keys.many? keys.map { |key| first[key] } else first[keys.first] end end
Extract the given key from the first element in the enumerable. [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) # => "David" [{ id: 1, name: "David" }, { id: 2, name: "Rafael" }].pick(:id, :name) # => [1, "David"]
pick
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def compact_blank #:nodoc: reject { |_k, v| v.blank? } end
Hash#reject has its own definition, so this needs one too.
compact_blank
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def compact_blank! # use delete_if rather than reject! because it always returns self even if nothing changed delete_if { |_k, v| v.blank? } end
Removes all blank values from the +Hash+ in place and returns self. Uses Object#blank? for determining if a value is blank. h = { a: "", b: 1, c: nil, d: [], e: false, f: true } h.compact_blank! # => { b: 1, f: true }
compact_blank!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def sum(identity = nil) if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer)) super else actual_last = exclude_end? ? (last - 1) : last if actual_last >= first sum = identity || 0 sum + (actual_last - first + 1) * (actual_last + first) / 2 else identity || 0 end end end
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
sum
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def sum(init = nil, &block) if init.is_a?(Numeric) || first.is_a?(Numeric) init ||= 0 orig_sum(init, &block) else super end end
Array#sum was added in Ruby 2.4 but it only works with Numeric elements.
sum
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def compact_blank! # use delete_if rather than reject! because it always returns self even if nothing changed delete_if(&:blank?) end
Removes all blank elements from the +Array+ in place and returns self. Uses Object#blank? for determining if an item is blank. a = [1, "", nil, 2, " ", [], {}, false, true] a.compact_blank! # => [1, 2, true]
compact_blank!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/enumerable.rb
Apache-2.0
def is_missing?(location) location.delete_suffix(".rb") == path.to_s.delete_suffix(".rb") end
Returns true if the given path name (except perhaps for the ".rb" extension) is the missing file which caused the exception to be raised.
is_missing?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/load_error.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/load_error.rb
Apache-2.0
def missing_name # Since ruby v2.3.0 `did_you_mean` gem is loaded by default. # It extends NameError#message with spell corrections which are SLOW. # We should use original_message message instead. message = respond_to?(:original_message) ? original_message : self.message return unless message.start_with?("uninitialized constant ") receiver = begin self.receiver rescue ArgumentError nil end if receiver == Object name.to_s elsif receiver "#{real_mod_name(receiver)}::#{self.name}" else if match = message.match(/((::)?([A-Z]\w*)(::[A-Z]\w*)*)$/) match[1] end end end
Extract the name of the missing constant from the exception message. begin HelloWorld rescue NameError => e e.missing_name end # => "HelloWorld"
missing_name
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/name_error.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/name_error.rb
Apache-2.0
def missing_name?(name) if name.is_a? Symbol self.name == name else missing_name == name.to_s end end
Was this exception raised because the given name was missing? begin HelloWorld rescue NameError => e e.missing_name?("HelloWorld") end # => true
missing_name?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/name_error.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/name_error.rb
Apache-2.0
def multiline? options & MULTILINE == MULTILINE end
Returns +true+ if the regexp has the multiline flag set. (/./).multiline? # => false (/./m).multiline? # => true Regexp.new(".").multiline? # => false Regexp.new(".", Regexp::MULTILINE).multiline? # => true
multiline?
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/regexp.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/regexp.rb
Apache-2.0
def from(position) self[position, length] || [] end
Returns the tail of the array from +position+. %w( a b c d ).from(0) # => ["a", "b", "c", "d"] %w( a b c d ).from(2) # => ["c", "d"] %w( a b c d ).from(10) # => [] %w().from(0) # => [] %w( a b c d ).from(-2) # => ["c", "d"] %w( a b c ).from(-10) # => []
from
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
Apache-2.0
def to(position) if position >= 0 take position + 1 else self[0..position] end end
Returns the beginning of the array up to +position+. %w( a b c d ).to(0) # => ["a"] %w( a b c d ).to(2) # => ["a", "b", "c"] %w( a b c d ).to(10) # => ["a", "b", "c", "d"] %w().to(0) # => [] %w( a b c d ).to(-2) # => ["a", "b", "c"] %w( a b c ).to(-10) # => []
to
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
Apache-2.0
def including(*elements) self + elements.flatten(1) end
Returns a new array that includes the passed elements. [ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] [ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ]
including
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
Apache-2.0
def excluding(*elements) self - elements.flatten(1) end
Returns a copy of the Array excluding the specified elements. ["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] [ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ] Note: This is an optimization of <tt>Enumerable#excluding</tt> that uses <tt>Array#-</tt> instead of <tt>Array#reject</tt> for performance reasons.
excluding
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/access.rb
Apache-2.0
def to_sentence(options = {}) options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale) default_connectors = { words_connector: ", ", two_words_connector: " and ", last_word_connector: ", and " } if defined?(I18n) i18n_connectors = I18n.translate(:'support.array', locale: options[:locale], default: {}) default_connectors.merge!(i18n_connectors) end options = default_connectors.merge!(options) case length when 0 +"" when 1 +"#{self[0]}" when 2 +"#{self[0]}#{options[:two_words_connector]}#{self[1]}" else +"#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" end end
Converts the array to a comma-separated sentence where the last element is joined by the connector word. You can pass the following options to change the default behavior. If you pass an option key that doesn't exist in the list below, it will raise an <tt>ArgumentError</tt>. ==== Options * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", "). * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and "). * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and "). * <tt>:locale</tt> - If +i18n+ is available, you can set a locale and use the connector options defined on the 'support.array' namespace in the corresponding dictionary file. ==== Examples [].to_sentence # => "" ['one'].to_sentence # => "one" ['one', 'two'].to_sentence # => "one and two" ['one', 'two', 'three'].to_sentence # => "one, two, and three" ['one', 'two'].to_sentence(passing: 'invalid option') # => ArgumentError: Unknown key: :passing. Valid keys are: :words_connector, :two_words_connector, :last_word_connector, :locale ['one', 'two'].to_sentence(two_words_connector: '-') # => "one-two" ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ') # => "one or two or at least three" Using <tt>:locale</tt> option: # Given this locale dictionary: # # es: # support: # array: # words_connector: " o " # two_words_connector: " y " # last_word_connector: " o al menos " ['uno', 'dos'].to_sentence(locale: :es) # => "uno y dos" ['uno', 'dos', 'tres'].to_sentence(locale: :es) # => "uno o dos o al menos tres"
to_sentence
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
Apache-2.0
def to_formatted_s(format = :default) case format when :db if empty? "null" else collect(&:id).join(",") end else to_default_s end end
Extends <tt>Array#to_s</tt> to convert a collection of elements into a comma separated id list if <tt>:db</tt> argument is given as the format. Blog.all.to_formatted_s(:db) # => "1,2,3" Blog.none.to_formatted_s(:db) # => "null" [1,2].to_formatted_s # => "[1, 2]"
to_formatted_s
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
Apache-2.0
def to_xml(options = {}) require "active_support/builder" unless defined?(Builder::XmlMarkup) options = options.dup options[:indent] ||= 2 options[:builder] ||= Builder::XmlMarkup.new(indent: options[:indent]) options[:root] ||= \ if first.class != Hash && all? { |e| e.is_a?(first.class) } underscored = ActiveSupport::Inflector.underscore(first.class.name) ActiveSupport::Inflector.pluralize(underscored).tr("/", "_") else "objects" end builder = options[:builder] builder.instruct! unless options.delete(:skip_instruct) root = ActiveSupport::XmlMini.rename_key(options[:root].to_s, options) children = options.delete(:children) || root.singularize attributes = options[:skip_types] ? {} : { type: "array" } if empty? builder.tag!(root, attributes) else builder.tag!(root, attributes) do each { |value| ActiveSupport::XmlMini.to_tag(children, value, options) } yield builder if block_given? end end end
Returns a string that represents the array in XML by invoking +to_xml+ on each element. Active Record collections delegate their representation in XML to this method. All elements are expected to respond to +to_xml+, if any of them does not then an exception is raised. The root node reflects the class name of the first element in plural if all elements belong to the same type and that's not Hash: customer.projects.to_xml <?xml version="1.0" encoding="UTF-8"?> <projects type="array"> <project> <amount type="decimal">20000.0</amount> <customer-id type="integer">1567</customer-id> <deal-date type="date">2008-04-09</deal-date> ... </project> <project> <amount type="decimal">57230.0</amount> <customer-id type="integer">1567</customer-id> <deal-date type="date">2008-04-15</deal-date> ... </project> </projects> Otherwise the root element is "objects": [{ foo: 1, bar: 2}, { baz: 3}].to_xml <?xml version="1.0" encoding="UTF-8"?> <objects type="array"> <object> <bar type="integer">2</bar> <foo type="integer">1</foo> </object> <object> <baz type="integer">3</baz> </object> </objects> If the collection is empty the root element is "nil-classes" by default: [].to_xml <?xml version="1.0" encoding="UTF-8"?> <nil-classes type="array"/> To ensure a meaningful root element use the <tt>:root</tt> option: customer_with_no_projects.projects.to_xml(root: 'projects') <?xml version="1.0" encoding="UTF-8"?> <projects type="array"/> By default name of the node for the children of root is <tt>root.singularize</tt>. You can change it with the <tt>:children</tt> option. The +options+ hash is passed downwards: Message.all.to_xml(skip_types: true) <?xml version="1.0" encoding="UTF-8"?> <messages> <message> <created-at>2008-03-07T09:58:18+01:00</created-at> <id>1</id> <name>1</name> <updated-at>2008-03-07T09:58:18+01:00</updated-at> <user-id>1</user-id> </message> </messages>
to_xml
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/conversions.rb
Apache-2.0
def extract! return to_enum(:extract!) { size } unless block_given? extracted_elements = [] reject! do |element| extracted_elements << element if yield(element) end extracted_elements end
Removes and returns the elements for which the block returns a true value. If no block is given, an Enumerator is returned instead. numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] odd_numbers = numbers.extract! { |number| number.odd? } # => [1, 3, 5, 7, 9] numbers # => [0, 2, 4, 6, 8]
extract!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/extract.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/extract.rb
Apache-2.0
def extract_options! if last.is_a?(Hash) && last.extractable_options? pop else {} end end
Extracts options from a set of arguments. Removes and returns the last element in the array if it's a hash, otherwise returns a blank hash. def options(*args) args.extract_options! end options(1, 2) # => {} options(1, 2, a: :b) # => {:a=>:b}
extract_options!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/extract_options.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/extract_options.rb
Apache-2.0
def in_groups_of(number, fill_with = nil) if number.to_i <= 0 raise ArgumentError, "Group size must be a positive integer, was #{number.inspect}" end if fill_with == false collection = self else # size % number gives how many extra we have; # subtracting from number gives how many to add; # modulo number ensures we don't add group of just fill. padding = (number - size % number) % number collection = dup.concat(Array.new(padding, fill_with)) end if block_given? collection.each_slice(number) { |slice| yield(slice) } else collection.each_slice(number).to_a end end
Splits or iterates over the array in groups of size +number+, padding any remaining slots with +fill_with+ unless it is +false+. %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group} ["1", "2", "3"] ["4", "5", "6"] ["7", "8", "9"] ["10", nil, nil] %w(1 2 3 4 5).in_groups_of(2, '&nbsp;') {|group| p group} ["1", "2"] ["3", "4"] ["5", "&nbsp;"] %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group} ["1", "2"] ["3", "4"] ["5"]
in_groups_of
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/grouping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/grouping.rb
Apache-2.0
def in_groups(number, fill_with = nil) # size.div number gives minor group size; # size % number gives how many objects need extra accommodation; # each group hold either division or division + 1 items. division = size.div number modulo = size % number # create a new array avoiding dup groups = [] start = 0 number.times do |index| length = division + (modulo > 0 && modulo > index ? 1 : 0) groups << last_group = slice(start, length) last_group << fill_with if fill_with != false && modulo > 0 && length == division start += length end if block_given? groups.each { |g| yield(g) } else groups end end
Splits or iterates over the array in +number+ of groups, padding any remaining slots with +fill_with+ unless it is +false+. %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group} ["1", "2", "3", "4"] ["5", "6", "7", nil] ["8", "9", "10", nil] %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, '&nbsp;') {|group| p group} ["1", "2", "3", "4"] ["5", "6", "7", "&nbsp;"] ["8", "9", "10", "&nbsp;"] %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group} ["1", "2", "3"] ["4", "5"] ["6", "7"]
in_groups
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/grouping.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/array/grouping.rb
Apache-2.0
def class_attribute(*attrs, instance_accessor: true, instance_reader: instance_accessor, instance_writer: instance_accessor, instance_predicate: true, default: nil) class_methods, methods = [], [] attrs.each do |name| unless name.is_a?(Symbol) || name.is_a?(String) raise TypeError, "#{name.inspect} is not a symbol nor a string" end class_methods << <<~RUBY # In case the method exists and is not public silence_redefinition_of_method def #{name} end RUBY methods << <<~RUBY if instance_reader silence_redefinition_of_method def #{name} defined?(@#{name}) ? @#{name} : self.class.#{name} end RUBY class_methods << <<~RUBY silence_redefinition_of_method def #{name}=(value) redefine_method(:#{name}) { value } if singleton_class? redefine_singleton_method(:#{name}) { value } value end RUBY methods << <<~RUBY if instance_writer silence_redefinition_of_method(:#{name}=) attr_writer :#{name} RUBY if instance_predicate class_methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end" if instance_reader methods << "silence_redefinition_of_method def #{name}?; !!self.#{name}; end" end end end location = caller_locations(1, 1).first class_eval(["class << self", *class_methods, "end", *methods].join(";").tr("\n", ";"), location.path, location.lineno) attrs.each { |name| public_send("#{name}=", default) } end
Declare a class-level attribute whose value is inheritable by subclasses. Subclasses can change their own value and it will not impact parent class. ==== Options * <tt>:instance_reader</tt> - Sets the instance reader method (defaults to true). * <tt>:instance_writer</tt> - Sets the instance writer method (defaults to true). * <tt>:instance_accessor</tt> - Sets both instance methods (defaults to true). * <tt>:instance_predicate</tt> - Sets a predicate method (defaults to true). * <tt>:default</tt> - Sets a default value for the attribute (defaults to nil). ==== Examples class Base class_attribute :setting end class Subclass < Base end Base.setting = true Subclass.setting # => true Subclass.setting = false Subclass.setting # => false Base.setting # => true In the above case as long as Subclass does not assign a value to setting by performing <tt>Subclass.setting = _something_</tt>, <tt>Subclass.setting</tt> would read value assigned to parent class. Once Subclass assigns a value then the value assigned by Subclass would be returned. This matches normal Ruby method inheritance: think of writing an attribute on a subclass as overriding the reader method. However, you need to be aware when using +class_attribute+ with mutable structures as +Array+ or +Hash+. In such cases, you don't want to do changes in place. Instead use setters: Base.setting = [] Base.setting # => [] Subclass.setting # => [] # Appending in child changes both parent and child because it is the same object: Subclass.setting << :foo Base.setting # => [:foo] Subclass.setting # => [:foo] # Use setters to not propagate changes: Base.setting = [] Subclass.setting += [:foo] Base.setting # => [] Subclass.setting # => [:foo] For convenience, an instance predicate method is defined as well. To skip it, pass <tt>instance_predicate: false</tt>. Subclass.setting? # => false Instances may overwrite the class value in the same way: Base.setting = true object = Base.new object.setting # => true object.setting = false object.setting # => false Base.setting # => true To opt out of the instance reader method, pass <tt>instance_reader: false</tt>. object.setting # => NoMethodError object.setting? # => NoMethodError To opt out of the instance writer method, pass <tt>instance_writer: false</tt>. object.setting = false # => NoMethodError To opt out of both instance methods, pass <tt>instance_accessor: false</tt>. To set a default value for the attribute, pass <tt>default:</tt>, like so: class_attribute :settings, default: {}
class_attribute
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/attribute.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/attribute.rb
Apache-2.0
def descendants ObjectSpace.each_object(singleton_class).reject do |k| k.singleton_class? || k == self end end
Returns an array with all classes that are < than its receiver. class C; end C.descendants # => [] class B < C; end C.descendants # => [B] class A < B; end C.descendants # => [B, A] class D < C; end C.descendants # => [B, A, D]
descendants
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/subclasses.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/subclasses.rb
Apache-2.0
def subclasses descendants.select { |descendant| descendant.superclass == self } end
Returns an array with the direct children of +self+. class Foo; end class Bar < Foo; end class Baz < Bar; end Foo.subclasses # => [Bar]
subclasses
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/subclasses.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/class/subclasses.rb
Apache-2.0
def beginning_of_week Thread.current[:beginning_of_week] || beginning_of_week_default || :monday end
Returns the week start (e.g. :monday) for the current request, if this has been set (via Date.beginning_of_week=). If <tt>Date.beginning_of_week</tt> has not been set for the current request, returns the week start specified in <tt>config.beginning_of_week</tt>. If no config.beginning_of_week was specified, returns :monday.
beginning_of_week
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def find_beginning_of_week!(week_start) raise ArgumentError, "Invalid beginning of week: #{week_start}" unless ::Date::DAYS_INTO_WEEK.key?(week_start) week_start end
Returns week start day symbol (e.g. :monday), or raises an +ArgumentError+ for invalid day symbol.
find_beginning_of_week!
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def current ::Time.zone ? ::Time.zone.today : ::Date.today end
Returns Time.zone.today when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns Date.today.
current
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def advance(options) d = self d = d >> options[:years] * 12 if options[:years] d = d >> options[:months] if options[:months] d = d + options[:weeks] * 7 if options[:weeks] d = d + options[:days] if options[:days] d end
Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
advance
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def change(options) ::Date.new( options.fetch(:year, year), options.fetch(:month, month), options.fetch(:day, day) ) end
Returns a new Date where one or more of the elements have been changed according to the +options+ parameter. The +options+ parameter is a hash with a combination of these keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>. Date.new(2007, 5, 12).change(day: 1) # => Date.new(2007, 5, 1) Date.new(2007, 5, 12).change(year: 2005, month: 1) # => Date.new(2005, 1, 12)
change
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def compare_with_coercion(other) if other.is_a?(Time) to_datetime <=> other else compare_without_coercion(other) end end
Allow Date to be compared with Time by converting to DateTime and relying on the <=> from there.
compare_with_coercion
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/calculations.rb
Apache-2.0
def to_formatted_s(format = :default) if formatter = DATE_FORMATS[format] if formatter.respond_to?(:call) formatter.call(self).to_s else strftime(formatter) end else to_default_s end end
Convert to a formatted string. See DATE_FORMATS for predefined formats. This method is aliased to <tt>to_s</tt>. date = Date.new(2007, 11, 10) # => Sat, 10 Nov 2007 date.to_formatted_s(:db) # => "2007-11-10" date.to_s(:db) # => "2007-11-10" date.to_formatted_s(:short) # => "10 Nov" date.to_formatted_s(:number) # => "20071110" date.to_formatted_s(:long) # => "November 10, 2007" date.to_formatted_s(:long_ordinal) # => "November 10th, 2007" date.to_formatted_s(:rfc822) # => "10 Nov 2007" date.to_formatted_s(:iso8601) # => "2007-11-10" == Adding your own date formats to to_formatted_s You can add your own formats to the Date::DATE_FORMATS hash. Use the format name as the hash key and either a strftime string or Proc instance that takes a date argument as the value. # config/initializers/date_formats.rb Date::DATE_FORMATS[:month_and_year] = '%B %Y' Date::DATE_FORMATS[:short_ordinal] = ->(date) { date.strftime("%B #{date.day.ordinalize}") }
to_formatted_s
ruby
collabnix/kubelabs
.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/conversions.rb
https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/date/conversions.rb
Apache-2.0