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 task_name_belongs_to_a_valid_task
Task.named(task_name)
rescue Task::NotFoundError
errors.add(:task_name, "must be the name of an existing Task.")
end
|
Performs validation on the task_name attribute.
A Run must be associated with a valid Task to be valid.
In order to confirm that, the Task is looked up by name.
|
task_name_belongs_to_a_valid_task
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def csv_attachment_presence
if Task.named(task_name).has_csv_content? && !csv_file.attached?
errors.add(:csv_file, "must be attached to CSV Task.")
elsif !Task.named(task_name).has_csv_content? && csv_file.present?
errors.add(:csv_file, "should not be attached to non-CSV Task.")
end
rescue Task::NotFoundError
nil
end
|
Performs validation on the presence of a :csv_file attachment.
A Run for a Task that uses CsvCollection must have an attached :csv_file
to be valid. Conversely, a Run for a Task that doesn't use CsvCollection
should not have an attachment to be valid. The appropriate error is added
if the Run does not meet the above criteria.
|
csv_attachment_presence
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def csv_content_type
if csv_file.present? && csv_file.content_type != "text/csv"
errors.add(:csv_file, "must be a CSV")
end
rescue Task::NotFoundError
nil
end
|
Performs validation on the content type of the :csv_file attachment.
A Run for a Task that uses CsvCollection must have a present :csv_file
and a content type of "text/csv" to be valid. The appropriate error is
added if the Run does not meet the above criteria.
|
csv_content_type
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def validate_task_arguments
arguments_match_task_attributes if arguments.present?
if task.invalid?
error_messages = task.errors
.map { |error| "#{error.attribute.inspect} #{error.message}" }
errors.add(
:arguments,
"are invalid: #{error_messages.join("; ")}",
)
end
rescue Task::NotFoundError
nil
end
|
Performs validation on the arguments to use for the Task. If the Task is
invalid, the errors are added to the Run.
|
validate_task_arguments
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def csv_file
return unless defined?(ActiveStorage)
return unless ActiveStorage::Attachment.table_exists?
super
end
|
Fetches the attached ActiveStorage CSV file for the run. Checks first
whether the ActiveStorage::Attachment table exists so that we are
compatible with apps that are not using ActiveStorage.
@return [ActiveStorage::Attached::One] the attached CSV file
|
csv_file
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def task
@task ||= begin
task = Task.named(task_name).new
if task.attribute_names.any? && arguments.present?
task.assign_attributes(arguments)
end
task.metadata = metadata
task
rescue ActiveModel::UnknownAttributeError
task
end
end
|
Returns a Task instance for this Run. Assigns any attributes to the Task
based on the Run's parameters. Note that the Task instance is not supplied
with :csv_content yet if it's a CSV Task. This is done in the job, since
downloading the CSV file can take some time.
@return [Task] a Task instance.
|
task
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def masked_arguments
return unless arguments.present?
argument_filter.filter(arguments)
end
|
Returns all the run arguments with sensitive information masked.
@return [Hash] The masked arguments.
|
masked_arguments
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/run.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/run.rb
|
MIT
|
def initialize(run)
super("The job to perform #{run.task_name} could not be enqueued")
@run = run
end
|
Initializes a Enqueuing Error.
@param run [Run] the Run which failed to be enqueued.
@return [EnqueuingError] an Enqueuing Error instance.
|
initialize
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/runner.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/runner.rb
|
MIT
|
def run(name:, csv_file: nil, arguments: {}, run_model: Run, metadata: nil)
run = run_model.new(task_name: name, arguments: arguments, metadata: metadata)
if csv_file
run.csv_file.attach(csv_file)
run.csv_file.filename = filename(name)
end
job = instantiate_job(run)
run.job_id = job.job_id
yield run if block_given?
run.enqueued!
enqueue(run, job)
Task.named(name)
end
|
Runs a Task.
This method creates a Run record for the given Task name and enqueues the
Run. If a CSV file is provided, it is attached to the Run record.
@param name [String] the name of the Task to be run.
@param csv_file [attachable, nil] a CSV file that provides the collection
for the Task to iterate over when running, in the form of an attachable
(see https://edgeapi.rubyonrails.org/classes/ActiveStorage/Attached/One.html#method-i-attach).
Value is nil if the Task does not use CSV iteration.
@param arguments [Hash] the arguments to persist to the Run and to make
accessible to the Task.
@return [Task] the Task that was run.
@raise [EnqueuingError] if an error occurs while enqueuing the Run.
@raise [ActiveRecord::RecordInvalid] if validation errors occur while
creating the Run.
@raise [ActiveRecord::ValueTooLong] if the creation of the Run fails due
to a value being too long for the column type.
|
run
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/runner.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/runner.rb
|
MIT
|
def resume(run)
job = instantiate_job(run)
run.job_id = job.job_id
run.enqueued!
enqueue(run, job)
end
|
Resumes a Task.
This method re-instantiates and re-enqueues a job for a Run that was
previously paused.
@param run [MaintenanceTasks::Run] the Run record to be resumed.
@return [TaskJob] the enqueued Task job.
@raise [EnqueuingError] if an error occurs while enqueuing the Run.
|
resume
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/runner.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/runner.rb
|
MIT
|
def initialize(runs, cursor)
@runs = runs
@cursor = cursor
end
|
Initializes a Runs Page with a Runs relation and a cursor. This page is
used by the views to render a set of Runs.
@param runs [ActiveRecord::Relation<MaintenanceTasks::Run>] the relation
of Run records to be paginated.
@param cursor [String, nil] the id that serves as the cursor when
querying the Runs dataset to produce a page of Runs. If nil, the first
Runs in the relation are used.
|
initialize
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/runs_page.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/runs_page.rb
|
MIT
|
def last?
records
@extra_run.nil?
end
|
Returns whether this Page is the last one.
@return [Boolean] whether this Page contains the last Run record in the Runs
dataset that is being paginated. This is done by checking whether an extra
Run was loaded by #records - if no extra Run was loaded, this is the last page.
|
last?
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/runs_page.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/runs_page.rb
|
MIT
|
def named(name)
task = name.safe_constantize
raise NotFoundError.new("Task #{name} not found.", name) unless task
unless task.is_a?(Class) && task < Task
raise NotFoundError.new("#{name} is not a Task.", name)
end
task
end
|
Finds a Task with the given name.
@param name [String] the name of the Task to be found.
@return [Task] the Task with the given name.
@raise [NotFoundError] if a Task with the given name does not exist.
|
named
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def load_all
load_constants
descendants
end
|
Loads and returns a list of concrete classes that inherit
from the Task superclass.
@return [Array<Class>] the list of classes.
|
load_all
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def available_tasks
warn(<<~MSG.squish, category: :deprecated)
MaintenanceTasks::Task.available_tasks is deprecated and will be
removed from maintenance-tasks 3.0.0. Use .load_all instead.
MSG
load_all
end
|
Loads and returns a list of concrete classes that inherit
from the Task superclass.
@return [Array<Class>] the list of classes.
|
available_tasks
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def csv_collection(in_batches: nil, **csv_options)
unless defined?(ActiveStorage)
raise NotImplementedError, "Active Storage needs to be installed\n" \
"To resolve this issue run: bin/rails active_storage:install"
end
csv_options[:headers] = true unless csv_options.key?(:headers)
csv_options[:encoding] ||= Encoding.default_external
self.collection_builder_strategy = if in_batches
BatchCsvCollectionBuilder.new(in_batches, **csv_options)
else
CsvCollectionBuilder.new(**csv_options)
end
end
|
Make this Task a task that handles CSV.
@param in_batches [Integer] optionally, supply a batch size if the CSV
should be processed in batches.
@param csv_options [Hash] optionally, supply options for the CSV parser.
If not given, defaults to: <code>{ headers: true }</code>
@see https://ruby-doc.org/3.3.0/stdlibs/csv/CSV.html#class-CSV-label-Options+for+Parsing
An input to upload a CSV will be added in the form to start a Run. The
collection and count method are implemented.
|
csv_collection
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def no_collection
self.collection_builder_strategy = MaintenanceTasks::NoCollectionBuilder.new
end
|
Make this a Task that calls #process once, instead of iterating over
a collection.
|
no_collection
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def throttle_on(backoff: 30.seconds, &condition)
backoff_as_proc = backoff
backoff_as_proc = -> { backoff } unless backoff.respond_to?(:call)
self.throttle_conditions += [{ throttle_on: condition, backoff: backoff_as_proc }]
end
|
Add a condition under which this Task will be throttled.
@param backoff [ActiveSupport::Duration, #call] a custom backoff
can be specified. This is the time to wait before retrying the Task,
defaulting to 30 seconds. If provided as a Duration, the backoff is
wrapped in a proc. Alternatively,an object responding to call can be
used. It must return an ActiveSupport::Duration.
@yieldreturn [Boolean] where the throttle condition is being met,
indicating that the Task should throttle.
|
throttle_on
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def mask_attribute(*attributes)
self.masked_arguments += attributes
end
|
Adds attribute names to sensitive arguments list.
@param attributes [Array<Symbol>] the attribute names to filter.
|
mask_attribute
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_start(*filter_list, &block)
set_callback(:start, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task starts.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_start
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_complete(*filter_list, &block)
set_callback(:complete, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task completes.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_complete
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_pause(*filter_list, &block)
set_callback(:pause, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task pauses.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_pause
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_interrupt(*filter_list, &block)
set_callback(:interrupt, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task is interrupted.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_interrupt
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_cancel(*filter_list, &block)
set_callback(:cancel, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task is cancelled.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_cancel
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def after_error(*filter_list, &block)
set_callback(:error, :after, *filter_list, &block)
end
|
Initialize a callback to run after the task produces an error.
@param filter_list apply filters to the callback
(see https://api.rubyonrails.org/classes/ActiveSupport/Callbacks/ClassMethods.html#method-i-set_callback)
|
after_error
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def report_on(*exceptions, **report_options)
rescue_from(*exceptions) do |exception|
if Rails.gem_version >= Gem::Version.new("7.1")
Rails.error.report(exception, source: "maintenance_tasks", **report_options)
else
Rails.error.report(exception, handled: true, **report_options)
end
end
end
|
Rescue listed exceptions during an iteration and report them to the error reporter, then
continue iteration.
@param exceptions list of exceptions to rescue and report
@param report_options [Hash] optionally, supply additional options for `Rails.error.report`.
By default: <code>{ source: "maintenance_tasks" }</code> or (Rails <v7.1) <code>{ handled: true }</code>.
|
report_on
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def csv_content
raise NoMethodError unless has_csv_content?
@csv_content
end
|
The contents of a CSV file to be processed by a Task.
@return [String] the content of the CSV file to process.
|
csv_content
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def process(_item)
raise NoMethodError, "#{self.class.name} must implement `process`."
end
|
Placeholder method to raise in case a subclass fails to implement the
expected instance method.
@param _item [Object] the current item from the enumerator being iterated.
@raise [NotImplementedError] with a message advising subclasses to
implement an override for this method.
|
process
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task.rb
|
MIT
|
def available_tasks
tasks = []
task_names = Task.load_all.map(&:name)
active_runs = Run.with_attached_csv.active.where(task_name: task_names)
active_runs.each do |run|
tasks << TaskDataIndex.new(run.task_name, run)
task_names.delete(run.task_name)
end
completed_runs = Run.completed.where(task_name: task_names)
last_runs = Run.with_attached_csv
.where(created_at: completed_runs.select("MAX(created_at) as created_at").group(:task_name))
task_names.map do |task_name|
last_run = last_runs.find { |run| run.task_name == task_name }
tasks << TaskDataIndex.new(task_name, last_run)
end
# We add an additional sorting key (status) to avoid possible
# inconsistencies across database adapters when a Task has
# multiple active Runs.
tasks.sort_by! { |task| [task.name, task.status] }
end
|
Returns a list of sorted Task Data objects that represent the
available Tasks.
Tasks are sorted by category, and within a category, by Task name.
Determining a Task's category requires their latest Run records.
Two queries are done to get the currently active and completed Run
records, and Task Data instances are initialized with these related run
values.
@return [Array<TaskDataIndex>] the list of Task Data.
|
available_tasks
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_index.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_index.rb
|
MIT
|
def initialize(name, related_run = nil)
@name = name
@related_run = related_run
end
|
Initializes a Task Data with a name and optionally a related run.
@param name [String] the name of the Task subclass.
@param related_run [MaintenanceTasks::Run] optionally, a Run record to
set for the Task.
|
initialize
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_index.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_index.rb
|
MIT
|
def status
related_run&.status || "new"
end
|
Returns the status of the latest active or completed Run, if present.
If the Task does not have any Runs, the Task status is `new`.
@return [String] the Task status.
|
status
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_index.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_index.rb
|
MIT
|
def category
if related_run.present? && related_run.active?
:active
elsif related_run.nil?
:new
else
:completed
end
end
|
Retrieves the Task's category, which is one of active, new, or completed.
@return [Symbol] the category of the Task.
|
category
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_index.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_index.rb
|
MIT
|
def initialize(name, runs_cursor: nil, arguments: nil)
@name = name
@arguments = arguments
@runs_page = RunsPage.new(completed_runs, runs_cursor)
end
|
Initializes a Task Data with a name.
@param name [String] the name of the Task subclass.
@param runs_cursor [String, nil] the cursor for the runs page.
@param arguments [Hash, nil] the Task arguments.
|
initialize
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def prepare(name, runs_cursor: nil, arguments: nil)
new(name, runs_cursor:, arguments:)
.load_active_runs
.ensure_task_exists
end
|
Prepares a Task Data from a task name.
@param name [String] the name of the Task subclass.
@param runs_cursor [String, nil] the cursor for the runs page.
@param arguments [Hash, nil] the Task arguments.
@raise [Task::NotFoundError] if the Task doesn't have runs (for the given cursor) and doesn't exist.
|
prepare
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def code
return if deleted?
task = Task.named(name)
file = if Object.respond_to?(:const_source_location)
Object.const_source_location(task.name).first
else
task.instance_method(:process).source_location.first
end
File.read(file)
end
|
The Task's source code.
@return [String] the contents of the file which defines the Task.
@return [nil] if the Task file was deleted.
|
code
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def active_runs
@active_runs ||= runs.active
end
|
Returns the set of currently active Run records associated with the Task.
@return [ActiveRecord::Relation<MaintenanceTasks::Run>] the relation of
active Run records.
|
active_runs
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def completed_runs
@completed_runs ||= runs.completed
end
|
Returns the set of completed Run records associated with the Task.
This collection represents a historic of past Runs for information
purposes, since the base for Task Data information comes
primarily from currently active runs.
@return [ActiveRecord::Relation<MaintenanceTasks::Run>] the relation of
completed Run records.
|
completed_runs
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def deleted?
Task.named(name)
false
rescue Task::NotFoundError
true
end
|
@return [Boolean] whether the Task has been deleted.
|
deleted?
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def csv_task?
!deleted? && Task.named(name).has_csv_content?
end
|
@return [Boolean] whether the Task inherits from CsvTask.
|
csv_task?
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def parameter_names
if deleted?
[]
else
Task.named(name).attribute_names
end
end
|
@return [Array<String>] the names of parameters the Task accepts.
|
parameter_names
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def new
return if deleted?
task = MaintenanceTasks::Task.named(name).new
begin
task.assign_attributes(@arguments) if @arguments
rescue ActiveModel::UnknownAttributeError
# nothing to do
end
task
end
|
@return [MaintenanceTasks::Task] an instance of the Task class.
@return [nil] if the Task file was deleted.
|
new
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def load_active_runs
active_runs.load
self
end
|
Preloads the records from the active_runs ActiveRecord::Relation
@return [self]
|
load_active_runs
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def ensure_task_exists
if active_runs.none? && runs_page.records.none?
Task.named(name)
end
self
end
|
@raise [Task::NotFoundError] if the Task doesn't have Runs (for the given cursor) and doesn't exist.
@return [self]
|
ensure_task_exists
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/task_data_show.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/task_data_show.rb
|
MIT
|
def initialize(throttle_duration, &persist)
@throttle_duration = throttle_duration
@persist = persist
@last_persisted = Time.now
@ticks_recorded = 0
end
|
Creates a Ticker that will call the block each time +tick+ is called,
unless the tick is being throttled.
@param throttle_duration [ActiveSupport::Duration, Numeric] Duration
since initialization or last call that will cause a throttle.
@yieldparam ticks [Integer] the increment in ticks to be persisted.
|
initialize
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/ticker.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/ticker.rb
|
MIT
|
def tick
@ticks_recorded += 1
persist if persist?
end
|
Increments the tick count by one, and may persist the new value if the
threshold duration has passed since initialization or the tick count was
last persisted.
|
tick
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/ticker.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/ticker.rb
|
MIT
|
def persist
return if @ticks_recorded == 0
now = Time.now
duration = now - @last_persisted
@last_persisted = now
@persist.call(@ticks_recorded, duration)
@ticks_recorded = 0
end
|
Persists the tick increments by calling the block passed to the
initializer. This is idempotent in the sense that calling it twice in a
row will call the block at most once (if it had been throttled).
|
persist
|
ruby
|
Shopify/maintenance_tasks
|
app/models/maintenance_tasks/ticker.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/models/maintenance_tasks/ticker.rb
|
MIT
|
def validate(record)
return unless (previous_status, new_status = record.status_change)
valid_new_statuses = VALID_STATUS_TRANSITIONS.fetch(previous_status, [])
unless valid_new_statuses.include?(new_status)
add_invalid_status_error(record, previous_status, new_status)
end
end
|
Validate whether a transition from one Run status
to another is acceptable.
@param record [MaintenanceTasks::Run] the Run object being validated.
|
validate
|
ruby
|
Shopify/maintenance_tasks
|
app/validators/maintenance_tasks/run_status_validator.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/app/validators/maintenance_tasks/run_status_validator.rb
|
MIT
|
def up
change_table(:maintenance_tasks_runs) do |t|
t.change(:cursor, :string)
end
end
|
This migration will clear all existing data in the cursor column with MySQL.
Ensure no Tasks are paused when this migration is deployed, or they will be resumed from the start.
Running tasks are able to gracefully handle this change, even if interrupted.
|
up
|
ruby
|
Shopify/maintenance_tasks
|
db/migrate/20210219212931_change_cursor_to_string.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/db/migrate/20210219212931_change_cursor_to_string.rb
|
MIT
|
def mount_engine
route("mount MaintenanceTasks::Engine, at: \"/maintenance_tasks\"")
end
|
Mounts the engine in the host application's config/routes.rb
|
mount_engine
|
ruby
|
Shopify/maintenance_tasks
|
lib/generators/maintenance_tasks/install_generator.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/lib/generators/maintenance_tasks/install_generator.rb
|
MIT
|
def install_migrations
rake("maintenance_tasks:install:migrations")
rake("db:migrate")
end
|
Copies engine migrations to host application and migrates the database
|
install_migrations
|
ruby
|
Shopify/maintenance_tasks
|
lib/generators/maintenance_tasks/install_generator.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/lib/generators/maintenance_tasks/install_generator.rb
|
MIT
|
def create_test_file
return unless test_framework
if test_framework == :rspec
create_task_spec_file
else
create_task_test_file
end
end
|
Creates the Task test file, according to the app's test framework.
A spec file is created if the app uses RSpec.
Otherwise, an ActiveSupport::TestCase test is created.
|
create_test_file
|
ruby
|
Shopify/maintenance_tasks
|
lib/generators/maintenance_tasks/task_generator.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/lib/generators/maintenance_tasks/task_generator.rb
|
MIT
|
def perform(name)
arguments = options[:arguments] || {}
task = Runner.run(name: name, csv_file: csv_file, arguments: arguments)
say_status(:success, "#{task.name} was enqueued.", :green)
rescue => error
say_status(:error, error.message, :red)
end
|
Command to run a Task.
It instantiates a Runner and sends a run message with the given Task name.
If a CSV file is supplied using the --csv option, an attachable with the
File IO object is sent along with the Task name to run. If arguments are
supplied using the --arguments option, these are also passed to run.
@param name [String] the name of the Task to be run.
|
perform
|
ruby
|
Shopify/maintenance_tasks
|
lib/maintenance_tasks/cli.rb
|
https://github.com/Shopify/maintenance_tasks/blob/master/lib/maintenance_tasks/cli.rb
|
MIT
|
def initialize(std_offset, dst_offset, dst_start_rule, dst_end_rule)
@std_offset = std_offset
@dst_offset = dst_offset
@dst_start_rule = dst_start_rule
@dst_end_rule = dst_end_rule
end
|
Initializes a new {AnnualRules} instance.
@param std_offset [TimezoneOffset] the standard offset that applies when
daylight savings time is not in force.
@param dst_offset [TimezoneOffset] the offset that applies when daylight
savings time is in force.
@param dst_start_rule [TransitionRule] the rule that determines when
daylight savings time starts.
@param dst_end_rule [TransitionRule] the rule that determines when daylight
savings time ends.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/annual_rules.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/annual_rules.rb
|
MIT
|
def transitions(year)
start_dst = apply_rule(@dst_start_rule, @std_offset, @dst_offset, year)
end_dst = apply_rule(@dst_end_rule, @dst_offset, @std_offset, year)
end_dst.timestamp_value < start_dst.timestamp_value ? [end_dst, start_dst] : [start_dst, end_dst]
end
|
Returns the transitions between standard and daylight savings time for a
given year. The results are ordered by time of occurrence (earliest to
latest).
@param year [Integer] the year to calculate transitions for.
@return [Array<TimezoneTransition>] the transitions for the year.
|
transitions
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/annual_rules.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/annual_rules.rb
|
MIT
|
def apply_rule(rule, from_offset, to_offset, year)
at = rule.at(from_offset, year)
TimezoneTransition.new(to_offset, from_offset, at.value)
end
|
Applies a given rule between offsets on a year.
@param rule [TransitionRule] the rule to apply.
@param from_offset [TimezoneOffset] the offset the rule transitions from.
@param to_offset [TimezoneOffset] the offset the rule transitions to.
@param year [Integer] the year when the transition occurs.
@return [TimezoneTransition] the transition determined by the rule.
|
apply_rule
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/annual_rules.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/annual_rules.rb
|
MIT
|
def all
data_source.country_codes.collect {|code| get(code)}
end
|
@return [Array<Country>] an `Array` containing one {Country} instance
for each defined country.
|
all
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country.rb
|
MIT
|
def initialize(info)
@info = info
end
|
Initializes a new {Country} based upon a {DataSources::CountryInfo}
instance.
{Country} instances should not normally be constructed directly. Use
the {Country.get} method to obtain instances instead.
@param info [DataSources::CountryInfo] the data to base the new {Country}
instance upon.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country.rb
|
MIT
|
def inspect
"#<#{self.class}: #{@info.code}>"
end
|
@return [String] the internal object state as a programmer-readable
`String`.
|
inspect
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country.rb
|
MIT
|
def eql?(c)
self == c
end
|
@param c [Object] an `Object` to compare this {Country} with.
@return [Boolean] `true` if `c` is an instance of {Country} and has the
same code as `self`, otherwise `false`.
|
eql?
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country.rb
|
MIT
|
def initialize(identifier, latitude, longitude, description = nil)
@identifier = identifier.freeze
@latitude = latitude
@longitude = longitude
@description = description && description.freeze
end
|
Creates a new {CountryTimezone}.
The passed in identifier and description instances will be frozen.
{CountryTimezone} instances should normally only be constructed
by implementations of {DataSource}.
@param identifier [String] the {Timezone} identifier.
@param latitude [Rational] the latitude of the time zone.
@param longitude [Rational] the longitude of the time zone.
@param description [String] an optional description of the time zone.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country_timezone.rb
|
MIT
|
def description_or_friendly_identifier
description || timezone.friendly_identifier(true)
end
|
@return [String] the {description} if present, otherwise a human-readable
representation of the identifier (using {Timezone#friendly_identifier}).
|
description_or_friendly_identifier
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country_timezone.rb
|
MIT
|
def eql?(ct)
self == ct
end
|
Tests if the given object is equal to the current instance (has the same
identifier, latitude, longitude and description).
@param ct [Object] the object to be compared.
@return [Boolean] `true` if `ct` is equal to the current instance.
|
eql?
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country_timezone.rb
|
MIT
|
def hash
[@identifier, @latitude, @longitude, @description].hash
end
|
@return [Integer] a hash based on the {identifier}, {latitude},
{longitude} and {description}.
|
hash
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/country_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/country_timezone.rb
|
MIT
|
def get
# If a DataSource hasn't been manually set when the first request is
# made to obtain a DataSource, then a default data source is created.
#
# This is done at the first request rather than when TZInfo is loaded to
# avoid unnecessary attempts to find a suitable DataSource.
#
# A `Mutex` is used to ensure that only a single default instance is
# created (this avoiding the possibility of retaining two copies of the
# same data in memory).
unless @@instance
@@default_mutex.synchronize do
set(create_default_data_source) unless @@instance
end
end
@@instance
end
|
@return [DataSource] the currently selected source of data.
|
get
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def set(data_source_or_type, *args)
if data_source_or_type.kind_of?(DataSource)
@@instance = data_source_or_type
elsif data_source_or_type == :ruby
@@instance = DataSources::RubyDataSource.new
elsif data_source_or_type == :zoneinfo
@@instance = DataSources::ZoneinfoDataSource.new(*args)
else
raise ArgumentError, 'data_source_or_type must be a DataSource instance or a data source type (:ruby or :zoneinfo)'
end
end
|
Sets the currently selected data source for time zone and country data.
This should usually be set to one of the two standard data source types:
* `:ruby` - read data from the Ruby modules included in the TZInfo::Data
library (tzinfo-data gem).
* `:zoneinfo` - read data from the zoneinfo files included with most
Unix-like operating systems (e.g. in /usr/share/zoneinfo).
To set TZInfo to use one of the standard data source types, call
`TZInfo::DataSource.set`` in one of the following ways:
TZInfo::DataSource.set(:ruby)
TZInfo::DataSource.set(:zoneinfo)
TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir)
TZInfo::DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)
`DataSource.set(:zoneinfo)` will automatically search for the zoneinfo
directory by checking the paths specified in
{DataSources::ZoneinfoDataSource.search_path}.
{DataSources::ZoneinfoDirectoryNotFound} will be raised if no valid
zoneinfo directory could be found.
`DataSource.set(:zoneinfo, zoneinfo_dir)` uses the specified
`zoneinfo_dir` directory as the data source. If the directory is not a
valid zoneinfo directory, a {DataSources::InvalidZoneinfoDirectory}
exception will be raised.
`DataSource.set(:zoneinfo, zoneinfo_dir, iso3166_tab_file)` uses the
specified `zoneinfo_dir` directory as the data source, but loads the
`iso3166.tab` file from the path given by `iso3166_tab_file`. If the
directory is not a valid zoneinfo directory, a
{DataSources::InvalidZoneinfoDirectory} exception will be raised.
Custom data sources can be created by subclassing TZInfo::DataSource and
implementing the following methods:
* {load_timezone_info}
* {data_timezone_identifiers}
* {linked_timezone_identifiers}
* {load_country_info}
* {country_codes}
To have TZInfo use the custom data source, call {DataSource.set},
passing an instance of the custom data source implementation as follows:
TZInfo::DataSource.set(CustomDataSource.new)
Calling {DataSource.set} will only affect instances of {Timezone} and
{Country} obtained with {Timezone.get} and {Country.get} subsequent to
the {DataSource.set} call. Existing {Timezone} and {Country} instances
will be unaffected.
If {DataSource.set} is not called, TZInfo will by default attempt to use
TZInfo::Data as the data source. If TZInfo::Data is not available (i.e.
if `require 'tzinfo/data'` fails), then TZInfo will search for a
zoneinfo directory instead (using the search path specified by
{DataSources::ZoneinfoDataSource.search_path}).
@param data_source_or_type [Object] either `:ruby`, `:zoneinfo` or an
instance of a {DataSource}.
@param args [Array<Object>] when `data_source_or_type` is a symbol,
optional arguments to use when initializing the data source.
@raise [ArgumentError] if `data_source_or_type` is not `:ruby`,
`:zoneinfo` or an instance of {DataSource}.
|
set
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def create_default_data_source
has_tzinfo_data = false
begin
require 'tzinfo/data'
has_tzinfo_data = true
rescue LoadError
end
return DataSources::RubyDataSource.new if has_tzinfo_data
begin
return DataSources::ZoneinfoDataSource.new
rescue DataSources::ZoneinfoDirectoryNotFound
raise DataSourceNotFound, "No source of timezone data could be found.\nPlease refer to https://tzinfo.github.io/datasourcenotfound for help resolving this error."
end
end
|
Creates a {DataSource} instance for use as the default. Used if no
preference has been specified manually.
@return [DataSource] the newly created default {DataSource} instance.
|
create_default_data_source
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def initialize
@timezones = Concurrent::Map.new
end
|
Initializes a new {DataSource} instance. Typically only called via
subclasses of {DataSource}.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def get_timezone_info(identifier)
result = @timezones[identifier]
unless result
# Thread-safety: It is possible that multiple equivalent TimezoneInfo
# instances could be created here in concurrently executing threads. The
# consequences of this are that the data may be loaded more than once
# (depending on the data source). The performance benefit of ensuring
# that only a single instance is created is unlikely to be worth the
# overhead of only allowing one TimezoneInfo to be loaded at a time.
result = load_timezone_info(identifier)
@timezones[result.identifier] = result
end
result
end
|
Returns a {DataSources::TimezoneInfo} instance for the given identifier.
The result will derive from either {DataSources::DataTimezoneInfo} for
time zones that define their own data or {DataSources::LinkedTimezoneInfo}
for links or aliases to other time zones.
{get_timezone_info} calls {load_timezone_info} to create the
{DataSources::TimezoneInfo} instance. The returned instance is cached and
returned in subsequent calls to {get_timezone_info} for the identifier.
@param identifier [String] A time zone identifier.
@return [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo} instance
for a given identifier.
@raise [InvalidTimezoneIdentifier] if the time zone is not found or the
identifier is invalid.
|
get_timezone_info
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def timezone_identifiers
# Thread-safety: It is possible that the value of @timezone_identifiers
# may be calculated multiple times in concurrently executing threads. It
# is not worth the overhead of locking to ensure that
# @timezone_identifiers is only calculated once.
@timezone_identifiers ||= build_timezone_identifiers
end
|
@return [Array<String>] a frozen `Array`` of all the available time zone
identifiers. The identifiers are sorted according to `String#<=>`.
|
timezone_identifiers
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def eager_load!
timezone_identifiers.each {|identifier| load_timezone_info(identifier) }
country_codes.each {|code| load_country_info(code) }
nil
end
|
Loads all timezone and country data into memory.
This may be desirable in production environments to improve copy-on-write
performance and to avoid flushing the constant cache every time a new
timezone or country is loaded from {DataSources::RubyDataSource}.
|
eager_load!
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def to_s
"Default DataSource"
end
|
@return [String] a description of the {DataSource}.
|
to_s
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def validate_timezone_identifier(identifier)
raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.nil? ? 'nil' : identifier}" unless identifier.kind_of?(String)
valid_identifier = try_with_encoding(identifier, timezone_identifier_encoding) {|id| find_timezone_identifier(id) }
return valid_identifier if valid_identifier
raise InvalidTimezoneIdentifier, "Invalid identifier: #{identifier.encode(Encoding::UTF_8)}"
end
|
Checks that the given identifier is a valid time zone identifier (can be
found in the {timezone_identifiers} `Array`). If the identifier is valid,
the `String` instance representing that identifier from
`timezone_identifiers` is returned. Otherwise an
{InvalidTimezoneIdentifier} exception is raised.
@param identifier [String] a time zone identifier to be validated.
@return [String] the `String` instance equivalent to `identifier` from
{timezone_identifiers}.
@raise [InvalidTimezoneIdentifier] if `identifier` was not found in
{timezone_identifiers}.
|
validate_timezone_identifier
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def lookup_country_info(hash, code, encoding = Encoding::UTF_8)
raise InvalidCountryCode, "Invalid country code: #{code.nil? ? 'nil' : code}" unless code.kind_of?(String)
info = try_with_encoding(code, encoding) {|c| hash[c] }
return info if info
raise InvalidCountryCode, "Invalid country code: #{code.encode(Encoding::UTF_8)}"
end
|
Looks up a given code in the given hash of code to
{DataSources::CountryInfo} mappings. If the code is found the
{DataSources::CountryInfo} is returned. Otherwise an {InvalidCountryCode}
exception is raised.
@param hash [String, DataSources::CountryInfo] a mapping from ISO 3166-1
alpha-2 country codes to {DataSources::CountryInfo} instances.
@param code [String] a country code to lookup.
@param encoding [Encoding] the encoding used for the country codes in
`hash`.
@return [DataSources::CountryInfo] the {DataSources::CountryInfo} instance
corresponding to `code`.
@raise [InvalidCountryCode] if `code` was not found in `hash`.
|
lookup_country_info
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def raise_invalid_data_source(method_name)
raise InvalidDataSource, "#{method_name} not defined"
end
|
Raises {InvalidDataSource} to indicate that a method has not been
overridden by a particular data source implementation.
@raise [InvalidDataSource] always.
|
raise_invalid_data_source
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def build_timezone_identifiers
data = data_timezone_identifiers
linked = linked_timezone_identifiers
linked.empty? ? data : (data + linked).sort!.freeze
end
|
Combines {data_timezone_identifiers} and {linked_timezone_identifiers}
to create an `Array` containing all valid time zone identifiers. If
{linked_timezone_identifiers} is empty, the {data_timezone_identifiers}
instance is returned.
The returned `Array` is frozen. The identifiers are sorted according to
`String#<=>`.
@return [Array<String>] an `Array` containing all valid time zone
identifiers.
|
build_timezone_identifiers
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def find_timezone_identifier(identifier)
result = timezone_identifiers.bsearch {|i| i >= identifier }
result == identifier ? result : nil
end
|
If the given `identifier` is contained within the {timezone_identifiers}
`Array`, the `String` instance representing that identifier from
{timezone_identifiers} is returned. Otherwise, `nil` is returned.
@param identifier [String] A time zone identifier to search for.
@return [String] the `String` instance representing `identifier` from
{timezone_identifiers} if found, or `nil` if not found.
:nocov_no_array_bsearch:
|
find_timezone_identifier
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def find_timezone_identifier(identifier)
identifiers = timezone_identifiers
low = 0
high = identifiers.length
while low < high do
mid = (low + high).div(2)
mid_identifier = identifiers[mid]
cmp = mid_identifier <=> identifier
return mid_identifier if cmp == 0
if cmp > 0
high = mid
else
low = mid + 1
end
end
nil
end
|
If the given `identifier` is contained within the {timezone_identifiers}
`Array`, the `String` instance representing that identifier from
{timezone_identifiers} is returned. Otherwise, `nil` is returned.
@param identifier [String] A time zone identifier to search for.
@return [String] the `String` instance representing `identifier` from
{timezone_identifiers} if found, or `nil` if not found.
:nocov_array_bsearch:
|
find_timezone_identifier
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def try_with_encoding(string, encoding)
result = yield string
return result if result
unless encoding == string.encoding
string = string.encode(encoding)
yield string
end
end
|
Tries an operation using `string` directly. If the operation fails, the
string is copied and encoded with `encoding` and the operation is tried
again.
@param string [String] The `String` to perform the operation on.
@param encoding [Encoding] The `Encoding` to use if the initial attempt
fails.
@yield [s] the caller will be yielded to once or twice to attempt the
operation.
@yieldparam s [String] either `string` or an encoded copy of `string`.
@yieldreturn [Object] The result of the operation. Must be truthy if
successful.
@return [Object] the result of the operation or `nil` if the first attempt
fails and `string` is already encoded with `encoding`.
|
try_with_encoding
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/data_source.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/data_source.rb
|
MIT
|
def set_timezone_offset(timezone_offset)
raise ArgumentError, 'timezone_offset must be specified' unless timezone_offset
raise ArgumentError, 'timezone_offset.observed_utc_offset does not match self.utc_offset' if offset * 86400 != timezone_offset.observed_utc_offset
@timezone_offset = timezone_offset
self
end
|
Sets the associated {TimezoneOffset}.
@param timezone_offset [TimezoneOffset] a {TimezoneOffset} valid at the
time and for the offset of this {DateTimeWithOffset}.
@return [DateTimeWithOffset] `self`.
@raise [ArgumentError] if `timezone_offset` is `nil`.
@raise [ArgumentError] if `timezone_offset.observed_utc_offset` does not
equal `self.offset * 86400`.
|
set_timezone_offset
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def to_time
if_timezone_offset(super) do |o,t|
# Ruby 2.4.0 changed the behaviour of to_time so that it preserves the
# offset instead of converting to the system local timezone.
#
# When self has an associated TimezonePeriod, this implementation will
# preserve the offset on all versions of Ruby.
TimeWithOffset.at(t.to_i, t.subsec * 1_000_000).set_timezone_offset(o)
end
end
|
An overridden version of `DateTime#to_time` that, if there is an
associated {TimezoneOffset}, returns a {DateTimeWithOffset} with that
offset.
@return [Time] if there is an associated {TimezoneOffset}, a
{TimeWithOffset} representation of this {DateTimeWithOffset}, otherwise
a `Time` representation.
|
to_time
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def downto(min)
if block_given?
super {|dt| yield dt.clear_timezone_offset }
else
enum = super
enum.each {|dt| dt.clear_timezone_offset }
enum
end
end
|
An overridden version of `DateTime#downto` that clears the associated
{TimezoneOffset} of the returned or yielded instances.
|
downto
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def england
# super doesn't call #new_start on MRI, so each method has to be
# individually overridden.
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
end
|
An overridden version of `DateTime#england` that preserves the associated
{TimezoneOffset}.
@return [DateTime]
|
england
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def gregorian
# super doesn't call #new_start on MRI, so each method has to be
# individually overridden.
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
end
|
An overridden version of `DateTime#gregorian` that preserves the
associated {TimezoneOffset}.
@return [DateTime]
|
gregorian
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def italy
# super doesn't call #new_start on MRI, so each method has to be
# individually overridden.
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
end
|
An overridden version of `DateTime#italy` that preserves the associated
{TimezoneOffset}.
@return [DateTime]
|
italy
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def julian
# super doesn't call #new_start on MRI, so each method has to be
# individually overridden.
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
end
|
An overridden version of `DateTime#julian` that preserves the associated
{TimezoneOffset}.
@return [DateTime]
|
julian
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def new_start(start = Date::ITALY)
if_timezone_offset(super) {|o,dt| dt.set_timezone_offset(o) }
end
|
An overridden version of `DateTime#new_start` that preserves the
associated {TimezoneOffset}.
@return [DateTime]
|
new_start
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def step(limit, step = 1)
if block_given?
super {|dt| yield dt.clear_timezone_offset }
else
enum = super
enum.each {|dt| dt.clear_timezone_offset }
enum
end
end
|
An overridden version of `DateTime#step` that clears the associated
{TimezoneOffset} of the returned or yielded instances.
|
step
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def upto(max)
if block_given?
super {|dt| yield dt.clear_timezone_offset }
else
enum = super
enum.each {|dt| dt.clear_timezone_offset }
enum
end
end
|
An overridden version of `DateTime#upto` that clears the associated
{TimezoneOffset} of the returned or yielded instances.
|
upto
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def clear_timezone_offset
@timezone_offset = nil
self
end
|
Clears the associated {TimezoneOffset}.
@return [DateTimeWithOffset] `self`.
|
clear_timezone_offset
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/datetime_with_offset.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/datetime_with_offset.rb
|
MIT
|
def initialize(info)
super()
@info = info
end
|
Initializes a new {InfoTimezone}.
{InfoTimezone} instances should not normally be created directly. Use
the {Timezone.get} method to obtain {Timezone} instances.
@param info [DataSources::TimezoneInfo] a {DataSources::TimezoneInfo}
instance supplied by a {DataSource} that will be used as the source of
data for this {InfoTimezone}.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/info_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/info_timezone.rb
|
MIT
|
def initialize(info)
super
@linked_timezone = Timezone.get(info.link_to_identifier)
end
|
Initializes a new {LinkedTimezone}.
{LinkedTimezone} instances should not normally be created directly. Use
the {Timezone.get} method to obtain {Timezone} instances.
@param info [DataSources::LinkedTimezoneInfo] a
{DataSources::LinkedTimezoneInfo} instance supplied by a {DataSource}
that will be used as the source of data for this {LinkedTimezone}.
|
initialize
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/linked_timezone.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/linked_timezone.rb
|
MIT
|
def dedupe(string)
return string if string.frozen?
@strings[string]
end
|
@param string [String] the string to deduplicate.
@return [bool] `string` if it is frozen, otherwise a frozen, possibly
pre-existing copy of `string`.
|
dedupe
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/string_deduper.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/string_deduper.rb
|
MIT
|
def dedupe(string)
# String#-@ on Ruby 2.6 will dedupe a frozen non-literal String. Ruby
# 2.5 will just return frozen strings.
#
# The pooled implementation can't tell the difference between frozen
# literals and frozen non-literals, so must always return frozen String
# instances to avoid doing unncessary work when loading format 2
# TZInfo::Data modules.
#
# For compatibility with the pooled implementation, just return frozen
# string instances (acting like Ruby 2.5).
return string if string.frozen?
-string
end
|
@param string [String] the string to deduplicate.
@return [bool] `string` if it is frozen, otherwise a frozen, possibly
pre-existing copy of `string`.
|
dedupe
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/string_deduper.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/string_deduper.rb
|
MIT
|
def create(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, sub_second = 0, utc_offset = nil)
raise ArgumentError, 'year must be an Integer' unless year.kind_of?(Integer)
raise ArgumentError, 'month must be an Integer' unless month.kind_of?(Integer)
raise ArgumentError, 'day must be an Integer' unless day.kind_of?(Integer)
raise ArgumentError, 'hour must be an Integer' unless hour.kind_of?(Integer)
raise ArgumentError, 'minute must be an Integer' unless minute.kind_of?(Integer)
raise ArgumentError, 'second must be an Integer' unless second.kind_of?(Integer)
raise RangeError, 'month must be between 1 and 12' if month < 1 || month > 12
raise RangeError, 'day must be between 1 and 31' if day < 1 || day > 31
raise RangeError, 'hour must be between 0 and 23' if hour < 0 || hour > 23
raise RangeError, 'minute must be between 0 and 59' if minute < 0 || minute > 59
raise RangeError, 'second must be between 0 and 59' if second < 0 || second > 59
# Based on days_from_civil from https://howardhinnant.github.io/date_algorithms.html#days_from_civil
after_february = month > 2
year -= 1 unless after_february
era = year / 400
year_of_era = year - era * 400
day_of_year = (153 * (month + (after_february ? -3 : 9)) + 2) / 5 + day - 1
day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year
days_since_epoch = era * 146097 + day_of_era - 719468
value = ((days_since_epoch * 24 + hour) * 60 + minute) * 60 + second
value -= utc_offset if utc_offset.kind_of?(Integer)
new(value, sub_second, utc_offset)
end
|
Returns a new {Timestamp} representing the (proleptic Gregorian
calendar) date and time specified by the supplied parameters.
If `utc_offset` is `nil`, `:utc` or 0, the date and time parameters will
be interpreted as representing a UTC date and time. Otherwise the date
and time parameters will be interpreted as a local date and time with
the given offset.
@param year [Integer] the year.
@param month [Integer] the month (1-12).
@param day [Integer] the day of the month (1-31).
@param hour [Integer] the hour (0-23).
@param minute [Integer] the minute (0-59).
@param second [Integer] the second (0-59).
@param sub_second [Numeric] the fractional part of the second as either
a `Rational` that is greater than or equal to 0 and less than 1, or
the `Integer` 0.
@param utc_offset [Object] either `nil` for a {Timestamp} without a
specified offset, an offset from UTC specified as an `Integer` number
of seconds or the `Symbol` `:utc`).
@return [Timestamp] a new {Timestamp} representing the specified
(proleptic Gregorian calendar) date and time.
@raise [ArgumentError] if either of `year`, `month`, `day`, `hour`,
`minute`, or `second` is not an `Integer`.
@raise [ArgumentError] if `sub_second` is not a `Rational`, or the
`Integer` 0.
@raise [ArgumentError] if `utc_offset` is not `nil`, not an `Integer`
and not the `Symbol` `:utc`.
@raise [RangeError] if `month` is not between 1 and 12.
@raise [RangeError] if `day` is not between 1 and 31.
@raise [RangeError] if `hour` is not between 0 and 23.
@raise [RangeError] if `minute` is not between 0 and 59.
@raise [RangeError] if `second` is not between 0 and 59.
@raise [RangeError] if `sub_second` is a `Rational` but that is less
than 0 or greater than or equal to 1.
|
create
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def for(value, offset = :preserve)
raise ArgumentError, 'value must be specified' unless value
case offset
when :ignore
ignore_offset = true
target_utc_offset = nil
when :treat_as_utc
ignore_offset = true
target_utc_offset = :utc
when :preserve
ignore_offset = false
target_utc_offset = nil
else
raise ArgumentError, 'offset must be :preserve, :ignore or :treat_as_utc'
end
time_like = false
timestamp = case value
when Time
for_time(value, ignore_offset, target_utc_offset)
when DateTime
for_datetime(value, ignore_offset, target_utc_offset)
when Timestamp
for_timestamp(value, ignore_offset, target_utc_offset)
else
raise ArgumentError, "#{value.class} values are not supported" unless is_time_like?(value)
time_like = true
for_time_like(value, ignore_offset, target_utc_offset)
end
if block_given?
result = yield timestamp
raise ArgumentError, 'block must return a Timestamp' unless result.kind_of?(Timestamp)
case value
when Time
result.to_time
when DateTime
result.to_datetime
else # A Time-like value or a Timestamp
time_like ? result.to_time : result
end
else
timestamp
end
end
|
When used without a block, returns a {Timestamp} representation of a
given `Time`, `DateTime` or {Timestamp}.
When called with a block, the {Timestamp} representation of `value` is
passed to the block. The block must then return a {Timestamp}, which
will be converted back to the type of the initial value. If the initial
value was a {Timestamp}, the block result will be returned. If the
initial value was a `DateTime`, a Gregorian `DateTime` will be returned.
The UTC offset of `value` can either be preserved (the {Timestamp}
representation will have the same UTC offset as `value`), ignored (the
{Timestamp} representation will have no defined UTC offset), or treated
as though it were UTC (the {Timestamp} representation will have a
{utc_offset} of 0 and {utc?} will return `true`).
@param value [Object] a `Time`, `DateTime` or {Timestamp}.
@param offset [Symbol] either `:preserve` to preserve the offset of
`value`, `:ignore` to ignore the offset of `value` and create a
{Timestamp} with an unspecified offset, or `:treat_as_utc` to treat
the offset of `value` as though it were UTC and create a UTC
{Timestamp}.
@yield [timestamp] if a block is provided, the {Timestamp}
representation is passed to the block.
@yieldparam timestamp [Timestamp] the {Timestamp} representation of
`value`.
@yieldreturn [Timestamp] a {Timestamp} to be converted back to the type
of `value`.
@return [Object] if called without a block, the {Timestamp}
representation of `value`, otherwise the result of the block,
converted back to the type of `value`.
|
for
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def utc(value, sub_second = 0)
new(value, sub_second, :utc)
end
|
Creates a new UTC {Timestamp}.
@param value [Integer] the number of seconds since 1970-01-01 00:00:00
UTC ignoring leap seconds.
@param sub_second [Numeric] the fractional part of the second as either
a `Rational` that is greater than or equal to 0 and less than 1, or
the `Integer` 0.
@raise [ArgumentError] if `value` is not an `Integer`.
@raise [ArgumentError] if `sub_second` is not a `Rational`, or the
`Integer` 0.
@raise [RangeError] if `sub_second` is a `Rational` but that is less
than 0 or greater than or equal to 1.
|
utc
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def new!(value, sub_second = 0, utc_offset = nil)
result = allocate
result.send(:initialize!, value, sub_second, utc_offset)
result
end
|
Constructs a new instance of `self` (i.e. {Timestamp} or a subclass of
{Timestamp}) without validating the parameters. This method is used
internally within {Timestamp} to avoid the overhead of checking
parameters.
@param value [Integer] the number of seconds since 1970-01-01 00:00:00
UTC ignoring leap seconds.
@param sub_second [Numeric] the fractional part of the second as either
a `Rational` that is greater than or equal to 0 and less than 1, or
the `Integer` 0.
@param utc_offset [Object] either `nil` for a {Timestamp} without a
specified offset, an offset from UTC specified as an `Integer` number
of seconds or the `Symbol` `:utc`).
@return [Timestamp] a new instance of `self`.
|
new!
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def for_time(time, ignore_offset, target_utc_offset)
value = time.to_i
sub_second = time.subsec
if ignore_offset
utc_offset = target_utc_offset
value += time.utc_offset
elsif time.utc?
utc_offset = :utc
else
utc_offset = time.utc_offset
end
new!(value, sub_second, utc_offset)
end
|
Creates a {Timestamp} that represents a given `Time`, optionally
ignoring the offset.
@param time [Time] a `Time`.
@param ignore_offset [Boolean] whether to ignore the offset of `time`.
@param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
offset of the result (`:utc`, `nil` or an `Integer`).
@return [Timestamp] the {Timestamp} representation of `time`.
|
for_time
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def for_datetime(datetime, ignore_offset, target_utc_offset)
value = (datetime.jd - JD_EPOCH) * 86400 + datetime.sec + datetime.min * 60 + datetime.hour * 3600
sub_second = datetime.sec_fraction
if ignore_offset
utc_offset = target_utc_offset
else
utc_offset = (datetime.offset * 86400).to_i
value -= utc_offset
end
new!(value, sub_second, utc_offset)
end
|
Creates a {Timestamp} that represents a given `DateTime`, optionally
ignoring the offset.
@param datetime [DateTime] a `DateTime`.
@param ignore_offset [Boolean] whether to ignore the offset of
`datetime`.
@param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
offset of the result (`:utc`, `nil` or an `Integer`).
@return [Timestamp] the {Timestamp} representation of `datetime`.
|
for_datetime
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
def for_timestamp(timestamp, ignore_offset, target_utc_offset)
if ignore_offset
if target_utc_offset
unless target_utc_offset == :utc && timestamp.utc? || timestamp.utc_offset == target_utc_offset
return new!(timestamp.value + (timestamp.utc_offset || 0), timestamp.sub_second, target_utc_offset)
end
elsif timestamp.utc_offset
return new!(timestamp.value + timestamp.utc_offset, timestamp.sub_second)
end
end
unless timestamp.instance_of?(Timestamp)
# timestamp is identical in value, sub_second and utc_offset but is a
# subclass (i.e. TimestampWithOffset). Return a new Timestamp
# instance.
return new!(timestamp.value, timestamp.sub_second, timestamp.utc? ? :utc : timestamp.utc_offset)
end
timestamp
end
|
Returns a {Timestamp} that represents another {Timestamp}, optionally
ignoring the offset. If the result would be identical to `value`, the
same instance is returned. If the passed in value is an instance of a
subclass of {Timestamp}, then a new {Timestamp} will always be returned.
@param timestamp [Timestamp] a {Timestamp}.
@param ignore_offset [Boolean] whether to ignore the offset of
`timestamp`.
@param target_utc_offset [Object] if `ignore_offset` is `true`, the UTC
offset of the result (`:utc`, `nil` or an `Integer`).
@return [Timestamp] a [Timestamp] representation of `timestamp`.
|
for_timestamp
|
ruby
|
tzinfo/tzinfo
|
lib/tzinfo/timestamp.rb
|
https://github.com/tzinfo/tzinfo/blob/master/lib/tzinfo/timestamp.rb
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.