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 singularize(word, locale = :en)
apply_inflections(word, inflections(locale).singulars, locale)
end | The reverse of #pluralize, returns the singular form of a word in a
string.
If passed an optional +locale+ parameter, the word will be
singularized using rules defined for that language. By default,
this parameter is set to <tt>:en</tt>.
singularize('posts') # => "post"
singularize('octopi') # => "octopus"
singularize('sheep') # => "sheep"
singularize('word') # => "word"
singularize('CamelOctopi') # => "CamelOctopus"
singularize('leyes', :es) # => "ley" | singularize | 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 |
def camelize(term, uppercase_first_letter = true)
string = term.to_s
if uppercase_first_letter
string = string.sub(/^[a-z\d]*/) { |match| inflections.acronyms[match] || match.capitalize }
else
string = string.sub(inflections.acronyms_camelize_regex) { |match| match.downcase }
end
string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" }
string.gsub!("/", "::")
string
end | Converts strings to UpperCamelCase.
If the +uppercase_first_letter+ parameter is set to false, then produces
lowerCamelCase.
Also converts '/' to '::' which is useful for converting
paths to namespaces.
camelize('active_model') # => "ActiveModel"
camelize('active_model', false) # => "activeModel"
camelize('active_model/errors') # => "ActiveModel::Errors"
camelize('active_model/errors', false) # => "activeModel::Errors"
As a rule of thumb you can think of +camelize+ as the inverse of
#underscore, though there are cases where that does not hold:
camelize(underscore('SSLError')) # => "SslError" | camelize | 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 |
def underscore(camel_cased_word)
return camel_cased_word unless /[A-Z-]|::/.match?(camel_cased_word)
word = camel_cased_word.to_s.gsub("::", "/")
word.gsub!(inflections.acronyms_underscore_regex) { "#{$1 && '_' }#{$2.downcase}" }
word.gsub!(/([A-Z])(?=[A-Z][a-z])|([a-z\d])(?=[A-Z])/) { ($1 || $2) << "_" }
word.tr!("-", "_")
word.downcase!
word
end | Makes an underscored, lowercase form from the expression in the string.
Changes '::' to '/' to convert namespaces to paths.
underscore('ActiveModel') # => "active_model"
underscore('ActiveModel::Errors') # => "active_model/errors"
As a rule of thumb you can think of +underscore+ as the inverse of
#camelize, though there are cases where that does not hold:
camelize(underscore('SSLError')) # => "SslError" | underscore | 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 |
def humanize(lower_case_and_underscored_word, capitalize: true, keep_id_suffix: false)
result = lower_case_and_underscored_word.to_s.dup
inflections.humans.each { |(rule, replacement)| break if result.sub!(rule, replacement) }
result.sub!(/\A_+/, "")
unless keep_id_suffix
result.delete_suffix!("_id")
end
result.tr!("_", " ")
result.gsub!(/([a-z\d]*)/i) do |match|
"#{inflections.acronyms[match.downcase] || match.downcase}"
end
if capitalize
result.sub!(/\A\w/) { |match| match.upcase }
end
result
end | Tweaks an attribute name for display to end users.
Specifically, performs these transformations:
* Applies human inflection rules to the argument.
* Deletes leading underscores, if any.
* Removes a "_id" suffix if present.
* Replaces underscores with spaces, if any.
* Downcases all words except acronyms.
* Capitalizes the first word.
The capitalization of the first word can be turned off by setting the
+:capitalize+ option to false (default is true).
The trailing '_id' can be kept and capitalized by setting the
optional parameter +keep_id_suffix+ to true (default is false).
humanize('employee_salary') # => "Employee salary"
humanize('author_id') # => "Author"
humanize('author_id', capitalize: false) # => "author"
humanize('_id') # => "Id"
humanize('author_id', keep_id_suffix: true) # => "Author Id"
If "SSL" was defined to be an acronym:
humanize('ssl_error') # => "SSL error" | humanize | 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 |
def upcase_first(string)
string.length > 0 ? string[0].upcase.concat(string[1..-1]) : ""
end | Converts just the first character to uppercase.
upcase_first('what a Lovely Day') # => "What a Lovely Day"
upcase_first('w') # => "W"
upcase_first('') # => "" | upcase_first | 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 |
def decode(json)
data = ::JSON.parse(json, quirks_mode: true)
if ActiveSupport.parse_json_times
convert_dates_from(data)
else
data
end
end | Parses a JSON string (JavaScript Object Notation) into a hash.
See http://www.json.org for more info.
ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}")
=> {"team" => "rails", "players" => "36"} | decode | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/decoding.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/decoding.rb | Apache-2.0 |
def encode(value)
stringify jsonify value.as_json(options.dup)
end | Encode the given object into a JSON string | encode | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/encoding.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/encoding.rb | Apache-2.0 |
def stringify(jsonified)
::JSON.generate(jsonified, quirks_mode: true, max_nesting: false)
end | Encode a "jsonified" Ruby data structure using the JSON gem | stringify | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/encoding.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/json/encoding.rb | Apache-2.0 |
def set_logger(logger)
ActiveSupport::LogSubscriber.logger = logger
end | Overwrite if you use another logger in your log subscriber.
def logger
ActiveRecord::Base.logger = @logger
end | set_logger | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/log_subscriber/test_helper.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/log_subscriber/test_helper.rb | Apache-2.0 |
def initialize(string)
@wrapped_string = string
@wrapped_string.force_encoding(Encoding::UTF_8) unless @wrapped_string.frozen?
end | Creates a new Chars instance by wrapping _string_. | initialize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | Apache-2.0 |
def method_missing(method, *args, &block)
result = @wrapped_string.__send__(method, *args, &block)
if method.end_with?("!")
self if result
else
result.kind_of?(String) ? chars(result) : result
end
end | Forward all undefined methods to the wrapped string. | method_missing | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | Apache-2.0 |
def respond_to_missing?(method, include_private)
@wrapped_string.respond_to?(method, include_private)
end | Returns +true+ if _obj_ responds to the given method. Private methods
are included in the search only if the optional second parameter
evaluates to +true+. | respond_to_missing? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/chars.rb | Apache-2.0 |
def decompose(type, codepoints)
if type == :compatibility
codepoints.pack("U*").unicode_normalize(:nfkd).codepoints
else
codepoints.pack("U*").unicode_normalize(:nfd).codepoints
end
end | Decompose composed characters to the decomposed form. | decompose | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/unicode.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/unicode.rb | Apache-2.0 |
def tidy_bytes(string, force = false)
return string if string.empty? || string.ascii_only?
return recode_windows1252_chars(string) if force
string.scrub { |bad| recode_windows1252_chars(bad) }
end | Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent
resulting in a valid UTF-8 string.
Passing +true+ will forcibly tidy all bytes, assuming that the string's
encoding is entirely CP1252 or ISO-8859-1. | tidy_bytes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/unicode.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/multibyte/unicode.rb | Apache-2.0 |
def instrument(name, payload = {})
# some of the listeners might have state
listeners_state = start name, payload
begin
yield payload if block_given?
rescue Exception => e
payload[:exception] = [e.class.name, e.message]
payload[:exception_object] = e
raise e
ensure
finish_with_state listeners_state, name, payload
end
end | Given a block, instrument it by measuring the time taken to execute
and publish it. Without a block, simply send a message via the
notifier. Notice that events get sent even if an error occurs in the
passed-in block. | instrument | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def start(name, payload)
@notifier.start name, @id, payload
end | Send a start notification with +name+ and +payload+. | start | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def finish(name, payload)
@notifier.finish name, @id, payload
end | Send a finish notification with +name+ and +payload+. | finish | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def start!
@time = now
@cpu_time_start = now_cpu
@allocation_count_start = now_allocations
end | Record information at the time this event starts | start! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def finish!
@cpu_time_finish = now_cpu
@end = now
@allocation_count_finish = now_allocations
end | Record information at the time this event finishes | finish! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def cpu_time
(@cpu_time_finish - @cpu_time_start) * 1000
end | Returns the CPU time (in milliseconds) passed since the call to
+start!+ and the call to +finish!+ | cpu_time | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def idle_time
duration - cpu_time
end | Returns the idle time time (in milliseconds) passed since the call to
+start!+ and the call to +finish!+ | idle_time | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def allocations
@allocation_count_finish - @allocation_count_start
end | Returns the number of allocations made since the call to +start!+ and
the call to +finish!+ | allocations | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def duration
1000.0 * (self.end - time)
end | Returns the difference in milliseconds between when the execution of the
event started and when it ended.
ActiveSupport::Notifications.subscribe('wait') do |*args|
@event = ActiveSupport::Notifications::Event.new(*args)
end
ActiveSupport::Notifications.instrument('wait') do
sleep 1
end
@event.duration # => 1000.138 | duration | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/notifications/instrumenter.rb | Apache-2.0 |
def assert_not(object, message = nil)
message ||= "Expected #{mu_pp(object)} to be nil or false"
assert !object, message
end | Asserts that an expression is not truthy. Passes if <tt>object</tt> is
+nil+ or +false+. "Truthy" means "considered true in a conditional"
like <tt>if foo</tt>.
assert_not nil # => true
assert_not false # => true
assert_not 'foo' # => Expected "foo" to be nil or false
An error message can be specified.
assert_not foo, 'foo should be false' | assert_not | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def assert_nothing_raised
yield
rescue => error
raise Minitest::UnexpectedError.new(error)
end | Assertion that the block should not raise an exception.
Passes if evaluated code in the yielded block raises no exception.
assert_nothing_raised do
perform_service(param: 'no_exception')
end | assert_nothing_raised | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def assert_difference(expression, *args, &block)
expressions =
if expression.is_a?(Hash)
message = args[0]
expression
else
difference = args[0] || 1
message = args[1]
Array(expression).index_with(difference)
end
exps = expressions.keys.map { |e|
e.respond_to?(:call) ? e : lambda { eval(e, block.binding) }
}
before = exps.map(&:call)
retval = assert_nothing_raised(&block)
expressions.zip(exps, before) do |(code, diff), exp, before_value|
error = "#{code.inspect} didn't change by #{diff}"
error = "#{message}.\n#{error}" if message
assert_equal(before_value + diff, exp.call, error)
end
retval
end | Test numeric difference between the return value of an expression as a
result of what is evaluated in the yielded block.
assert_difference 'Article.count' do
post :create, params: { article: {...} }
end
An arbitrary expression is passed in and evaluated.
assert_difference 'Article.last.comments(:reload).size' do
post :create, params: { comment: {...} }
end
An arbitrary positive or negative difference can be specified.
The default is <tt>1</tt>.
assert_difference 'Article.count', -1 do
post :delete, params: { id: ... }
end
An array of expressions can also be passed in and evaluated.
assert_difference [ 'Article.count', 'Post.count' ], 2 do
post :create, params: { article: {...} }
end
A hash of expressions/numeric differences can also be passed in and evaluated.
assert_difference ->{ Article.count } => 1, ->{ Notification.count } => 2 do
post :create, params: { article: {...} }
end
A lambda or a list of lambdas can be passed in and evaluated:
assert_difference ->{ Article.count }, 2 do
post :create, params: { article: {...} }
end
assert_difference [->{ Article.count }, ->{ Post.count }], 2 do
post :create, params: { article: {...} }
end
An error message can be specified.
assert_difference 'Article.count', -1, 'An Article should be destroyed' do
post :delete, params: { id: ... }
end | assert_difference | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def assert_no_difference(expression, message = nil, &block)
assert_difference expression, 0, message, &block
end | Assertion that the numeric result of evaluating an expression is not
changed before and after invoking the passed in block.
assert_no_difference 'Article.count' do
post :create, params: { article: invalid_attributes }
end
A lambda can be passed in and evaluated.
assert_no_difference -> { Article.count } do
post :create, params: { article: invalid_attributes }
end
An error message can be specified.
assert_no_difference 'Article.count', 'An Article should not be created' do
post :create, params: { article: invalid_attributes }
end
An array of expressions can also be passed in and evaluated.
assert_no_difference [ 'Article.count', -> { Post.count } ] do
post :create, params: { article: invalid_attributes }
end | assert_no_difference | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def assert_changes(expression, message = nil, from: UNTRACKED, to: UNTRACKED, &block)
exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) }
before = exp.call
retval = assert_nothing_raised(&block)
unless from == UNTRACKED
error = "Expected change from #{from.inspect}"
error = "#{message}.\n#{error}" if message
assert from === before, error
end
after = exp.call
error = "#{expression.inspect} didn't change"
error = "#{error}. It was already #{to}" if before == to
error = "#{message}.\n#{error}" if message
refute_equal before, after, error
unless to == UNTRACKED
error = "Expected change to #{to}\n"
error = "#{message}.\n#{error}" if message
assert to === after, error
end
retval
end | Assertion that the result of evaluating an expression is changed before
and after invoking the passed in block.
assert_changes 'Status.all_good?' do
post :create, params: { status: { ok: false } }
end
You can pass the block as a string to be evaluated in the context of
the block. A lambda can be passed for the block as well.
assert_changes -> { Status.all_good? } do
post :create, params: { status: { ok: false } }
end
The assertion is useful to test side effects. The passed block can be
anything that can be converted to string with #to_s.
assert_changes :@object do
@object = 42
end
The keyword arguments :from and :to can be given to specify the
expected initial value and the expected value after the block was
executed.
assert_changes :@object, from: nil, to: :foo do
@object = :foo
end
An error message can be specified.
assert_changes -> { Status.all_good? }, 'Expected the status to be bad' do
post :create, params: { status: { incident: true } }
end | assert_changes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def assert_no_changes(expression, message = nil, &block)
exp = expression.respond_to?(:call) ? expression : -> { eval(expression.to_s, block.binding) }
before = exp.call
retval = assert_nothing_raised(&block)
after = exp.call
error = "#{expression.inspect} changed"
error = "#{message}.\n#{error}" if message
if before.nil?
assert_nil after, error
else
assert_equal before, after, error
end
retval
end | Assertion that the result of evaluating an expression is not changed before
and after invoking the passed in block.
assert_no_changes 'Status.all_good?' do
post :create, params: { status: { ok: true } }
end
An error message can be specified.
assert_no_changes -> { Status.all_good? }, 'Expected the status to be good' do
post :create, params: { status: { ok: false } }
end | assert_no_changes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/assertions.rb | Apache-2.0 |
def test(name, &block)
test_name = "test_#{name.gsub(/\s+/, '_')}".to_sym
defined = method_defined? test_name
raise "#{test_name} is already defined in #{self}" if defined
if block_given?
define_method(test_name, &block)
else
define_method(test_name) do
flunk "No implementation provided for #{name}"
end
end
end | Helper to define a test method using a String. Under the hood, it replaces
spaces with underscores and defines the test method.
test "verify something" do
...
end | test | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/declarative.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/declarative.rb | Apache-2.0 |
def file_fixture(fixture_name)
path = Pathname.new(File.join(file_fixture_path, fixture_name))
if path.exist?
path
else
msg = "the directory '%s' does not contain a file named '%s'"
raise ArgumentError, msg % [file_fixture_path, fixture_name]
end
end | Returns a +Pathname+ to the fixture file named +fixture_name+.
Raises +ArgumentError+ if +fixture_name+ can't be found. | file_fixture | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/file_fixtures.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/file_fixtures.rb | Apache-2.0 |
def run_in_isolation(&blk)
require "tempfile"
if ENV["ISOLATION_TEST"]
yield
test_result = defined?(Minitest::Result) ? Minitest::Result.from(self) : dup
File.open(ENV["ISOLATION_OUTPUT"], "w") do |file|
file.puts [Marshal.dump(test_result)].pack("m")
end
exit!
else
Tempfile.open("isolation") do |tmpfile|
env = {
"ISOLATION_TEST" => self.class.name,
"ISOLATION_OUTPUT" => tmpfile.path
}
test_opts = "-n#{self.class.name}##{name}"
load_path_args = []
$-I.each do |p|
load_path_args << "-I"
load_path_args << File.expand_path(p)
end
child = IO.popen([env, Gem.ruby, *load_path_args, $0, *ORIG_ARGV, test_opts])
begin
Process.wait(child.pid)
rescue Errno::ECHILD # The child process may exit before we wait
nil
end
return tmpfile.read.unpack1("m")
end
end
end | Crazy H4X to get this working in windows / jruby with
no forking. | run_in_isolation | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/isolation.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/isolation.rb | Apache-2.0 |
def setup(*args, &block)
set_callback(:setup, :before, *args, &block)
end | Add a callback, which runs before <tt>TestCase#setup</tt>. | setup | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/setup_and_teardown.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/setup_and_teardown.rb | Apache-2.0 |
def teardown(*args, &block)
set_callback(:teardown, :after, *args, &block)
end | Add a callback, which runs after <tt>TestCase#teardown</tt>. | teardown | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/setup_and_teardown.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/setup_and_teardown.rb | Apache-2.0 |
def stub_object(object, method_name, &block)
if stub = stubbing(object, method_name)
unstub_object(stub)
end
new_name = "__simple_stub__#{method_name}"
@stubs[object.object_id][method_name] = Stub.new(object, method_name, new_name)
object.singleton_class.alias_method new_name, method_name
object.define_singleton_method(method_name, &block)
end | Stubs object.method_name with the given block
If the method is already stubbed, remove that stub
so that removing this stub will restore the original implementation.
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
target = Time.zone.local(2004, 11, 24, 1, 4, 44)
simple_stubs.stub_object(Time, :now) { at(target.to_i) }
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 | stub_object | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def unstub_all!
@stubs.each_value do |object_stubs|
object_stubs.each_value do |stub|
unstub_object(stub)
end
end
@stubs.clear
end | Remove all object-method stubs held by this instance | unstub_all! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def unstub_object(stub)
singleton_class = stub.object.singleton_class
singleton_class.silence_redefinition_of_method stub.method_name
singleton_class.alias_method stub.method_name, stub.original_method
singleton_class.undef_method stub.original_method
end | Restores the original object.method described by the Stub | unstub_object | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def travel(duration, &block)
travel_to Time.now + duration, &block
end | Changes current time to the time in the future or in the past by a given time difference by
stubbing +Time.now+, +Date.today+, and +DateTime.now+. The stubs are automatically removed
at the end of the test.
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel 1.day
Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00
Date.current # => Sun, 10 Nov 2013
DateTime.current # => Sun, 10 Nov 2013 15:34:49 -0500
This method also accepts a block, which will return the current time back to its original
state at the end of the block:
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel 1.day do
User.create.created_at # => Sun, 10 Nov 2013 15:34:49 EST -05:00
end
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 | travel | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def travel_to(date_or_time)
if block_given? && simple_stubs.stubbing(Time, :now)
travel_to_nested_block_call = <<~MSG
Calling `travel_to` with a block, when we have previously already made a call to `travel_to`, can lead to confusing time stubbing.
Instead of:
travel_to 2.days.from_now do
# 2 days from today
travel_to 3.days.from_now do
# 5 days from today
end
end
preferred way to achieve above is:
travel 2.days do
# 2 days from today
end
travel 5.days do
# 5 days from today
end
MSG
raise travel_to_nested_block_call
end
if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime)
now = date_or_time.midnight.to_time
else
now = date_or_time.to_time.change(usec: 0)
end
simple_stubs.stub_object(Time, :now) { at(now.to_i) }
simple_stubs.stub_object(Date, :today) { jd(now.to_date.jd) }
simple_stubs.stub_object(DateTime, :now) { jd(now.to_date.jd, now.hour, now.min, now.sec, Rational(now.utc_offset, 86400)) }
if block_given?
begin
yield
ensure
travel_back
end
end
end | Changes current time to the given time by stubbing +Time.now+,
+Date.today+, and +DateTime.now+ to return the time or date passed into this method.
The stubs are automatically removed at the end of the test.
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel_to Time.zone.local(2004, 11, 24, 1, 4, 44)
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
Date.current # => Wed, 24 Nov 2004
DateTime.current # => Wed, 24 Nov 2004 01:04:44 -0500
Dates are taken as their timestamp at the beginning of the day in the
application time zone. <tt>Time.current</tt> returns said timestamp,
and <tt>Time.now</tt> its equivalent in the system time zone. Similarly,
<tt>Date.current</tt> returns a date equal to the argument, and
<tt>Date.today</tt> the date according to <tt>Time.now</tt>, which may
be different. (Note that you rarely want to deal with <tt>Time.now</tt>,
or <tt>Date.today</tt>, in order to honor the application time zone
please always use <tt>Time.current</tt> and <tt>Date.current</tt>.)
Note that the usec for the time passed will be set to 0 to prevent rounding
errors with external services, like MySQL (which will round instead of floor,
leading to off-by-one-second errors).
This method also accepts a block, which will return the current time back to its original
state at the end of the block:
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel_to Time.zone.local(2004, 11, 24, 1, 4, 44) do
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
end
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 | travel_to | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def travel_back
stubbed_time = Time.current if block_given? && simple_stubs.stubbed?
simple_stubs.unstub_all!
yield if block_given?
ensure
travel_to stubbed_time if stubbed_time
end | Returns the current time back to its original state, by removing the stubs added by
+travel+, +travel_to+, and +freeze_time+.
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel_to Time.zone.local(2004, 11, 24, 1, 4, 44)
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
travel_back
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
This method also accepts a block, which brings the stubs back at the end of the block:
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
travel_to Time.zone.local(2004, 11, 24, 1, 4, 44)
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00
travel_back do
Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00
end
Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 | travel_back | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def freeze_time(&block)
travel_to Time.now, &block
end | Calls +travel_to+ with +Time.now+.
Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
freeze_time
sleep(1)
Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
This method also accepts a block, which will return the current time back to its original
state at the end of the block:
Time.current # => Sun, 09 Jul 2017 15:34:49 EST -05:00
freeze_time do
sleep(1)
User.create.created_at # => Sun, 09 Jul 2017 15:34:49 EST -05:00
end
Time.current # => Sun, 09 Jul 2017 15:34:50 EST -05:00 | freeze_time | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/testing/time_helpers.rb | Apache-2.0 |
def seconds_to_utc_offset(seconds, colon = true)
format = colon ? UTC_OFFSET_WITH_COLON : UTC_OFFSET_WITHOUT_COLON
sign = (seconds < 0 ? "-" : "+")
hours = seconds.abs / 3600
minutes = (seconds.abs % 3600) / 60
format % [sign, hours, minutes]
end | Assumes self represents an offset from UTC in seconds (as returned from
Time#utc_offset) and turns this into an +HH:MM formatted string.
ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00" | seconds_to_utc_offset | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def all
@zones ||= zones_map.values.sort
end | Returns an array of all TimeZone objects. There are multiple
TimeZone objects per time zone, in many cases, to make it easier
for users to find their own time zone. | all | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def country_zones(country_code)
code = country_code.to_s.upcase
@country_zones[code] ||= load_country_zones(code)
end | A convenience method for returning a collection of TimeZone objects
for time zones in the country specified by its ISO 3166-1 Alpha2 code. | country_zones | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def initialize(name, utc_offset = nil, tzinfo = nil)
@name = name
@utc_offset = utc_offset
@tzinfo = tzinfo || TimeZone.find_tzinfo(name)
end | Create a new TimeZone object with the given name and offset. The
offset is the number of seconds that this time zone is offset from UTC
(GMT). Seconds were chosen as the offset unit because that is the unit
that Ruby uses to represent time zone offsets (see Time#utc_offset). | initialize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def utc_offset
@utc_offset || tzinfo&.current_period&.base_utc_offset
end | Returns the offset of this time zone from UTC in seconds. | utc_offset | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def formatted_offset(colon = true, alternate_utc_string = nil)
utc_offset == 0 && alternate_utc_string || self.class.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.
zone = ActiveSupport::TimeZone['Central Time (US & Canada)']
zone.formatted_offset # => "-06:00"
zone.formatted_offset(false) # => "-0600" | formatted_offset | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def match?(re)
(re == name) || (re == MAPPING[name]) ||
((Regexp === re) && (re.match?(name) || re.match?(MAPPING[name])))
end | Compare #name and TZInfo identifier to a supplied regexp, returning +true+
if a match is found. | match? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def to_s
"(GMT#{formatted_offset}) #{name}"
end | Returns a textual representation of this time zone. | to_s | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def local(*args)
time = Time.utc(*args)
ActiveSupport::TimeWithZone.new(nil, self, time)
end | Method for creating new ActiveSupport::TimeWithZone instance in time zone
of +self+ from given values.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.local(2007, 2, 1, 15, 30, 45) # => Thu, 01 Feb 2007 15:30:45 HST -10:00 | local | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def iso8601(str)
raise ArgumentError, "invalid date" if str.nil?
parts = Date._iso8601(str)
raise ArgumentError, "invalid date" if parts.empty?
time = Time.new(
parts.fetch(:year),
parts.fetch(:mon),
parts.fetch(:mday),
parts.fetch(:hour, 0),
parts.fetch(:min, 0),
parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
parts.fetch(:offset, 0)
)
if parts[:offset]
TimeWithZone.new(time.utc, self)
else
TimeWithZone.new(nil, self, time)
end
end | Method for creating new ActiveSupport::TimeWithZone instance in time zone
of +self+ from an ISO 8601 string.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.iso8601('1999-12-31T14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
If the time components are missing then they will be set to zero.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.iso8601('1999-12-31') # => Fri, 31 Dec 1999 00:00:00 HST -10:00
If the string is invalid then an +ArgumentError+ will be raised unlike +parse+
which usually returns +nil+ when given an invalid date string. | iso8601 | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def parse(str, now = now())
parts_to_time(Date._parse(str, false), now)
end | Method for creating new ActiveSupport::TimeWithZone instance in time zone
of +self+ from parsed string.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.parse('1999-12-31 14:00:00') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
If upper components are missing from the string, they are supplied from
TimeZone#now:
Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
Time.zone.parse('22:30:00') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
However, if the date component is not provided, but any other upper
components are supplied, then the day of the month defaults to 1:
Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
If the string is invalid then an +ArgumentError+ could be raised. | parse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def rfc3339(str)
parts = Date._rfc3339(str)
raise ArgumentError, "invalid date" if parts.empty?
time = 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)
)
TimeWithZone.new(time.utc, self)
end | Method for creating new ActiveSupport::TimeWithZone instance in time zone
of +self+ from an RFC 3339 string.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.rfc3339('2000-01-01T00:00:00Z') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
If the time or zone components are missing then an +ArgumentError+ will
be raised. This is much stricter than either +parse+ or +iso8601+ which
allow for missing components.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.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/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def strptime(str, format, now = now())
parts_to_time(DateTime._strptime(str, format), now)
end | Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone.
Assumes that +str+ is a time in the time zone +self+,
unless +format+ includes an explicit time zone.
(This is the same behavior as +parse+.)
In either case, the returned TimeWithZone has the timezone of +self+.
Time.zone = 'Hawaii' # => "Hawaii"
Time.zone.strptime('1999-12-31 14:00:00', '%Y-%m-%d %H:%M:%S') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
If upper components are missing from the string, they are supplied from
TimeZone#now:
Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
Time.zone.strptime('22:30:00', '%H:%M:%S') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
However, if the date component is not provided, but any other upper
components are supplied, then the day of the month defaults to 1:
Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00 | strptime | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def tomorrow
today + 1
end | Returns the next date in this time zone. | tomorrow | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def yesterday
today - 1
end | Returns the previous date in this time zone. | yesterday | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def utc_to_local(time)
tzinfo.utc_to_local(time).yield_self do |t|
ActiveSupport.utc_to_local_returns_utc_offset_times ?
t : Time.utc(t.year, t.month, t.day, t.hour, t.min, t.sec, t.sec_fraction)
end
end | Adjust the given time to the simultaneous time in the time zone
represented by +self+. Returns a local time with the appropriate offset
-- if you want an ActiveSupport::TimeWithZone instance, use
Time#in_time_zone() instead.
As of tzinfo 2, utc_to_local returns a Time with a non-zero utc_offset.
See the +utc_to_local_returns_utc_offset_times+ config for more info. | utc_to_local | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def local_to_utc(time, dst = true)
tzinfo.local_to_utc(time, dst)
end | Adjust the given time to the simultaneous time in UTC. Returns a
Time.utc() instance. | local_to_utc | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def period_for_local(time, dst = true)
tzinfo.period_for_local(time, dst) { |periods| periods.last }
end | Available so that TimeZone instances respond like TZInfo::Timezone
instances. | period_for_local | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/values/time_zone.rb | Apache-2.0 |
def parse(data)
if data.respond_to?(:read)
data = data.read
end
if data.blank?
{}
else
@dbf = DocumentBuilderFactory.new_instance
# secure processing of java xml
# https://archive.is/9xcQQ
@dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
@dbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
@dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false)
@dbf.setFeature(javax.xml.XMLConstants::FEATURE_SECURE_PROCESSING, true)
xml_string_reader = StringReader.new(data)
xml_input_source = InputSource.new(xml_string_reader)
doc = @dbf.new_document_builder.parse(xml_input_source)
merge_element!({ CONTENT_KEY => "" }, doc.document_element, XmlMini.depth)
end
end | Parse an XML Document string or IO into a simple hash using Java's jdom.
data::
XML Document string or IO to parse | parse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def merge_element!(hash, element, depth)
raise "Document too deep!" if depth == 0
delete_empty(hash)
merge!(hash, element.tag_name, collapse(element, depth))
end | Convert an XML element and merge into the hash
hash::
Hash to merge the converted element into.
element::
XML element to merge into hash | merge_element! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def collapse(element, depth)
hash = get_attributes(element)
child_nodes = element.child_nodes
if child_nodes.length > 0
(0...child_nodes.length).each do |i|
child = child_nodes.item(i)
merge_element!(hash, child, depth - 1) unless child.node_type == Node.TEXT_NODE
end
merge_texts!(hash, element) unless empty_content?(element)
hash
else
merge_texts!(hash, element)
end
end | Actually converts an XML document element into a data structure.
element::
The document element to be collapsed. | collapse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def merge_texts!(hash, element)
delete_empty(hash)
text_children = texts(element)
if text_children.join.empty?
hash
else
# must use value to prevent double-escaping
merge!(hash, CONTENT_KEY, text_children.join)
end
end | Merge all the texts of an element into the hash
hash::
Hash to add the converted element to.
element::
XML element whose texts are to me merged into the hash | merge_texts! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def merge!(hash, key, value)
if hash.has_key?(key)
if hash[key].instance_of?(Array)
hash[key] << value
else
hash[key] = [hash[key], value]
end
elsif value.instance_of?(Array)
hash[key] = [value]
else
hash[key] = value
end
hash
end | Adds a new key/value pair to an existing Hash. If the key to be added
already exists and the existing value associated with key is not
an Array, it will be wrapped in an Array. Then the new value is
appended to that Array.
hash::
Hash to add key/value pair to.
key::
Key to be added.
value::
Value to be associated with key. | merge! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def get_attributes(element)
attribute_hash = {}
attributes = element.attributes
(0...attributes.length).each do |i|
attribute_hash[CONTENT_KEY] ||= ""
attribute_hash[attributes.item(i).name] = attributes.item(i).value
end
attribute_hash
end | Converts the attributes array of an XML element into a hash.
Returns an empty Hash if node has no attributes.
element::
XML element to extract attributes from. | get_attributes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def texts(element)
texts = []
child_nodes = element.child_nodes
(0...child_nodes.length).each do |i|
item = child_nodes.item(i)
if item.node_type == Node.TEXT_NODE
texts << item.get_data
end
end
texts
end | Determines if a document element has text content
element::
XML element to be checked. | texts | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def empty_content?(element)
text = +""
child_nodes = element.child_nodes
(0...child_nodes.length).each do |i|
item = child_nodes.item(i)
if item.node_type == Node.TEXT_NODE
text << item.get_data.strip
end
end
text.strip.length == 0
end | Determines if a document element has text content
element::
XML element to be checked. | empty_content? | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/jdom.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/jdom.rb | Apache-2.0 |
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
if data.eof?
{}
else
LibXML::XML::Parser.io(data).parse.to_hash
end
end | Parse an XML Document string or IO into a simple hash using libxml.
data::
XML Document string or IO to parse | parse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/libxml.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/libxml.rb | Apache-2.0 |
def to_hash(hash = {})
node_hash = {}
# Insert node hash into parent hash correctly.
case hash[name]
when Array then hash[name] << node_hash
when Hash then hash[name] = [hash[name], node_hash]
when nil then hash[name] = node_hash
end
# Handle child elements
each_child do |c|
if c.element?
c.to_hash(node_hash)
elsif c.text? || c.cdata?
node_hash[CONTENT_ROOT] ||= +""
node_hash[CONTENT_ROOT] << c.content
end
end
# Remove content node if it is blank
if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
node_hash.delete(CONTENT_ROOT)
end
# Handle attributes
each_attr { |a| node_hash[a.name] = a.value }
hash
end | Convert XML document to hash.
hash::
Hash to merge the converted element into. | to_hash | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/libxml.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/libxml.rb | Apache-2.0 |
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
if data.eof?
{}
else
doc = Nokogiri::XML(data)
raise doc.errors.first if doc.errors.length > 0
doc.to_hash
end
end | Parse an XML Document string or IO into a simple hash using libxml / nokogiri.
data::
XML Document string or IO to parse | parse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/nokogiri.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/nokogiri.rb | Apache-2.0 |
def to_hash(hash = {})
node_hash = {}
# Insert node hash into parent hash correctly.
case hash[name]
when Array then hash[name] << node_hash
when Hash then hash[name] = [hash[name], node_hash]
when nil then hash[name] = node_hash
end
# Handle child elements
children.each do |c|
if c.element?
c.to_hash(node_hash)
elsif c.text? || c.cdata?
node_hash[CONTENT_ROOT] ||= +""
node_hash[CONTENT_ROOT] << c.content
end
end
# Remove content node if it is blank and there are child tags
if node_hash.length > 1 && node_hash[CONTENT_ROOT].blank?
node_hash.delete(CONTENT_ROOT)
end
# Handle attributes
attribute_nodes.each { |a| node_hash[a.node_name] = a.value }
hash
end | Convert XML document to hash.
hash::
Hash to merge the converted element into. | to_hash | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/nokogiri.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/nokogiri.rb | Apache-2.0 |
def parse(data)
if !data.respond_to?(:read)
data = StringIO.new(data || "")
end
if data.eof?
{}
else
require_rexml unless defined?(REXML::Document)
doc = REXML::Document.new(data)
if doc.root
merge_element!({}, doc.root, XmlMini.depth)
else
raise REXML::ParseException,
"The document #{doc.to_s.inspect} does not have a valid root"
end
end
end | Parse an XML Document string or IO into a simple hash.
Same as XmlSimple::xml_in but doesn't shoot itself in the foot,
and uses the defaults from Active Support.
data::
XML Document string or IO to parse | parse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def merge_element!(hash, element, depth)
raise REXML::ParseException, "The document is too deep" if depth == 0
merge!(hash, element.name, collapse(element, depth))
end | Convert an XML element and merge into the hash
hash::
Hash to merge the converted element into.
element::
XML element to merge into hash | merge_element! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def collapse(element, depth)
hash = get_attributes(element)
if element.has_elements?
element.each_element { |child| merge_element!(hash, child, depth - 1) }
merge_texts!(hash, element) unless empty_content?(element)
hash
else
merge_texts!(hash, element)
end
end | Actually converts an XML document element into a data structure.
element::
The document element to be collapsed. | collapse | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def merge_texts!(hash, element)
unless element.has_text?
hash
else
# must use value to prevent double-escaping
texts = +""
element.texts.each { |t| texts << t.value }
merge!(hash, CONTENT_KEY, texts)
end
end | Merge all the texts of an element into the hash
hash::
Hash to add the converted element to.
element::
XML element whose texts are to me merged into the hash | merge_texts! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def merge!(hash, key, value)
if hash.has_key?(key)
if hash[key].instance_of?(Array)
hash[key] << value
else
hash[key] = [hash[key], value]
end
elsif value.instance_of?(Array)
hash[key] = [value]
else
hash[key] = value
end
hash
end | Adds a new key/value pair to an existing Hash. If the key to be added
already exists and the existing value associated with key is not
an Array, it will be wrapped in an Array. Then the new value is
appended to that Array.
hash::
Hash to add key/value pair to.
key::
Key to be added.
value::
Value to be associated with key. | merge! | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def get_attributes(element)
attributes = {}
element.attributes.each { |n, v| attributes[n] = v }
attributes
end | Converts the attributes array of an XML element into a hash.
Returns an empty Hash if node has no attributes.
element::
XML element to extract attributes from. | get_attributes | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/activesupport-6.1.7.3/lib/active_support/xml_mini/rexml.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/rexml.rb | Apache-2.0 |
def initialize(uri, template, mapping)
@uri = uri.dup.freeze
@template = template
@mapping = mapping.dup.freeze
end | #
Creates a new MatchData object.
MatchData objects should never be instantiated directly.
@param [Addressable::URI] uri
The URI that the template was matched against. | initialize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def values
@values ||= self.variables.inject([]) do |accu, key|
accu << self.mapping[key]
accu
end
end | #
@return [Array]
The list of values that were captured by the Template.
Note that this list will include nils for any variables which
were in the Template, but did not appear in the URI. | values | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def to_a
[to_s, *values]
end | #
@return [Array]
Array with the matched URI as first element followed by the captured
values. | to_a | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def values_at(*indexes)
indexes.map { |i| self[i] }
end | Returns multiple captured values at once.
@param [String, Symbol, Fixnum] *indexes
Indices of the captures to be returned
@return [Array]
Values corresponding to given indices.
@see Addressable::Template::MatchData#[] | values_at | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def inspect
sprintf("#<%s:%#0x RESULT:%s>",
self.class.to_s, self.object_id, self.mapping.inspect)
end | #
Returns a <tt>String</tt> representation of the MatchData's state.
@return [String] The MatchData's state, as a <tt>String</tt>. | inspect | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def initialize(pattern)
if !pattern.respond_to?(:to_str)
raise TypeError, "Can't convert #{pattern.class} into String."
end
@pattern = pattern.to_str.dup.freeze
end | #
Creates a new <tt>Addressable::Template</tt> object.
@param [#to_str] pattern The URI Template pattern.
@return [Addressable::Template] The initialized Template object. | initialize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def freeze
self.variables
self.variable_defaults
self.named_captures
super
end | #
Freeze URI, initializing instance variables.
@return [Addressable::URI] The frozen URI object. | freeze | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def inspect
sprintf("#<%s:%#0x PATTERN:%s>",
self.class.to_s, self.object_id, self.pattern)
end | #
Returns a <tt>String</tt> representation of the Template object's state.
@return [String] The Template object's state, as a <tt>String</tt>. | inspect | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def extract(uri, processor=nil)
match_data = self.match(uri, processor)
return (match_data ? match_data.mapping : nil)
end | #
Extracts a mapping from the URI using a URI Template pattern.
@param [Addressable::URI, #to_str] uri
The URI to extract from.
@param [#restore, #match] processor
A template processor object may optionally be supplied.
The object should respond to either the <tt>restore</tt> or
<tt>match</tt> messages or both. The <tt>restore</tt> method should
take two parameters: `[String] name` and `[String] value`.
The <tt>restore</tt> method should reverse any transformations that
have been performed on the value to ensure a valid URI.
The <tt>match</tt> method should take a single
parameter: `[String] name`. The <tt>match</tt> method should return
a <tt>String</tt> containing a regular expression capture group for
matching on that particular variable. The default value is `".*?"`.
The <tt>match</tt> method has no effect on multivariate operator
expansions.
@return [Hash, NilClass]
The <tt>Hash</tt> mapping that was extracted from the URI, or
<tt>nil</tt> if the URI didn't match the template.
@example
class ExampleProcessor
def self.restore(name, value)
return value.gsub(/\+/, " ") if name == "query"
return value
end
def self.match(name)
return ".*?" if name == "first"
return ".*"
end
end
uri = Addressable::URI.parse(
"http://example.com/search/an+example+search+query/"
)
Addressable::Template.new(
"http://example.com/search/{query}/"
).extract(uri, ExampleProcessor)
#=> {"query" => "an example search query"}
uri = Addressable::URI.parse("http://example.com/a/b/c/")
Addressable::Template.new(
"http://example.com/{first}/{second}/"
).extract(uri, ExampleProcessor)
#=> {"first" => "a", "second" => "b/c"}
uri = Addressable::URI.parse("http://example.com/a/b/c/")
Addressable::Template.new(
"http://example.com/{first}/{-list|/|second}/"
).extract(uri)
#=> {"first" => "a", "second" => ["b", "c"]} | extract | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def match(uri, processor=nil)
uri = Addressable::URI.parse(uri) unless uri.is_a?(Addressable::URI)
mapping = {}
# First, we need to process the pattern, and extract the values.
expansions, expansion_regexp =
parse_template_pattern(pattern, processor)
return nil unless uri.to_str.match(expansion_regexp)
unparsed_values = uri.to_str.scan(expansion_regexp).flatten
if uri.to_str == pattern
return Addressable::Template::MatchData.new(uri, self, mapping)
elsif expansions.size > 0
index = 0
expansions.each do |expansion|
_, operator, varlist = *expansion.match(EXPRESSION)
varlist.split(',').each do |varspec|
_, name, modifier = *varspec.match(VARSPEC)
mapping[name] ||= nil
case operator
when nil, '+', '#', '/', '.'
unparsed_value = unparsed_values[index]
name = varspec[VARSPEC, 1]
value = unparsed_value
value = value.split(JOINERS[operator]) if value && modifier == '*'
when ';', '?', '&'
if modifier == '*'
if unparsed_values[index]
value = unparsed_values[index].split(JOINERS[operator])
value = value.inject({}) do |acc, v|
key, val = v.split('=')
val = "" if val.nil?
acc[key] = val
acc
end
end
else
if (unparsed_values[index])
name, value = unparsed_values[index].split('=')
value = "" if value.nil?
end
end
end
if processor != nil && processor.respond_to?(:restore)
value = processor.restore(name, value)
end
if processor == nil
if value.is_a?(Hash)
value = value.inject({}){|acc, (k, v)|
acc[Addressable::URI.unencode_component(k)] =
Addressable::URI.unencode_component(v)
acc
}
elsif value.is_a?(Array)
value = value.map{|v| Addressable::URI.unencode_component(v) }
else
value = Addressable::URI.unencode_component(value)
end
end
if !mapping.has_key?(name) || mapping[name].nil?
# Doesn't exist, set to value (even if value is nil)
mapping[name] = value
end
index = index + 1
end
end
return Addressable::Template::MatchData.new(uri, self, mapping)
else
return nil
end
end | #
Extracts match data from the URI using a URI Template pattern.
@param [Addressable::URI, #to_str] uri
The URI to extract from.
@param [#restore, #match] processor
A template processor object may optionally be supplied.
The object should respond to either the <tt>restore</tt> or
<tt>match</tt> messages or both. The <tt>restore</tt> method should
take two parameters: `[String] name` and `[String] value`.
The <tt>restore</tt> method should reverse any transformations that
have been performed on the value to ensure a valid URI.
The <tt>match</tt> method should take a single
parameter: `[String] name`. The <tt>match</tt> method should return
a <tt>String</tt> containing a regular expression capture group for
matching on that particular variable. The default value is `".*?"`.
The <tt>match</tt> method has no effect on multivariate operator
expansions.
@return [Hash, NilClass]
The <tt>Hash</tt> mapping that was extracted from the URI, or
<tt>nil</tt> if the URI didn't match the template.
@example
class ExampleProcessor
def self.restore(name, value)
return value.gsub(/\+/, " ") if name == "query"
return value
end
def self.match(name)
return ".*?" if name == "first"
return ".*"
end
end
uri = Addressable::URI.parse(
"http://example.com/search/an+example+search+query/"
)
match = Addressable::Template.new(
"http://example.com/search/{query}/"
).match(uri, ExampleProcessor)
match.variables
#=> ["query"]
match.captures
#=> ["an example search query"]
uri = Addressable::URI.parse("http://example.com/a/b/c/")
match = Addressable::Template.new(
"http://example.com/{first}/{+second}/"
).match(uri, ExampleProcessor)
match.variables
#=> ["first", "second"]
match.captures
#=> ["a", "b/c"]
uri = Addressable::URI.parse("http://example.com/a/b/c/")
match = Addressable::Template.new(
"http://example.com/{first}{/second*}/"
).match(uri)
match.variables
#=> ["first", "second"]
match.captures
#=> ["a", ["b", "c"]] | match | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def partial_expand(mapping, processor=nil, normalize_values=true)
result = self.pattern.dup
mapping = normalize_keys(mapping)
result.gsub!( EXPRESSION ) do |capture|
transform_partial_capture(mapping, capture, processor, normalize_values)
end
return Addressable::Template.new(result)
end | #
Expands a URI template into another URI template.
@param [Hash] mapping The mapping that corresponds to the pattern.
@param [#validate, #transform] processor
An optional processor object may be supplied.
@param [Boolean] normalize_values
Optional flag to enable/disable unicode normalization. Default: true
The object should respond to either the <tt>validate</tt> or
<tt>transform</tt> messages or both. Both the <tt>validate</tt> and
<tt>transform</tt> methods should take two parameters: <tt>name</tt> and
<tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt>
or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid,
<tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt>
exception will be raised if the value is invalid. The <tt>transform</tt>
method should return the transformed variable value as a <tt>String</tt>.
If a <tt>transform</tt> method is used, the value will not be percent
encoded automatically. Unicode normalization will be performed both
before and after sending the value to the transform method.
@return [Addressable::Template] The partially expanded URI template.
@example
Addressable::Template.new(
"http://example.com/{one}/{two}/"
).partial_expand({"one" => "1"}).pattern
#=> "http://example.com/1/{two}/"
Addressable::Template.new(
"http://example.com/{?one,two}/"
).partial_expand({"one" => "1"}).pattern
#=> "http://example.com/?one=1{&two}/"
Addressable::Template.new(
"http://example.com/{?one,two,three}/"
).partial_expand({"one" => "1", "three" => 3}).pattern
#=> "http://example.com/?one=1{&two}&three=3" | partial_expand | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def expand(mapping, processor=nil, normalize_values=true)
result = self.pattern.dup
mapping = normalize_keys(mapping)
result.gsub!( EXPRESSION ) do |capture|
transform_capture(mapping, capture, processor, normalize_values)
end
return Addressable::URI.parse(result)
end | #
Expands a URI template into a full URI.
@param [Hash] mapping The mapping that corresponds to the pattern.
@param [#validate, #transform] processor
An optional processor object may be supplied.
@param [Boolean] normalize_values
Optional flag to enable/disable unicode normalization. Default: true
The object should respond to either the <tt>validate</tt> or
<tt>transform</tt> messages or both. Both the <tt>validate</tt> and
<tt>transform</tt> methods should take two parameters: <tt>name</tt> and
<tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt>
or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid,
<tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt>
exception will be raised if the value is invalid. The <tt>transform</tt>
method should return the transformed variable value as a <tt>String</tt>.
If a <tt>transform</tt> method is used, the value will not be percent
encoded automatically. Unicode normalization will be performed both
before and after sending the value to the transform method.
@return [Addressable::URI] The expanded URI template.
@example
class ExampleProcessor
def self.validate(name, value)
return !!(value =~ /^[\w ]+$/) if name == "query"
return true
end
def self.transform(name, value)
return value.gsub(/ /, "+") if name == "query"
return value
end
end
Addressable::Template.new(
"http://example.com/search/{query}/"
).expand(
{"query" => "an example search query"},
ExampleProcessor
).to_str
#=> "http://example.com/search/an+example+search+query/"
Addressable::Template.new(
"http://example.com/search/{query}/"
).expand(
{"query" => "an example search query"}
).to_str
#=> "http://example.com/search/an%20example%20search%20query/"
Addressable::Template.new(
"http://example.com/search/{query}/"
).expand(
{"query" => "bogus!"},
ExampleProcessor
).to_str
#=> Addressable::Template::InvalidTemplateValueError | expand | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def variables
@variables ||= ordered_variable_defaults.map { |var, val| var }.uniq
end | #
Returns an Array of variables used within the template pattern.
The variables are listed in the Array in the order they appear within
the pattern. Multiple occurrences of a variable within a pattern are
not represented in this Array.
@return [Array] The variables present in the template's pattern. | variables | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def variable_defaults
@variable_defaults ||=
Hash[*ordered_variable_defaults.reject { |k, v| v.nil? }.flatten]
end | #
Returns a mapping of variables to their default values specified
in the template. Variables without defaults are not returned.
@return [Hash] Mapping of template variables to their defaults | variable_defaults | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def to_regexp
_, source = parse_template_pattern(pattern)
Regexp.new(source)
end | #
Coerces a template into a `Regexp` object. This regular expression will
behave very similarly to the actual template, and should match the same
URI values, but it cannot fully handle, for example, values that would
extract to an `Array`.
@return [Regexp] A regular expression which should match the template. | to_regexp | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def transform_partial_capture(mapping, capture, processor = nil,
normalize_values = true)
_, operator, varlist = *capture.match(EXPRESSION)
vars = varlist.split(",")
if operator == "?"
# partial expansion of form style query variables sometimes requires a
# slight reordering of the variables to produce a valid url.
first_to_expand = vars.find { |varspec|
_, name, _ = *varspec.match(VARSPEC)
mapping.key?(name) && !mapping[name].nil?
}
vars = [first_to_expand] + vars.reject {|varspec| varspec == first_to_expand} if first_to_expand
end
vars.
inject("".dup) do |acc, varspec|
_, name, _ = *varspec.match(VARSPEC)
next_val = if mapping.key? name
transform_capture(mapping, "{#{operator}#{varspec}}",
processor, normalize_values)
else
"{#{operator}#{varspec}}"
end
# If we've already expanded at least one '?' operator with non-empty
# value, change to '&'
operator = "&" if (operator == "?") && (next_val != "")
acc << next_val
end
end | #
Loops through each capture and expands any values available in mapping
@param [Hash] mapping
Set of keys to expand
@param [String] capture
The expression to expand
@param [#validate, #transform] processor
An optional processor object may be supplied.
@param [Boolean] normalize_values
Optional flag to enable/disable unicode normalization. Default: true
The object should respond to either the <tt>validate</tt> or
<tt>transform</tt> messages or both. Both the <tt>validate</tt> and
<tt>transform</tt> methods should take two parameters: <tt>name</tt> and
<tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt>
or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid,
<tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception
will be raised if the value is invalid. The <tt>transform</tt> method
should return the transformed variable value as a <tt>String</tt>. If a
<tt>transform</tt> method is used, the value will not be percent encoded
automatically. Unicode normalization will be performed both before and
after sending the value to the transform method.
@return [String] The expanded expression | transform_partial_capture | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def transform_capture(mapping, capture, processor=nil,
normalize_values=true)
_, operator, varlist = *capture.match(EXPRESSION)
return_value = varlist.split(',').inject([]) do |acc, varspec|
_, name, modifier = *varspec.match(VARSPEC)
value = mapping[name]
unless value == nil || value == {}
allow_reserved = %w(+ #).include?(operator)
# Common primitives where the .to_s output is well-defined
if Numeric === value || Symbol === value ||
value == true || value == false
value = value.to_s
end
length = modifier.gsub(':', '').to_i if modifier =~ /^:\d+/
unless (Hash === value) ||
value.respond_to?(:to_ary) || value.respond_to?(:to_str)
raise TypeError,
"Can't convert #{value.class} into String or Array."
end
value = normalize_value(value) if normalize_values
if processor == nil || !processor.respond_to?(:transform)
# Handle percent escaping
if allow_reserved
encode_map =
Addressable::URI::CharacterClasses::RESERVED +
Addressable::URI::CharacterClasses::UNRESERVED
else
encode_map = Addressable::URI::CharacterClasses::UNRESERVED
end
if value.kind_of?(Array)
transformed_value = value.map do |val|
if length
Addressable::URI.encode_component(val[0...length], encode_map)
else
Addressable::URI.encode_component(val, encode_map)
end
end
unless modifier == "*"
transformed_value = transformed_value.join(',')
end
elsif value.kind_of?(Hash)
transformed_value = value.map do |key, val|
if modifier == "*"
"#{
Addressable::URI.encode_component( key, encode_map)
}=#{
Addressable::URI.encode_component( val, encode_map)
}"
else
"#{
Addressable::URI.encode_component( key, encode_map)
},#{
Addressable::URI.encode_component( val, encode_map)
}"
end
end
unless modifier == "*"
transformed_value = transformed_value.join(',')
end
else
if length
transformed_value = Addressable::URI.encode_component(
value[0...length], encode_map)
else
transformed_value = Addressable::URI.encode_component(
value, encode_map)
end
end
end
# Process, if we've got a processor
if processor != nil
if processor.respond_to?(:validate)
if !processor.validate(name, value)
display_value = value.kind_of?(Array) ? value.inspect : value
raise InvalidTemplateValueError,
"#{name}=#{display_value} is an invalid template value."
end
end
if processor.respond_to?(:transform)
transformed_value = processor.transform(name, value)
if normalize_values
transformed_value = normalize_value(transformed_value)
end
end
end
acc << [name, transformed_value]
end
acc
end
return "" if return_value.empty?
join_values(operator, return_value)
end | #
Transforms a mapped value so that values can be substituted into the
template.
@param [Hash] mapping The mapping to replace captures
@param [String] capture
The expression to replace
@param [#validate, #transform] processor
An optional processor object may be supplied.
@param [Boolean] normalize_values
Optional flag to enable/disable unicode normalization. Default: true
The object should respond to either the <tt>validate</tt> or
<tt>transform</tt> messages or both. Both the <tt>validate</tt> and
<tt>transform</tt> methods should take two parameters: <tt>name</tt> and
<tt>value</tt>. The <tt>validate</tt> method should return <tt>true</tt>
or <tt>false</tt>; <tt>true</tt> if the value of the variable is valid,
<tt>false</tt> otherwise. An <tt>InvalidTemplateValueError</tt> exception
will be raised if the value is invalid. The <tt>transform</tt> method
should return the transformed variable value as a <tt>String</tt>. If a
<tt>transform</tt> method is used, the value will not be percent encoded
automatically. Unicode normalization will be performed both before and
after sending the value to the transform method.
@return [String] The expanded expression | transform_capture | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def join_values(operator, return_value)
leader = LEADERS.fetch(operator, '')
joiner = JOINERS.fetch(operator, ',')
case operator
when '&', '?'
leader + return_value.map{|k,v|
if v.is_a?(Array) && v.first =~ /=/
v.join(joiner)
elsif v.is_a?(Array)
v.map{|inner_value| "#{k}=#{inner_value}"}.join(joiner)
else
"#{k}=#{v}"
end
}.join(joiner)
when ';'
return_value.map{|k,v|
if v.is_a?(Array) && v.first =~ /=/
';' + v.join(";")
elsif v.is_a?(Array)
';' + v.map{|inner_value| "#{k}=#{inner_value}"}.join(";")
else
v && v != '' ? ";#{k}=#{v}" : ";#{k}"
end
}.join
else
leader + return_value.map{|k,v| v}.join(joiner)
end
end | #
Takes a set of values, and joins them together based on the
operator.
@param [String, Nil] operator One of the operators from the set
(?,&,+,#,;,/,.), or nil if there wasn't one.
@param [Array] return_value
The set of return values (as [variable_name, value] tuples) that will
be joined together.
@return [String] The transformed mapped value | join_values | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def normalize_value(value)
# Handle unicode normalization
if value.respond_to?(:to_ary)
value.to_ary.map! { |val| normalize_value(val) }
elsif value.kind_of?(Hash)
value = value.inject({}) { |acc, (k, v)|
acc[normalize_value(k)] = normalize_value(v)
acc
}
else
value = value.to_s if !value.kind_of?(String)
if value.encoding != Encoding::UTF_8
value = value.dup.force_encoding(Encoding::UTF_8)
end
value = value.unicode_normalize(:nfc)
end
value
end | #
Takes a set of values, and joins them together based on the
operator.
@param [Hash, Array, String] value
Normalizes unicode keys and values with String#unicode_normalize (NFC)
@return [Hash, Array, String] The normalized values | normalize_value | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def normalize_keys(mapping)
return mapping.inject({}) do |accu, pair|
name, value = pair
if Symbol === name
name = name.to_s
elsif name.respond_to?(:to_str)
name = name.to_str
else
raise TypeError,
"Can't convert #{name.class} into String."
end
accu[name] = value
accu
end
end | #
Generates a hash with string keys
@param [Hash] mapping A mapping hash to normalize
@return [Hash]
A hash with stringified keys | normalize_keys | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def parse_template_pattern(pattern, processor = nil)
if processor.nil? && pattern == @pattern
@cached_template_parse ||=
parse_new_template_pattern(pattern, processor)
else
parse_new_template_pattern(pattern, processor)
end
end | #
Generates the <tt>Regexp</tt> that parses a template pattern. Memoizes the
value if template processor not set (processors may not be deterministic)
@param [String] pattern The URI template pattern.
@param [#match] processor The template processor to use.
@return [Array, Regexp]
An array of expansion variables nad a regular expression which may be
used to parse a template pattern | parse_template_pattern | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def parse_new_template_pattern(pattern, processor = nil)
# Escape the pattern. The two gsubs restore the escaped curly braces
# back to their original form. Basically, escape everything that isn't
# within an expansion.
escaped_pattern = Regexp.escape(
pattern
).gsub(/\\\{(.*?)\\\}/) do |escaped|
escaped.gsub(/\\(.)/, "\\1")
end
expansions = []
# Create a regular expression that captures the values of the
# variables in the URI.
regexp_string = escaped_pattern.gsub( EXPRESSION ) do |expansion|
expansions << expansion
_, operator, varlist = *expansion.match(EXPRESSION)
leader = Regexp.escape(LEADERS.fetch(operator, ''))
joiner = Regexp.escape(JOINERS.fetch(operator, ','))
combined = varlist.split(',').map do |varspec|
_, name, modifier = *varspec.match(VARSPEC)
result = processor && processor.respond_to?(:match) ? processor.match(name) : nil
if result
"(?<#{name}>#{ result })"
else
group = case operator
when '+'
"#{ RESERVED }*?"
when '#'
"#{ RESERVED }*?"
when '/'
"#{ UNRESERVED }*?"
when '.'
"#{ UNRESERVED.gsub('\.', '') }*?"
when ';'
"#{ UNRESERVED }*=?#{ UNRESERVED }*?"
when '?'
"#{ UNRESERVED }*=#{ UNRESERVED }*?"
when '&'
"#{ UNRESERVED }*=#{ UNRESERVED }*?"
else
"#{ UNRESERVED }*?"
end
if modifier == '*'
"(?<#{name}>#{group}(?:#{joiner}?#{group})*)?"
else
"(?<#{name}>#{group})?"
end
end
end.join("#{joiner}?")
"(?:|#{leader}#{combined})"
end
# Ensure that the regular expression matches the whole URI.
regexp_string = "\\A#{regexp_string}\\z"
return expansions, Regexp.new(regexp_string)
end | #
Generates the <tt>Regexp</tt> that parses a template pattern.
@param [String] pattern The URI template pattern.
@param [#match] processor The template processor to use.
@return [Array, Regexp]
An array of expansion variables nad a regular expression which may be
used to parse a template pattern | parse_new_template_pattern | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/addressable-2.8.4/lib/addressable/template.rb | Apache-2.0 |
def initialize(type, children=[], properties={})
@type, @children = type.to_sym, children.to_a.freeze
assign_properties(properties)
@hash = [@type, @children, self.class].hash
freeze
end | Constructs a new instance of Node.
The arguments `type` and `children` are converted with `to_sym` and
`to_a` respectively. Additionally, the result of converting `children`
is frozen. While mutating the arguments is generally considered harmful,
the most common case is to pass an array literal to the constructor. If
your code does not expect the argument to be frozen, use `#dup`.
The `properties` hash is passed to {#assign_properties}. | initialize | ruby | collabnix/kubelabs | .bundles_cache/ruby/2.6.0/gems/ast-2.4.2/lib/ast/node.rb | https://github.com/collabnix/kubelabs/blob/master/.bundles_cache/ruby/2.6.0/gems/ast-2.4.2/lib/ast/node.rb | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.