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 gigabytes
self * GIGABYTE
end | Returns the number of bytes equivalent to the gigabytes provided.
2.gigabytes # => 2_147_483_648 | gigabytes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/bytes.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/numeric/bytes.rb | Apache-2.0 |
def terabytes
self * TERABYTE
end | Returns the number of bytes equivalent to the terabytes provided.
2.terabytes # => 2_199_023_255_552 | terabytes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/bytes.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/numeric/bytes.rb | Apache-2.0 |
def petabytes
self * PETABYTE
end | Returns the number of bytes equivalent to the petabytes provided.
2.petabytes # => 2_251_799_813_685_248 | petabytes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/bytes.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/numeric/bytes.rb | Apache-2.0 |
def exabytes
self * EXABYTE
end | Returns the number of bytes equivalent to the exabytes provided.
2.exabytes # => 2_305_843_009_213_693_952 | exabytes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/bytes.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/numeric/bytes.rb | Apache-2.0 |
def fortnights
ActiveSupport::Duration.weeks(self * 2)
end | Returns a Duration instance matching the number of fortnights provided.
2.fortnights # => 4 weeks | fortnights | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/time.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/numeric/time.rb | Apache-2.0 |
def in_milliseconds
self * 1000
end | Returns the number of milliseconds equivalent to the seconds provided.
Used with the standard time durations.
2.in_milliseconds # => 2000
1.hour.in_milliseconds # => 3600000 | in_milliseconds | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/numeric/time.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/numeric/time.rb | Apache-2.0 |
def acts_like?(duck)
case duck
when :time
respond_to? :acts_like_time?
when :date
respond_to? :acts_like_date?
when :string
respond_to? :acts_like_string?
else
respond_to? :"acts_like_#{duck}?"
end
end | A duck-type assistant method. For example, Active Support extends Date
to define an <tt>acts_like_date?</tt> method, and extends Time to define
<tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and
<tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that
we want to act like Time simply need to define an <tt>acts_like_time?</tt> method. | acts_like? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/acts_like.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/object/acts_like.rb | Apache-2.0 |
def blank?
respond_to?(:empty?) ? !!empty? : !self
end | An object is blank if it's false, empty, or a whitespace string.
For example, +nil+, '', ' ', [], {}, and +false+ are all blank.
This simplifies
!address || address.empty?
to
address.blank?
@return [true, false] | blank? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/blank.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/object/blank.rb | Apache-2.0 |
def presence
self if present?
end | Returns the receiver if it's present otherwise returns +nil+.
<tt>object.presence</tt> is equivalent to
object.present? ? object : nil
For example, something like
state = params[:state] if params[:state].present?
country = params[:country] if params[:country].present?
region = state || country || 'US'
becomes
region = params[:state].presence || params[:country].presence || 'US'
@return [Object] | presence | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/blank.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/object/blank.rb | Apache-2.0 |
def blank?
# The regexp that matches blank strings is expensive. For the case of empty
# strings we can speed up this method (~3.5x) with an empty? call. The
# penalty for the rest of strings is marginal.
empty? ||
begin
BLANK_RE.match?(self)
rescue Encoding::CompatibilityError
ENCODED_BLANKS[self.encoding].match?(self)
end
end | A string is blank if it's empty or contains whitespaces only:
''.blank? # => true
' '.blank? # => true
"\t\n\r".blank? # => true
' blah '.blank? # => false
Unicode whitespace is supported:
"\u00a0".blank? # => true
@return [true, false] | blank? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/blank.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/object/blank.rb | Apache-2.0 |
def deep_dup
duplicable? ? dup : self
end | Returns a deep copy of object if it's duplicable. If it's
not duplicable, returns +self+.
object = Object.new
dup = object.deep_dup
dup.instance_variable_set(:@a, 1)
object.instance_variable_defined?(:@a) # => false
dup.instance_variable_defined?(:@a) # => true | deep_dup | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/deep_dup.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/object/deep_dup.rb | Apache-2.0 |
def deep_dup
hash = dup
each_pair do |key, value|
if (::String === key && key.frozen?) || ::Symbol === key
hash[key] = value.deep_dup
else
hash.delete(key)
hash[key.deep_dup] = value.deep_dup
end
end
hash
end | Returns a deep copy of hash.
hash = { a: { b: 'b' } }
dup = hash.deep_dup
dup[:a][:c] = 'c'
hash[:a][:c] # => nil
dup[:a][:c] # => "c" | deep_dup | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/deep_dup.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/object/deep_dup.rb | Apache-2.0 |
def in?(another_object)
another_object.include?(self)
rescue NoMethodError
raise ArgumentError.new("The parameter passed to #in? must respond to #include?")
end | Returns true if this object is included in the argument. Argument must be
any object which responds to +#include?+. Usage:
characters = ["Konata", "Kagami", "Tsukasa"]
"Konata".in?(characters) # => true
This will throw an +ArgumentError+ if the argument doesn't respond
to +#include?+. | in? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/inclusion.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/object/inclusion.rb | Apache-2.0 |
def presence_in(another_object)
in?(another_object) ? self : nil
end | Returns the receiver if it's included in the argument otherwise returns +nil+.
Argument must be any object which responds to +#include?+. Usage:
params[:bucket_type].presence_in %w( project calendar )
This will throw an +ArgumentError+ if the argument doesn't respond to +#include?+.
@return [Object] | presence_in | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/inclusion.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/object/inclusion.rb | Apache-2.0 |
def instance_values
Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }]
end | Returns a hash with string keys that maps instance variable names without "@" to their
corresponding values.
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} | instance_values | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/instance_variables.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/object/instance_variables.rb | Apache-2.0 |
def as_json(options = nil) #:nodoc:
finite? ? self : nil
end | Encoding Infinity or NaN to JSON should return "null". The default returns
"Infinity" or "NaN" which are not valid JSON. | as_json | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/json.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/object/json.rb | Apache-2.0 |
def as_json(options = nil) #:nodoc:
finite? ? to_s : nil
end | A BigDecimal would be naturally represented as a JSON number. Most libraries,
however, parse non-integer JSON numbers directly as floats. Clients using
those libraries would get in general a wrong number and no way to recover
other than manually inspecting the string with the JSON code itself.
That's why a JSON string is returned. The JSON literal is not numeric, but
if the other end knows by contract that the data is supposed to be a
BigDecimal, it still has the chance to post-process the string and get the
real value. | as_json | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/json.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/object/json.rb | Apache-2.0 |
def to_param
collect(&:to_param).join "/"
end | Calls <tt>to_param</tt> on all its elements and joins the result with
slashes. This is used by <tt>url_for</tt> in Action Pack. | to_param | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/to_query.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/object/to_query.rb | Apache-2.0 |
def to_query(key)
prefix = "#{key}[]"
if empty?
nil.to_query(prefix)
else
collect { |value| value.to_query(prefix) }.join "&"
end
end | Converts an array into a string suitable for use as a URL query string,
using the given +key+ as the param name.
['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" | to_query | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/to_query.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/object/to_query.rb | Apache-2.0 |
def to_query(namespace = nil)
query = collect do |key, value|
unless (value.is_a?(Hash) || value.is_a?(Array)) && value.empty?
value.to_query(namespace ? "#{namespace}[#{key}]" : key)
end
end.compact
query.sort! unless namespace.to_s.include?("[]")
query.join("&")
end | Returns a string representation of the receiver suitable for use as a URL
query string:
{name: 'David', nationality: 'Danish'}.to_query
# => "name=David&nationality=Danish"
An optional namespace can be passed to enclose key names:
{name: 'David', nationality: 'Danish'}.to_query('user')
# => "user%5Bname%5D=David&user%5Bnationality%5D=Danish"
The string pairs "key=value" that conform the query string
are sorted lexicographically in ascending order.
This method is also aliased as +to_param+. | to_query | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/to_query.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/object/to_query.rb | Apache-2.0 |
def with_options(options, &block)
option_merger = ActiveSupport::OptionMerger.new(self, options)
block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger)
end | An elegant way to factor duplication out of options passed to a series of
method calls. Each method called in the block, with the block variable as
the receiver, will have its options merged with the default +options+ hash
provided. Each method called on the block variable must take an options
hash as its final argument.
Without <tt>with_options</tt>, this code contains duplication:
class Account < ActiveRecord::Base
has_many :customers, dependent: :destroy
has_many :products, dependent: :destroy
has_many :invoices, dependent: :destroy
has_many :expenses, dependent: :destroy
end
Using <tt>with_options</tt>, we can remove the duplication:
class Account < ActiveRecord::Base
with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
assoc.has_many :expenses
end
end
It can also be used with an explicit receiver:
I18n.with_options locale: user.locale, scope: 'newsletter' do |i18n|
subject i18n.t :subject
body i18n.t :body, user_name: user.name
end
When you don't pass an explicit receiver, it executes the whole block
in merging options context:
class Account < ActiveRecord::Base
with_options dependent: :destroy do
has_many :customers
has_many :products
has_many :invoices
has_many :expenses
end
end
<tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
NOTE: Each nesting level will merge inherited defaults in addition to their own.
class Post < ActiveRecord::Base
with_options if: :persisted?, length: { minimum: 50 } do
validates :content, if: -> { content.present? }
end
end
The code is equivalent to:
validates :content, length: { minimum: 50 }, if: -> { content.present? }
Hence the inherited default for +if+ key is ignored.
NOTE: You cannot call class methods implicitly inside of with_options.
You can access these methods using the class name instead:
class Phone < ActiveRecord::Base
enum phone_number_type: { home: 0, office: 1, mobile: 2 }
with_options presence: true do
validates :phone_number_type, inclusion: { in: Phone.phone_number_types.keys }
end
end | with_options | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/object/with_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/object/with_options.rb | Apache-2.0 |
def include?(value)
if value.is_a?(::Range)
is_backwards_op = value.exclude_end? ? :>= : :>
return false if value.begin && value.end && value.begin.public_send(is_backwards_op, value.end)
# 1...10 includes 1..9 but it does not include 1..10.
# 1..10 includes 1...11 but it does not include 1...12.
operator = exclude_end? && !value.exclude_end? ? :< : :<=
value_max = !exclude_end? && value.exclude_end? ? value.max : value.last
super(value.first) && (self.end.nil? || value_max.public_send(operator, last))
else
super
end
end | Extends the default Range#include? to support range comparisons.
(1..5).include?(1..5) # => true
(1..5).include?(2..3) # => true
(1..5).include?(1...6) # => true
(1..5).include?(2..6) # => false
The native Range#include? behavior is untouched.
('a'..'f').include?('c') # => true
(5..9).include?(11) # => false
The given range must be fully bounded, with both start and end. | include? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/range/compare_range.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/range/compare_range.rb | Apache-2.0 |
def cover?(value)
if value.is_a?(::Range)
is_backwards_op = value.exclude_end? ? :>= : :>
return false if value.begin && value.end && value.begin.public_send(is_backwards_op, value.end)
# 1...10 covers 1..9 but it does not cover 1..10.
# 1..10 covers 1...11 but it does not cover 1...12.
operator = exclude_end? && !value.exclude_end? ? :< : :<=
value_max = !exclude_end? && value.exclude_end? ? value.max : value.last
super(value.first) && (self.end.nil? || value_max.public_send(operator, last))
else
super
end
end | Extends the default Range#cover? to support range comparisons.
(1..5).cover?(1..5) # => true
(1..5).cover?(2..3) # => true
(1..5).cover?(1...6) # => true
(1..5).cover?(2..6) # => false
The native Range#cover? behavior is untouched.
('a'..'f').cover?('c') # => true
(5..9).cover?(11) # => false
The given range must be fully bounded, with both start and end. | cover? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/range/compare_range.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/range/compare_range.rb | Apache-2.0 |
def to_s(format = :default)
if formatter = RANGE_FORMATS[format]
formatter.call(first, last)
else
super()
end
end | Convert range to a formatted string. See RANGE_FORMATS for predefined formats.
range = (1..100) # => 1..100
range.to_s # => "1..100"
range.to_s(:db) # => "BETWEEN '1' AND '100'"
== Adding your own range formats to to_s
You can add your own formats to the Range::RANGE_FORMATS hash.
Use the format name as the hash key and a Proc instance.
# config/initializers/range_formats.rb
Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_s(:db)} and #{stop.to_s(:db)}" } | to_s | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/range/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/range/conversions.rb | Apache-2.0 |
def include?(value)
if self.begin.is_a?(TimeWithZone) || self.end.is_a?(TimeWithZone)
ActiveSupport::Deprecation.warn(<<-MSG.squish)
Using `Range#include?` to check the inclusion of a value in
a date time range is deprecated.
It is recommended to use `Range#cover?` instead of `Range#include?` to
check the inclusion of a value in a date time range.
MSG
cover?(value)
else
super
end
end | Extends the default Range#include? to support ActiveSupport::TimeWithZone.
(1.hour.ago..1.hour.from_now).include?(Time.current) # => true | include? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/range/include_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/core_ext/range/include_time_with_zone.rb | Apache-2.0 |
def overlaps?(other)
cover?(other.first) || other.cover?(first)
end | Compare two ranges and see if they overlap each other
(1..5).overlaps?(4..6) # => true
(1..5).overlaps?(7..9) # => false | overlaps? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/range/overlaps.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/range/overlaps.rb | Apache-2.0 |
def from(position)
self[position, length]
end | Returns a substring from the given position to the end of the string.
If the position is negative, it is counted from the end of the string.
str = "hello"
str.from(0) # => "hello"
str.from(3) # => "lo"
str.from(-2) # => "lo"
You can mix it with +to+ method and do fun things like:
str = "hello"
str.from(0).to(-1) # => "hello"
str.from(1).to(-2) # => "ell" | from | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/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/string/access.rb | Apache-2.0 |
def to(position)
position += size if position < 0
self[0, position + 1] || +""
end | Returns a substring from the beginning of the string to the given position.
If the position is negative, it is counted from the end of the string.
str = "hello"
str.to(0) # => "h"
str.to(3) # => "hell"
str.to(-2) # => "hell"
You can mix it with +from+ method and do fun things like:
str = "hello"
str.from(0).to(-1) # => "hello"
str.from(1).to(-2) # => "ell" | to | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/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/string/access.rb | Apache-2.0 |
def to_time(form = :local)
parts = Date._parse(self, false)
used_keys = %i(year mon mday hour min sec sec_fraction offset)
return if (parts.keys & used_keys).empty?
now = Time.now
time = Time.new(
parts.fetch(:year, now.year),
parts.fetch(:mon, now.month),
parts.fetch(:mday, now.day),
parts.fetch(:hour, 0),
parts.fetch(:min, 0),
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
parts.fetch(:offset, form == :utc ? 0 : nil)
)
form == :utc ? time.utc : time.to_time
end | Converts a string to a Time value.
The +form+ can be either :utc or :local (default :local).
The time is parsed using Time.parse method.
If +form+ is :local, then the time is in the system timezone.
If the date part is missing then the current date is used and if
the time part is missing then it is assumed to be 00:00:00.
"13-12-2012".to_time # => 2012-12-13 00:00:00 +0100
"06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13 06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time # => 2012-12-13 06:12:00 +0100
"2012-12-13T06:12".to_time(:utc) # => 2012-12-13 06:12:00 UTC
"12/13/2012".to_time # => ArgumentError: argument out of range
"1604326192".to_time # => ArgumentError: argument out of range | to_time | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/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/string/conversions.rb | Apache-2.0 |
def to_date
::Date.parse(self, false) unless blank?
end | Converts a string to a Date value.
"1-1-2012".to_date # => Sun, 01 Jan 2012
"01/01/2012".to_date # => Sun, 01 Jan 2012
"2012-12-13".to_date # => Thu, 13 Dec 2012
"12/13/2012".to_date # => ArgumentError: invalid date | to_date | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/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/string/conversions.rb | Apache-2.0 |
def to_datetime
::DateTime.parse(self, false) unless blank?
end | Converts a string to a DateTime value.
"1-1-2012".to_datetime # => Sun, 01 Jan 2012 00:00:00 +0000
"01/01/2012 23:59:59".to_datetime # => Sun, 01 Jan 2012 23:59:59 +0000
"2012-12-13 12:50".to_datetime # => Thu, 13 Dec 2012 12:50:00 +0000
"12/13/2012".to_datetime # => ArgumentError: invalid date | to_datetime | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/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/string/conversions.rb | Apache-2.0 |
def squish!
gsub!(/[[:space:]]+/, " ")
strip!
self
end | Performs a destructive squish. See String#squish.
str = " foo bar \n \t boo"
str.squish! # => "foo bar boo"
str # => "foo bar boo" | squish! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/filters.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/string/filters.rb | Apache-2.0 |
def remove!(*patterns)
patterns.each do |pattern|
gsub! pattern, ""
end
self
end | Alters the string by removing all occurrences of the patterns.
str = "foo bar test"
str.remove!(" test", /bar/) # => "foo "
str # => "foo " | remove! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/filters.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/string/filters.rb | Apache-2.0 |
def truncate(truncate_at, options = {})
return dup unless length > truncate_at
omission = options[:omission] || "..."
length_with_room_for_omission = truncate_at - omission.length
stop = \
if options[:separator]
rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
else
length_with_room_for_omission
end
+"#{self[0, stop]}#{omission}"
end | Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>:
'Once upon a time in a world far far away'.truncate(27)
# => "Once upon a time in a wo..."
Pass a string or regexp <tt>:separator</tt> to truncate +text+ at a natural break:
'Once upon a time in a world far far away'.truncate(27, separator: ' ')
# => "Once upon a time in a..."
'Once upon a time in a world far far away'.truncate(27, separator: /\s/)
# => "Once upon a time in a..."
The last characters will be replaced with the <tt>:omission</tt> string (defaults to "...")
for a total length not exceeding <tt>length</tt>:
'And they found that many people were sleeping better.'.truncate(25, omission: '... (continued)')
# => "And they f... (continued)" | truncate | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/filters.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/string/filters.rb | Apache-2.0 |
def indent!(amount, indent_string = nil, indent_empty_lines = false)
indent_string = indent_string || self[/^[ \t]/] || " "
re = indent_empty_lines ? /^/ : /^(?!$)/
gsub!(re, indent_string * amount)
end | Same as +indent+, except it indents the receiver in-place.
Returns the indented string, or +nil+ if there was nothing to indent. | indent! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/indent.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/string/indent.rb | Apache-2.0 |
def indent(amount, indent_string = nil, indent_empty_lines = false)
dup.tap { |_| _.indent!(amount, indent_string, indent_empty_lines) }
end | Indents the lines in the receiver:
<<EOS.indent(2)
def some_method
some_code
end
EOS
# =>
def some_method
some_code
end
The second argument, +indent_string+, specifies which indent string to
use. The default is +nil+, which tells the method to make a guess by
peeking at the first indented line, and fallback to a space if there is
none.
" foo".indent(2) # => " foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t") # => "\t\tfoo"
While +indent_string+ is typically one space or tab, it may be any string.
The third argument, +indent_empty_lines+, is a flag that says whether
empty lines should be indented. Default is false.
"foo\n\nbar".indent(2) # => " foo\n\n bar"
"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar" | indent | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/indent.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/string/indent.rb | Apache-2.0 |
def pluralize(count = nil, locale = :en)
locale = count if count.is_a?(Symbol)
if count == 1
dup
else
ActiveSupport::Inflector.pluralize(self, locale)
end
end | Returns the plural form of the word in the string.
If the optional parameter +count+ is specified,
the singular form will be returned if <tt>count == 1</tt>.
For any other value of +count+ the plural will be returned.
If the optional parameter +locale+ is specified,
the word will be pluralized as a word of that language.
By default, this parameter is set to <tt>:en</tt>.
You must define your own inflection rules for languages other than English.
'post'.pluralize # => "posts"
'octopus'.pluralize # => "octopi"
'sheep'.pluralize # => "sheep"
'words'.pluralize # => "words"
'the blue mailman'.pluralize # => "the blue mailmen"
'CamelOctopus'.pluralize # => "CamelOctopi"
'apple'.pluralize(1) # => "apple"
'apple'.pluralize(2) # => "apples"
'ley'.pluralize(:es) # => "leyes"
'ley'.pluralize(1, :es) # => "ley"
See ActiveSupport::Inflector.pluralize. | pluralize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def singularize(locale = :en)
ActiveSupport::Inflector.singularize(self, locale)
end | The reverse of +pluralize+, returns the singular form of a word in a string.
If the optional parameter +locale+ is specified,
the word will be singularized as a word of that language.
By default, this parameter is set to <tt>:en</tt>.
You must define your own inflection rules for languages other than English.
'posts'.singularize # => "post"
'octopi'.singularize # => "octopus"
'sheep'.singularize # => "sheep"
'word'.singularize # => "word"
'the blue mailmen'.singularize # => "the blue mailman"
'CamelOctopi'.singularize # => "CamelOctopus"
'leyes'.singularize(:es) # => "ley"
See ActiveSupport::Inflector.singularize. | singularize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def camelize(first_letter = :upper)
case first_letter
when :upper
ActiveSupport::Inflector.camelize(self, true)
when :lower
ActiveSupport::Inflector.camelize(self, false)
else
raise ArgumentError, "Invalid option, use either :upper or :lower."
end
end | By default, +camelize+ converts strings to UpperCamelCase. If the argument to camelize
is set to <tt>:lower</tt> then camelize produces lowerCamelCase.
+camelize+ will also convert '/' to '::' which is useful for converting paths to namespaces.
'active_record'.camelize # => "ActiveRecord"
'active_record'.camelize(:lower) # => "activeRecord"
'active_record/errors'.camelize # => "ActiveRecord::Errors"
'active_record/errors'.camelize(:lower) # => "activeRecord::Errors"
+camelize+ is also aliased as +camelcase+.
See ActiveSupport::Inflector.camelize. | camelize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def titleize(keep_id_suffix: false)
ActiveSupport::Inflector.titleize(self, keep_id_suffix: keep_id_suffix)
end | Capitalizes all the words and replaces some characters in the string to create
a nicer looking title. +titleize+ is meant for creating pretty output. It is not
used in the Rails internals.
The trailing '_id','Id'.. can be kept and capitalized by setting the
optional parameter +keep_id_suffix+ to true.
By default, this parameter is false.
'man from the boondocks'.titleize # => "Man From The Boondocks"
'x-men: the last stand'.titleize # => "X Men: The Last Stand"
'string_ending_with_id'.titleize(keep_id_suffix: true) # => "String Ending With Id"
+titleize+ is also aliased as +titlecase+.
See ActiveSupport::Inflector.titleize. | titleize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def parameterize(separator: "-", preserve_case: false, locale: nil)
ActiveSupport::Inflector.parameterize(self, separator: separator, preserve_case: preserve_case, locale: locale)
end | Replaces special characters in a string so that it may be used as part of a 'pretty' URL.
If the optional parameter +locale+ is specified,
the word will be parameterized as a word of that language.
By default, this parameter is set to <tt>nil</tt> and it will use
the configured <tt>I18n.locale</tt>.
class Person
def to_param
"#{id}-#{name.parameterize}"
end
end
@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">
<%= link_to(@person.name, person_path) %>
# => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
To preserve the case of the characters in a string, use the +preserve_case+ argument.
class Person
def to_param
"#{id}-#{name.parameterize(preserve_case: true)}"
end
end
@person = Person.find(1)
# => #<Person id: 1, name: "Donald E. Knuth">
<%= link_to(@person.name, person_path) %>
# => <a href="/person/1-Donald-E-Knuth">Donald E. Knuth</a>
See ActiveSupport::Inflector.parameterize. | parameterize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def humanize(capitalize: true, keep_id_suffix: false)
ActiveSupport::Inflector.humanize(self, capitalize: capitalize, keep_id_suffix: keep_id_suffix)
end | Capitalizes the first word, turns underscores into spaces, and (by default)strips a
trailing '_id' if present.
Like +titleize+, this is meant for creating pretty output.
The capitalization of the first word can be turned off by setting the
optional parameter +capitalize+ to false.
By default, this parameter is true.
The trailing '_id' can be kept and capitalized by setting the
optional parameter +keep_id_suffix+ to true.
By default, this parameter is false.
'employee_salary'.humanize # => "Employee salary"
'author_id'.humanize # => "Author"
'author_id'.humanize(capitalize: false) # => "author"
'_id'.humanize # => "Id"
'author_id'.humanize(keep_id_suffix: true) # => "Author Id"
See ActiveSupport::Inflector.humanize. | humanize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def foreign_key(separate_class_name_and_id_with_underscore = true)
ActiveSupport::Inflector.foreign_key(self, separate_class_name_and_id_with_underscore)
end | Creates a foreign key name from a class name.
+separate_class_name_and_id_with_underscore+ sets whether
the method should put '_' between the name and 'id'.
'Message'.foreign_key # => "message_id"
'Message'.foreign_key(false) # => "messageid"
'Admin::Post'.foreign_key # => "post_id"
See ActiveSupport::Inflector.foreign_key. | foreign_key | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/inflections.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/string/inflections.rb | Apache-2.0 |
def unwrapped_html_escape(s) # :nodoc:
s = s.to_s
if s.html_safe?
s
else
CGI.escapeHTML(ActiveSupport::Multibyte::Unicode.tidy_bytes(s))
end
end | HTML escapes strings but doesn't wrap them with an ActiveSupport::SafeBuffer.
This method is not for public consumption! Seriously! | unwrapped_html_escape | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/output_safety.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/string/output_safety.rb | Apache-2.0 |
def html_escape_once(s)
result = ActiveSupport::Multibyte::Unicode.tidy_bytes(s.to_s).gsub(HTML_ESCAPE_ONCE_REGEXP, HTML_ESCAPE)
s.html_safe? ? result.html_safe : result
end | A utility method for escaping HTML without affecting existing escaped entities.
html_escape_once('1 < 2 & 3')
# => "1 < 2 & 3"
html_escape_once('<< Accept & Checkout')
# => "<< Accept & Checkout" | html_escape_once | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/output_safety.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/string/output_safety.rb | Apache-2.0 |
def json_escape(s)
result = s.to_s.gsub(JSON_ESCAPE_REGEXP, JSON_ESCAPE)
s.html_safe? ? result.html_safe : result
end | A utility method for escaping HTML entities in JSON strings. Specifically, the
&, > and < characters are replaced with their equivalent unicode escaped form -
\u0026, \u003e, and \u003c. The Unicode sequences \u2028 and \u2029 are also
escaped as they are treated as newline characters in some JavaScript engines.
These sequences have identical meaning as the original characters inside the
context of a JSON string, so assuming the input is a valid and well-formed
JSON value, the output will have equivalent meaning when parsed:
json = JSON.generate({ name: "</script><script>alert('PWNED!!!')</script>"})
# => "{\"name\":\"</script><script>alert('PWNED!!!')</script>\"}"
json_escape(json)
# => "{\"name\":\"\\u003C/script\\u003E\\u003Cscript\\u003Ealert('PWNED!!!')\\u003C/script\\u003E\"}"
JSON.parse(json) == JSON.parse(json_escape(json))
# => true
The intended use case for this method is to escape JSON strings before including
them inside a script tag to avoid XSS vulnerability:
<script>
var currentUser = <%= raw json_escape(current_user.to_json) %>;
</script>
It is necessary to +raw+ the result of +json_escape+, so that quotation marks
don't get converted to <tt>"</tt> entities. +json_escape+ doesn't
automatically flag the result as HTML safe, since the raw value is unsafe to
use inside HTML attributes.
If your JSON is being used downstream for insertion into the DOM, be aware of
whether or not it is being inserted via <tt>html()</tt>. Most jQuery plugins do this.
If that is the case, be sure to +html_escape+ or +sanitize+ any user-generated
content returned by your JSON.
If you need to output JSON elsewhere in your HTML, you can just do something
like this, as any unsafe characters (including quotation marks) will be
automatically escaped for you:
<div data-user-info="<%= current_user.to_json %>">...</div>
WARNING: this helper only works with valid JSON. Using this on non-JSON values
will open up serious XSS vulnerabilities. For example, if you replace the
+current_user.to_json+ in the example above with user input instead, the browser
will happily eval() that string as JavaScript.
The escaping performed in this method is identical to those performed in the
Active Support JSON encoder when +ActiveSupport.escape_html_entities_in_json+ is
set to true. Because this transformation is idempotent, this helper can be
applied even if +ActiveSupport.escape_html_entities_in_json+ is already true.
Therefore, when you are unsure if +ActiveSupport.escape_html_entities_in_json+
is enabled, or if you are unsure where your JSON string originated from, it
is recommended that you always apply this helper (other libraries, such as the
JSON gem, do not provide this kind of protection by default; also some gems
might override +to_json+ to bypass Active Support's encoder). | json_escape | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/output_safety.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/string/output_safety.rb | Apache-2.0 |
def xml_name_escape(name)
name = name.to_s
return "" if name.blank?
starting_char = name[0].gsub(TAG_NAME_START_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
return starting_char if name.size == 1
following_chars = name[1..-1].gsub(TAG_NAME_FOLLOWING_REGEXP, TAG_NAME_REPLACEMENT_CHAR)
starting_char + following_chars
end | A utility method for escaping XML names of tags and names of attributes.
xml_name_escape('1 < 2 & 3')
# => "1___2___3"
It follows the requirements of the specification: https://www.w3.org/TR/REC-xml/#NT-Name | xml_name_escape | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/output_safety.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/string/output_safety.rb | Apache-2.0 |
def strip_heredoc
gsub(/^#{scan(/^[ \t]*(?=\S)/).min}/, "").tap do |stripped|
stripped.freeze if frozen?
end
end | Strips indentation in heredocs.
For example in
if options[:usage]
puts <<-USAGE.strip_heredoc
This command does such and such.
Supported options are:
-h This message
...
USAGE
end
the user would see the usage message aligned against the left margin.
Technically, it looks for the least indented non-empty line
in the whole string, and removes that amount of leading whitespace. | strip_heredoc | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/strip.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/string/strip.rb | Apache-2.0 |
def in_time_zone(zone = ::Time.zone)
if zone
::Time.find_zone!(zone).parse(self)
else
to_time
end
end | Converts String to a TimeWithZone in the current zone if Time.zone or Time.zone_default
is set, otherwise converts String to a Time via String#to_time | in_time_zone | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/string/zones.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/string/zones.rb | Apache-2.0 |
def days_in_month(month, year = current.year)
if month == 2 && ::Date.gregorian_leap?(year)
29
else
COMMON_YEAR_DAYS_IN_MONTH[month]
end
end | Returns the number of days in the given month.
If no year is specified, it will use the current year. | days_in_month | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def days_in_year(year = current.year)
days_in_month(2, year) + 337
end | Returns the number of days in the given year.
If no year is specified, it will use the current year. | days_in_year | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def current
::Time.zone ? ::Time.zone.now : ::Time.now
end | Returns <tt>Time.zone.now</tt> when <tt>Time.zone</tt> or <tt>config.time_zone</tt> are set, otherwise just returns <tt>Time.now</tt>. | current | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def at_with_coercion(*args)
return at_without_coercion(*args) if args.size != 1
# Time.at can be called with a time or numerical value
time_or_number = args.first
if time_or_number.is_a?(ActiveSupport::TimeWithZone)
at_without_coercion(time_or_number.to_r).getlocal
elsif time_or_number.is_a?(DateTime)
at_without_coercion(time_or_number.to_f).getlocal
else
at_without_coercion(time_or_number)
end
end | Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
instances can be used when called with a single argument | at_with_coercion | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def rfc3339(str)
parts = Date._rfc3339(str)
raise ArgumentError, "invalid date" if parts.empty?
Time.new(
parts.fetch(:year),
parts.fetch(:mon),
parts.fetch(:mday),
parts.fetch(:hour),
parts.fetch(:min),
parts.fetch(:sec) + parts.fetch(:sec_fraction, 0),
parts.fetch(:offset)
)
end | Creates a +Time+ instance from an RFC 3339 string.
Time.rfc3339('1999-12-31T14:00:00-10:00') # => 2000-01-01 00:00:00 -1000
If the time or offset components are missing then an +ArgumentError+ will be raised.
Time.rfc3339('1999-12-31') # => ArgumentError: invalid date | rfc3339 | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def seconds_since_midnight
to_i - change(hour: 0).to_i + (usec / 1.0e+6)
end | Returns the number of seconds since 00:00:00.
Time.new(2012, 8, 29, 0, 0, 0).seconds_since_midnight # => 0.0
Time.new(2012, 8, 29, 12, 34, 56).seconds_since_midnight # => 45296.0
Time.new(2012, 8, 29, 23, 59, 59).seconds_since_midnight # => 86399.0 | seconds_since_midnight | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def seconds_until_end_of_day
end_of_day.to_i - to_i
end | Returns the number of seconds until 23:59:59.
Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399
Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103
Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 | seconds_until_end_of_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def change(options)
new_year = options.fetch(:year, year)
new_month = options.fetch(:month, month)
new_day = options.fetch(:day, day)
new_hour = options.fetch(:hour, hour)
new_min = options.fetch(:min, options[:hour] ? 0 : min)
new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec)
new_offset = options.fetch(:offset, nil)
if new_nsec = options[:nsec]
raise ArgumentError, "Can't change both :nsec and :usec at the same time: #{options.inspect}" if options[:usec]
new_usec = Rational(new_nsec, 1000)
else
new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000))
end
raise ArgumentError, "argument out of range" if new_usec >= 1000000
new_sec += Rational(new_usec, 1000000)
if new_offset
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, new_offset)
elsif utc?
::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec)
elsif zone&.respond_to?(:utc_to_local)
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, zone)
elsif zone
::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec)
else
::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec, utc_offset)
end
end | Returns a new Time 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>. Pass either <tt>:usec</tt> or <tt>:nsec</tt>, not both.
Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0)
Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0)
Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0) | change | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def advance(options)
unless options[:weeks].nil?
options[:weeks], partial_weeks = options[:weeks].divmod(1)
options[:days] = options.fetch(:days, 0) + 7 * partial_weeks
end
unless options[:days].nil?
options[:days], partial_days = options[:days].divmod(1)
options[:hours] = options.fetch(:hours, 0) + 24 * partial_days
end
d = to_date.gregorian.advance(options)
time_advanced_by_date = change(year: d.year, month: d.month, day: d.day)
seconds_to_advance = \
options.fetch(:seconds, 0) +
options.fetch(:minutes, 0) * 60 +
options.fetch(:hours, 0) * 3600
if seconds_to_advance.zero?
time_advanced_by_date
else
time_advanced_by_date.since(seconds_to_advance)
end
end | Uses Date to provide precise Time calculations for years, months, and days
according to the proleptic Gregorian calendar. 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>.
Time.new(2015, 8, 1, 14, 35, 0).advance(seconds: 1) # => 2015-08-01 14:35:01 -0700
Time.new(2015, 8, 1, 14, 35, 0).advance(minutes: 1) # => 2015-08-01 14:36:00 -0700
Time.new(2015, 8, 1, 14, 35, 0).advance(hours: 1) # => 2015-08-01 15:35:00 -0700
Time.new(2015, 8, 1, 14, 35, 0).advance(days: 1) # => 2015-08-02 14:35:00 -0700
Time.new(2015, 8, 1, 14, 35, 0).advance(weeks: 1) # => 2015-08-08 14:35:00 -0700 | advance | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def since(seconds)
self + seconds
rescue
to_datetime.since(seconds)
end | Returns a new Time representing the time a number of seconds since the instance time | since | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def beginning_of_day
change(hour: 0)
end | Returns a new Time representing the start of the day (0:00) | beginning_of_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def middle_of_day
change(hour: 12)
end | Returns a new Time representing the middle of the day (12:00) | middle_of_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def end_of_day
change(
hour: 23,
min: 59,
sec: 59,
usec: Rational(999999999, 1000)
)
end | Returns a new Time representing the end of the day, 23:59:59.999999 | end_of_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def beginning_of_hour
change(min: 0)
end | Returns a new Time representing the start of the hour (x:00) | beginning_of_hour | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def end_of_hour
change(
min: 59,
sec: 59,
usec: Rational(999999999, 1000)
)
end | Returns a new Time representing the end of the hour, x:59:59.999999 | end_of_hour | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def beginning_of_minute
change(sec: 0)
end | Returns a new Time representing the start of the minute (x:xx:00) | beginning_of_minute | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def end_of_minute
change(
sec: 59,
usec: Rational(999999999, 1000)
)
end | Returns a new Time representing the end of the minute, x:xx:59.999999 | end_of_minute | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def minus_with_coercion(other)
other = other.comparable_time if other.respond_to?(:comparable_time)
other.is_a?(DateTime) ? to_f - other.to_f : minus_without_coercion(other)
end | Time#- can also be used to determine the number of seconds between two Time instances.
We're layering on additional behavior so that ActiveSupport::TimeWithZone instances
are coerced into values that Time#- will recognize | minus_with_coercion | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def compare_with_coercion(other)
# we're avoiding Time#to_datetime and Time#to_time because they're expensive
if other.class == Time
compare_without_coercion(other)
elsif other.is_a?(Time)
compare_without_coercion(other.to_time)
else
to_datetime <=> other
end
end | Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances
can be chronologically compared with a Time | compare_with_coercion | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def eql_with_coercion(other)
# if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do eql? comparison
other = other.comparable_time if other.respond_to?(:comparable_time)
eql_without_coercion(other)
end | Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances
can be eql? to an equivalent Time | eql_with_coercion | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def prev_day(days = 1)
advance(days: -days)
end | Returns a new time the specified number of days ago. | prev_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def next_day(days = 1)
advance(days: days)
end | Returns a new time the specified number of days in the future. | next_day | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def prev_month(months = 1)
advance(months: -months)
end | Returns a new time the specified number of months ago. | prev_month | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def next_month(months = 1)
advance(months: months)
end | Returns a new time the specified number of months in the future. | next_month | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def prev_year(years = 1)
advance(years: -years)
end | Returns a new time the specified number of years ago. | prev_year | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def next_year(years = 1)
advance(years: years)
end | Returns a new time the specified number of years in the future. | next_year | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/calculations.rb | Apache-2.0 |
def to_time
preserve_timezone ? self : getlocal
end | Either return +self+ or the time 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/core_ext/time/compatibility.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/time/compatibility.rb | Apache-2.0 |
def to_formatted_s(format = :default)
if formatter = DATE_FORMATS[format]
formatter.respond_to?(:call) ? formatter.call(self).to_s : strftime(formatter)
else
to_default_s
end
end | Converts to a formatted string. See DATE_FORMATS for built-in formats.
This method is aliased to <tt>to_s</tt>.
time = Time.now # => 2007-01-18 06:10:17 -06:00
time.to_formatted_s(:time) # => "06:10"
time.to_s(:time) # => "06:10"
time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
time.to_formatted_s(:number) # => "20070118061017"
time.to_formatted_s(:short) # => "18 Jan 06:10"
time.to_formatted_s(:long) # => "January 18, 2007 06:10"
time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"
time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600"
time.to_formatted_s(:iso8601) # => "2007-01-18T06:10:17-06:00"
== Adding your own time formats to +to_formatted_s+
You can add your own formats to the Time::DATE_FORMATS hash.
Use the format name as the hash key and either a strftime string
or Proc instance that takes a time argument as the value.
# config/initializers/time_formats.rb
Time::DATE_FORMATS[:month_and_year] = '%B %Y'
Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.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/time/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/time/conversions.rb | Apache-2.0 |
def formatted_offset(colon = true, alternate_utc_string = nil)
utc? && alternate_utc_string || ActiveSupport::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.local(2000).formatted_offset # => "-06:00"
Time.local(2000).formatted_offset(false) # => "-0600" | formatted_offset | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/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/time/conversions.rb | Apache-2.0 |
def zone
Thread.current[:time_zone] || zone_default
end | Returns the TimeZone for the current request, if this has been set (via Time.zone=).
If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>. | zone | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/zones.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/time/zones.rb | Apache-2.0 |
def use_zone(time_zone)
new_zone = find_zone!(time_zone)
begin
old_zone, ::Time.zone = ::Time.zone, new_zone
yield
ensure
::Time.zone = old_zone
end
end | Allows override of <tt>Time.zone</tt> locally inside supplied block;
resets <tt>Time.zone</tt> to existing value when done.
class ApplicationController < ActionController::Base
around_action :set_time_zone
private
def set_time_zone
Time.use_zone(current_user.timezone) { yield }
end
end
NOTE: This won't affect any <tt>ActiveSupport::TimeWithZone</tt>
objects that have already been created, e.g. any model timestamp
attributes that have been read before the block will remain in
the application's default timezone. | use_zone | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/zones.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/time/zones.rb | Apache-2.0 |
def find_zone!(time_zone)
if !time_zone || time_zone.is_a?(ActiveSupport::TimeZone)
time_zone
else
# Look up the timezone based on the identifier (unless we've been
# passed a TZInfo::Timezone)
unless time_zone.respond_to?(:period_for_local)
time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone)
end
# Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone
if time_zone.is_a?(ActiveSupport::TimeZone)
time_zone
else
ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone)
end
end
rescue TZInfo::InvalidTimezoneIdentifier
raise ArgumentError, "Invalid Timezone: #{time_zone}"
end | Returns a TimeZone instance matching the time zone provided.
Accepts the time zone in any format supported by <tt>Time.zone=</tt>.
Raises an +ArgumentError+ for invalid time zones.
Time.find_zone! "America/New_York" # => #<ActiveSupport::TimeZone @name="America/New_York" ...>
Time.find_zone! "EST" # => #<ActiveSupport::TimeZone @name="EST" ...>
Time.find_zone! -5.hours # => #<ActiveSupport::TimeZone @name="Bogota" ...>
Time.find_zone! nil # => nil
Time.find_zone! false # => false
Time.find_zone! "NOT-A-TIMEZONE" # => ArgumentError: Invalid Timezone: NOT-A-TIMEZONE | find_zone! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/zones.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/time/zones.rb | Apache-2.0 |
def find_zone(time_zone)
find_zone!(time_zone) rescue nil
end | Returns a TimeZone instance matching the time zone provided.
Accepts the time zone in any format supported by <tt>Time.zone=</tt>.
Returns +nil+ for invalid time zones.
Time.find_zone "America/New_York" # => #<ActiveSupport::TimeZone @name="America/New_York" ...>
Time.find_zone "NOT-A-TIMEZONE" # => nil | find_zone | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/core_ext/time/zones.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/time/zones.rb | Apache-2.0 |
def behavior
@behavior ||= [DEFAULT_BEHAVIORS[:stderr]]
end | Returns the current behavior or if one isn't set, defaults to +:stderr+. | behavior | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/behaviors.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/behaviors.rb | Apache-2.0 |
def disallowed_behavior
@disallowed_behavior ||= [DEFAULT_BEHAVIORS[:raise]]
end | Returns the current behavior for disallowed deprecations or if one isn't set, defaults to +:raise+. | disallowed_behavior | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/behaviors.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/behaviors.rb | Apache-2.0 |
def disallowed_warnings
@disallowed_warnings ||= []
end | Returns the configured criteria used to identify deprecation messages
which should be treated as disallowed. | disallowed_warnings | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/disallowed.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/disallowed.rb | Apache-2.0 |
def deprecate_methods(target_module, *method_names)
options = method_names.extract_options!
deprecator = options.delete(:deprecator) || self
method_names += options.keys
mod = nil
method_names.each do |method_name|
message = options[method_name]
if target_module.method_defined?(method_name) || target_module.private_method_defined?(method_name)
method = target_module.instance_method(method_name)
target_module.module_eval do
redefine_method(method_name) do |*args, &block|
deprecator.deprecation_warning(method_name, message)
method.bind(self).call(*args, &block)
end
ruby2_keywords(method_name) if respond_to?(:ruby2_keywords, true)
end
else
mod ||= Module.new
mod.module_eval do
define_method(method_name) do |*args, &block|
deprecator.deprecation_warning(method_name, message)
super(*args, &block)
end
ruby2_keywords(method_name) if respond_to?(:ruby2_keywords, true)
end
end
end
target_module.prepend(mod) if mod
end | Declare that a method has been deprecated.
class Fred
def aaa; end
def bbb; end
def ccc; end
def ddd; end
def eee; end
end
Using the default deprecator:
ActiveSupport::Deprecation.deprecate_methods(Fred, :aaa, bbb: :zzz, ccc: 'use Bar#ccc instead')
# => Fred
Fred.new.aaa
# DEPRECATION WARNING: aaa is deprecated and will be removed from Rails 5.1. (called from irb_binding at (irb):10)
# => nil
Fred.new.bbb
# DEPRECATION WARNING: bbb is deprecated and will be removed from Rails 5.1 (use zzz instead). (called from irb_binding at (irb):11)
# => nil
Fred.new.ccc
# DEPRECATION WARNING: ccc is deprecated and will be removed from Rails 5.1 (use Bar#ccc instead). (called from irb_binding at (irb):12)
# => nil
Passing in a custom deprecator:
custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem')
ActiveSupport::Deprecation.deprecate_methods(Fred, ddd: :zzz, deprecator: custom_deprecator)
# => [:ddd]
Fred.new.ddd
DEPRECATION WARNING: ddd is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):15)
# => nil
Using a custom deprecator directly:
custom_deprecator = ActiveSupport::Deprecation.new('next-release', 'MyGem')
custom_deprecator.deprecate_methods(Fred, eee: :zzz)
# => [:eee]
Fred.new.eee
DEPRECATION WARNING: eee is deprecated and will be removed from MyGem next-release (use zzz instead). (called from irb_binding at (irb):18)
# => nil | deprecate_methods | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/method_wrappers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/method_wrappers.rb | Apache-2.0 |
def warn(message = nil, callstack = nil)
return if silenced
callstack ||= caller_locations(2)
deprecation_message(callstack, message).tap do |m|
if deprecation_disallowed?(message)
disallowed_behavior.each { |b| b.call(m, callstack, deprecation_horizon, gem_name) }
else
behavior.each { |b| b.call(m, callstack, deprecation_horizon, gem_name) }
end
end
end | Outputs a deprecation warning to the output configured by
<tt>ActiveSupport::Deprecation.behavior</tt>.
ActiveSupport::Deprecation.warn('something broke!')
# => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)" | warn | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | Apache-2.0 |
def silence(&block)
@silenced_thread.bind(true, &block)
end | Silence deprecation warnings within the block.
ActiveSupport::Deprecation.warn('something broke!')
# => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"
ActiveSupport::Deprecation.silence do
ActiveSupport::Deprecation.warn('something broke!')
end
# => nil | silence | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | Apache-2.0 |
def allow(allowed_warnings = :all, if: true, &block)
conditional = binding.local_variable_get(:if)
conditional = conditional.call if conditional.respond_to?(:call)
if conditional
@explicitly_allowed_warnings.bind(allowed_warnings, &block)
else
yield
end
end | Allow previously disallowed deprecation warnings within the block.
<tt>allowed_warnings</tt> can be an array containing strings, symbols, or regular
expressions. (Symbols are treated as strings). These are compared against
the text of deprecation warning messages generated within the block.
Matching warnings will be exempt from the rules set by
+ActiveSupport::Deprecation.disallowed_warnings+
The optional <tt>if:</tt> argument accepts a truthy/falsy value or an object that
responds to <tt>.call</tt>. If truthy, then matching warnings will be allowed.
If falsey then the method yields to the block without allowing the warning.
ActiveSupport::Deprecation.disallowed_behavior = :raise
ActiveSupport::Deprecation.disallowed_warnings = [
"something broke"
]
ActiveSupport::Deprecation.warn('something broke!')
# => ActiveSupport::DeprecationException
ActiveSupport::Deprecation.allow ['something broke'] do
ActiveSupport::Deprecation.warn('something broke!')
end
# => nil
ActiveSupport::Deprecation.allow ['something broke'], if: Rails.env.production? do
ActiveSupport::Deprecation.warn('something broke!')
end
# => ActiveSupport::DeprecationException for dev/test, nil for production | allow | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | Apache-2.0 |
def deprecated_method_warning(method_name, message = nil)
warning = "#{method_name} is deprecated and will be removed from #{gem_name} #{deprecation_horizon}"
case message
when Symbol then "#{warning} (use #{message} instead)"
when String then "#{warning} (#{message})"
else warning
end
end | Outputs a deprecation warning message
deprecated_method_warning(:method_name)
# => "method_name is deprecated and will be removed from Rails #{deprecation_horizon}"
deprecated_method_warning(:method_name, :another_method)
# => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (use another_method instead)"
deprecated_method_warning(:method_name, "Optional message")
# => "method_name is deprecated and will be removed from Rails #{deprecation_horizon} (Optional message)" | deprecated_method_warning | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/deprecation/reporting.rb | Apache-2.0 |
def number
PERIOD_OR_COMMA.match?(scanner[1]) ? scanner[1].tr(COMMA, PERIOD).to_f : scanner[1].to_i
end | Parses number which can be a float with either comma or period. | number | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_parser.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_parser.rb | Apache-2.0 |
def validate!
raise_parsing_error("is empty duration") if parts.empty?
# Mixing any of Y, M, D with W is invalid.
if parts.key?(:weeks) && (parts.keys & DATE_COMPONENTS).any?
raise_parsing_error("mixing weeks with other date parts not allowed")
end
# Specifying an empty T part is invalid.
if mode == :time && (parts.keys & TIME_COMPONENTS).empty?
raise_parsing_error("time part marker is present but time part is empty")
end
fractions = parts.values.reject(&:zero?).select { |a| (a % 1) != 0 }
unless fractions.empty? || (fractions.size == 1 && fractions.last == @parts.values.reject(&:zero?).last)
raise_parsing_error "(only last part can be fractional)"
end
true
end | Checks for various semantic errors as stated in ISO 8601 standard. | validate! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_parser.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_parser.rb | Apache-2.0 |
def normalize
parts = @duration.parts.each_with_object(Hash.new(0)) do |(k, v), p|
p[k] += v unless v.zero?
end
# Convert weeks to days and remove weeks if mixed with date parts
if week_mixed_with_date?(parts)
parts[:days] += parts.delete(:weeks) * SECONDS_PER_WEEK / SECONDS_PER_DAY
end
parts
end | Return pair of duration's parts and whole duration sign.
Parts are summarized (as they can become repetitive due to addition, etc).
Zero parts are removed as not significant.
If all parts are negative it will negate all of them and return minus as a sign. | normalize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_serializer.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/duration/iso8601_serializer.rb | Apache-2.0 |
def plural(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@plurals.prepend([rule, replacement])
end | Specifies a new pluralization rule and its replacement. The rule can
either be a string or a regular expression. The replacement should
always be a string that may include references to the matched data from
the rule. | plural | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def singular(rule, replacement)
@uncountables.delete(rule) if rule.is_a?(String)
@uncountables.delete(replacement)
@singulars.prepend([rule, replacement])
end | Specifies a new singularization rule and its replacement. The rule can
either be a string or a regular expression. The replacement should
always be a string that may include references to the matched data from
the rule. | singular | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def irregular(singular, plural)
@uncountables.delete(singular)
@uncountables.delete(plural)
s0 = singular[0]
srest = singular[1..-1]
p0 = plural[0]
prest = plural[1..-1]
if s0.upcase == p0.upcase
plural(/(#{s0})#{srest}$/i, '\1' + prest)
plural(/(#{p0})#{prest}$/i, '\1' + prest)
singular(/(#{s0})#{srest}$/i, '\1' + srest)
singular(/(#{p0})#{prest}$/i, '\1' + srest)
else
plural(/#{s0.upcase}(?i)#{srest}$/, p0.upcase + prest)
plural(/#{s0.downcase}(?i)#{srest}$/, p0.downcase + prest)
plural(/#{p0.upcase}(?i)#{prest}$/, p0.upcase + prest)
plural(/#{p0.downcase}(?i)#{prest}$/, p0.downcase + prest)
singular(/#{s0.upcase}(?i)#{srest}$/, s0.upcase + srest)
singular(/#{s0.downcase}(?i)#{srest}$/, s0.downcase + srest)
singular(/#{p0.upcase}(?i)#{prest}$/, s0.upcase + srest)
singular(/#{p0.downcase}(?i)#{prest}$/, s0.downcase + srest)
end
end | Specifies a new irregular that applies to both pluralization and
singularization at the same time. This can only be used for strings, not
regular expressions. You simply pass the irregular in singular and
plural form.
irregular 'octopus', 'octopi'
irregular 'person', 'people' | irregular | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def human(rule, replacement)
@humans.prepend([rule, replacement])
end | Specifies a humanized form of a string by a regular expression rule or
by a string mapping. When using a regular expression based replacement,
the normal humanize formatting is called after the replacement. When a
string is used, the human form should be specified as desired (example:
'The name', not 'the_name').
human /_cnt$/i, '\1_count'
human 'legacy_col_person_name', 'Name' | human | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def clear(scope = :all)
case scope
when :all
@plurals, @singulars, @uncountables, @humans = [], [], Uncountables.new, []
else
instance_variable_set "@#{scope}", []
end
end | Clears the loaded inflections within a given scope (default is
<tt>:all</tt>). Give the scope as a symbol of the inflection type, the
options are: <tt>:plurals</tt>, <tt>:singulars</tt>, <tt>:uncountables</tt>,
<tt>:humans</tt>.
clear :all
clear :plurals | clear | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def inflections(locale = :en)
if block_given?
yield Inflections.instance(locale)
else
Inflections.instance(locale)
end
end | Yields a singleton instance of Inflector::Inflections so you can specify
additional inflector rules. If passed an optional locale, rules for other
languages can be specified. If not specified, defaults to <tt>:en</tt>.
Only rules for English are provided.
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.uncountable 'rails'
end | inflections | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/inflections.rb | Apache-2.0 |
def pluralize(word, locale = :en)
apply_inflections(word, inflections(locale).plurals, locale)
end | Returns the plural form of the word in the string.
If passed an optional +locale+ parameter, the word will be
pluralized using rules defined for that language. By default,
this parameter is set to <tt>:en</tt>.
pluralize('post') # => "posts"
pluralize('octopus') # => "octopi"
pluralize('sheep') # => "sheep"
pluralize('words') # => "words"
pluralize('CamelOctopus') # => "CamelOctopi"
pluralize('ley', :es) # => "leyes" | pluralize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/methods.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/inflector/methods.rb | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.