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 initialize(name, concurrency: nil, threshold: nil, key_suffix: nil, observer: nil, requeue: nil) # rubocop:disable Metrics/MethodLength, Metrics/ParameterLists
@observer = observer
@concurrency = StrategyCollection.new(concurrency,
strategy: Concurrency,
name: name,
key_suffix: key_suffix)
@threshold = StrategyCollection.new(threshold,
strategy: Threshold,
name: name,
key_suffix: key_suffix)
@requeue_options = Throttled.config.default_requeue_options.merge(requeue || {})
validate!
end | @param [#to_s] name
@param [Hash] concurrency Concurrency options.
See keyword args of {Strategy::Concurrency#initialize} for details.
@param [Hash] threshold Threshold options.
See keyword args of {Strategy::Threshold#initialize} for details.
@param [#call] key_suffix Dynamic key suffix generator.
@param [#call] observer Process called after throttled.
@param [#call] requeue What to do with jobs that are throttled. | initialize | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def dynamic?
return true if @concurrency&.dynamic?
return true if @threshold&.dynamic?
false
end | @return [Boolean] whenever strategy has dynamic config | dynamic? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def throttled?(jid, *job_args)
if @concurrency&.throttled?(jid, *job_args)
@observer&.call(:concurrency, *job_args)
return true
end
if @threshold&.throttled?(*job_args)
@observer&.call(:threshold, *job_args)
finalize!(jid, *job_args)
return true
end
false
end | @return [Boolean] whenever job is throttled or not. | throttled? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def requeue_throttled(work) # rubocop:disable Metrics/MethodLength
# Resolve :with and :to options, calling them if they are Procs
job_args = JSON.parse(work.job)["args"]
with = requeue_with.respond_to?(:call) ? requeue_with.call(*job_args) : requeue_with
target_queue = calc_target_queue(work)
case with
when :enqueue
re_enqueue_throttled(work, target_queue)
when :schedule
# Find out when we will next be able to execute this job, and reschedule for then.
reschedule_throttled(work, target_queue)
else
raise "unrecognized :with option #{with}"
end
end | Return throttled job to be executed later. Implementation depends on the strategy's `requeue` options.
@return [void] | requeue_throttled | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def finalize!(jid, *job_args)
@concurrency&.finalize!(jid, *job_args)
end | Marks job as being processed.
@return [void] | finalize! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def reset!
@concurrency&.reset!
@threshold&.reset!
end | Resets count of jobs of all available strategies
@return [void] | reset! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def re_enqueue_throttled(work, target_queue)
target_queue = "queue:#{target_queue}" unless target_queue.start_with?("queue:")
case work.class.name
when "Sidekiq::Pro::SuperFetch::UnitOfWork"
# Calls SuperFetch UnitOfWork's requeue to remove the job from the
# temporary queue and push job back to the head of the target queue, so that
# the job won't be tried immediately after it was requeued (in most cases).
work.queue = target_queue
work.requeue
else
# This is the same operation Sidekiq performs upon `Sidekiq::Worker.perform_async` call.
Sidekiq.redis { |conn| conn.lpush(target_queue, work.job) }
end
end | Push the job back to the head of the queue.
The queue name is expected to include the "queue:" prefix, so we add it if it's missing. | re_enqueue_throttled | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def reschedule_throttled(work, target_queue)
target_queue = target_queue.delete_prefix("queue:")
message = JSON.parse(work.job)
job_class = message.fetch("wrapped") { message.fetch("class") { return false } }
job_args = message["args"]
# Re-enqueue the job to the target queue at another time as a NEW unit of work
# AND THEN mark this work as done, so SuperFetch doesn't think this instance is orphaned
# Technically, the job could processed twice if the process dies between the two lines,
# but your job should be idempotent anyway, right?
# The job running twice was already a risk with SuperFetch anyway and this doesn't really increase that risk.
Sidekiq::Client.enqueue_to_in(target_queue, retry_in(work), Object.const_get(job_class), *job_args)
work.acknowledge
end | Reschedule the job to be executed later in the target queue.
The queue name should NOT include the "queue:" prefix, so we remove it if it's present. | reschedule_throttled | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy.rb | MIT |
def initialize(strategies, strategy:, name:, key_suffix:)
@strategies = (strategies.is_a?(Hash) ? [strategies] : Array(strategies)).map do |options|
make_strategy(strategy, name, key_suffix, options)
end
end | @param [Hash, Array, nil] strategies Concurrency or Threshold options
or array of options.
See keyword args of {Strategy::Concurrency#initialize} for details.
See keyword args of {Strategy::Threshold#initialize} for details.
@param [Class] strategy class of strategy: Concurrency or Threshold
@param [#to_s] name
@param [#call] key_suffix Dynamic key suffix generator. | initialize | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy_collection.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy_collection.rb | MIT |
def throttled?(...)
any? { |s| s.throttled?(...) }
end | @return [Boolean] whenever job is throttled or not
by any strategy in collection. | throttled? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy_collection.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy_collection.rb | MIT |
def retry_in(*args)
map { |s| s.retry_in(*args) }.max
end | @return [Float] How long, in seconds, before we'll next be able to take on jobs | retry_in | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy_collection.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy_collection.rb | MIT |
def finalize!(...)
each { |c| c.finalize!(...) }
end | Marks job as being processed.
@return [void] | finalize! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy_collection.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy_collection.rb | MIT |
def queues_cmd
throttled_queues = Throttled.cooldown&.queues
return super if throttled_queues.nil? || throttled_queues.empty?
super - throttled_queues
end | Returns list of queues to try to fetch jobs from.
@note It may return an empty array.
@param [Array<String>] queues
@return [Array<String>] | queues_cmd | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/patches/basic_fetch.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/patches/basic_fetch.rb | MIT |
def active_queues
# Create a hash of throttled queues for fast lookup
throttled_queues = Throttled.cooldown&.queues&.to_h { |queue| [queue, true] }
return super if throttled_queues.nil? || throttled_queues.empty?
# Reject throttled queues from the list of active queues
super.reject { |queue, _private_queue| throttled_queues[queue] }
end | Returns list of non-paused queues to try to fetch jobs from.
@note It may return an empty array.
@return [Array<Array(String, String)>] | active_queues | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/patches/super_fetch.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/patches/super_fetch.rb | MIT |
def retrieve_work
work = super
if work && Throttled.throttled?(work.job)
Throttled.cooldown&.notify_throttled(work.queue)
Throttled.requeue_throttled(work)
return nil
end
Throttled.cooldown&.notify_admitted(work.queue) if work
work
end | Retrieves job from redis.
@return [Sidekiq::BasicFetch::UnitOfWork, nil] | retrieve_work | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/patches/throttled_retriever.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/patches/throttled_retriever.rb | MIT |
def dynamic?
@key_suffix || @limit.respond_to?(:call)
end | @return [Boolean] Whenever strategy has dynamic config | dynamic? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def throttled?(jid, *job_args)
job_limit = limit(job_args)
return false unless job_limit
return true if job_limit <= 0
keys = [key(job_args)]
argv = [jid.to_s, job_limit, @ttl, Time.now.to_f]
Sidekiq.redis { |redis| 1 == SCRIPT.call(redis, keys: keys, argv: argv) }
end | @return [Boolean] whenever job is throttled or not | throttled? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def retry_in(_jid, *job_args)
job_limit = limit(job_args)
return 0.0 if !job_limit || count(*job_args) < job_limit
oldest_jid_with_score = Sidekiq.redis { |redis| redis.zrange(key(job_args), 0, 0, withscores: true) }.first
return 0.0 unless oldest_jid_with_score
expiry_time = oldest_jid_with_score.last.to_f
expiry_time - Time.now.to_f
end | @return [Float] How long, in seconds, before we'll next be able to take on jobs | retry_in | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def count(*job_args)
Sidekiq.redis { |conn| conn.zcard(key(job_args)) }.to_i
end | @return [Integer] Current count of jobs | count | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def reset!(*job_args)
Sidekiq.redis { |conn| conn.del(key(job_args)) }
end | Resets count of jobs
@return [void] | reset! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def finalize!(jid, *job_args)
Sidekiq.redis { |conn| conn.zrem(key(job_args), jid.to_s) }
end | Remove jid from the pool of jobs in progress
@return [void] | finalize! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/concurrency.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/concurrency.rb | MIT |
def dynamic?
@key_suffix || @limit.respond_to?(:call) || @period.respond_to?(:call)
end | @return [Boolean] Whenever strategy has dynamic config | dynamic? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/threshold.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/threshold.rb | MIT |
def throttled?(*job_args)
job_limit = limit(job_args)
return false unless job_limit
return true if job_limit <= 0
keys = [key(job_args)]
argv = [job_limit, period(job_args), Time.now.to_f]
Sidekiq.redis { |redis| 1 == SCRIPT.call(redis, keys: keys, argv: argv) }
end | @return [Boolean] whenever job is throttled or not | throttled? | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/threshold.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/threshold.rb | MIT |
def retry_in(*job_args)
job_limit = limit(job_args)
return 0.0 if !job_limit || count(*job_args) < job_limit
job_period = period(job_args)
job_key = key(job_args)
time_since_oldest = Time.now.to_f - Sidekiq.redis { |redis| redis.lindex(job_key, -1) }.to_f
if time_since_oldest > job_period
# The oldest job on our list is from more than the throttling period ago,
# which means we have not hit the limit this period.
0.0
else
# If we can only have X jobs every Y minutes, then wait until Y minutes have elapsed
# since the oldest job on our list.
job_period - time_since_oldest
end
end | @return [Float] How long, in seconds, before we'll next be able to take on jobs | retry_in | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/threshold.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/threshold.rb | MIT |
def count(*job_args)
Sidekiq.redis { |conn| conn.llen(key(job_args)) }.to_i
end | @return [Integer] Current count of jobs | count | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/threshold.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/threshold.rb | MIT |
def reset!(*job_args)
Sidekiq.redis { |conn| conn.del(key(job_args)) }
end | Resets count of jobs
@return [void] | reset! | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/strategy/threshold.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/strategy/threshold.rb | MIT |
def initialize(strategy)
raise ArgumentError, "Can't handle dynamic strategies" if strategy&.dynamic?
@strategy = strategy
end | @param [Strategy::Concurrency, Strategy::Threshold] strategy | initialize | ruby | ixti/sidekiq-throttled | lib/sidekiq/throttled/web/stats.rb | https://github.com/ixti/sidekiq-throttled/blob/master/lib/sidekiq/throttled/web/stats.rb | MIT |
def reset_redis!
if Sidekiq.default_configuration.instance_variable_defined?(:@redis)
existing_pool = Sidekiq.default_configuration.instance_variable_get(:@redis)
existing_pool&.shutdown(&:close)
end
RedisClient.new(url: REDIS_URL).call("flushall")
# After resetting redis, create a new Sidekiq::Config instance to avoid ConnectionPool::PoolShuttingDownError
Sidekiq.instance_variable_set :@config, new_sidekiq_config
new_sidekiq_config
end | https://github.com/sidekiq/sidekiq/blob/7df28434f03fa1111e9e2834271c020205369f94/test/helper.rb#L30 | reset_redis! | ruby | ixti/sidekiq-throttled | spec/support/sidekiq.rb | https://github.com/ixti/sidekiq-throttled/blob/master/spec/support/sidekiq.rb | MIT |
def read_raw_attribute(name)
if name.to_s == self.class.legacy_code_attribute.to_s
if respond_to?(name)
send(name)
else
code
end
elsif name.to_s == 'code'
code
else
super
end
end | TODO: Only for legacy codes, remove after migration | read_raw_attribute | ruby | cenit-io/cenit | app/models/concerns/setup/snippet_code.rb | https://github.com/cenit-io/cenit/blob/master/app/models/concerns/setup/snippet_code.rb | MIT |
def snippet_required?
%w(chain mapping).exclude?(style)
end | TODO Remove when refactoring translators in style models | snippet_required? | ruby | cenit-io/cenit | app/models/setup/converter.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/converter.rb | MIT |
def apply_to_source?(data_type)
source_data_type.blank? || source_data_type == data_type
end | TODO Remove this method if refactored Conversions does not use it | apply_to_source? | ruby | cenit-io/cenit | app/models/setup/converter_transformation.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/converter_transformation.rb | MIT |
def apply_to_target?(data_type)
target_data_type.blank? || target_data_type == data_type
end | TODO Remove this method if refactored Conversions does not use it | apply_to_target? | ruby | cenit-io/cenit | app/models/setup/converter_transformation.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/converter_transformation.rb | MIT |
def process(record)
fail NotImplementedError
end | Virtual abstract method to process a data type record. | process | ruby | cenit-io/cenit | app/models/setup/notification_flow.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/notification_flow.rb | MIT |
def apply_to_target?(data_type)
target_data_type.blank? || target_data_type == data_type
end | TODO Remove this method if refactored Conversions does not use it | apply_to_target? | ruby | cenit-io/cenit | app/models/setup/parser_transformation.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/parser_transformation.rb | MIT |
def apply_to_source?(data_type)
source_data_type.blank? || source_data_type == data_type
end | TODO Remove this method if refactored Conversions does not use it | apply_to_source? | ruby | cenit-io/cenit | app/models/setup/template.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/template.rb | MIT |
def apply_to_target?(data_type)
target_data_type.blank? || target_data_type == data_type
end | TODO Remove this method if refactored Conversions does not use it | apply_to_target? | ruby | cenit-io/cenit | app/models/setup/updater_transformation.rb | https://github.com/cenit-io/cenit/blob/master/app/models/setup/updater_transformation.rb | MIT |
def resolve_name(mod, name)
cls = exc = nil
parts = name.to_s.split('::')
if parts.first == ''
parts.shift
hierarchy = [Object]
else
hierarchy = namespace_hierarchy(mod)
end
hierarchy.each do |ns|
begin
parts.each do |part|
# Simple const_get sometimes pulls names out of weird scopes,
# perhaps confusing the receiver (ns in this case) with the
# local scope. Walk the class hierarchy ourselves one node
# at a time by specifying false as the second argument.
ns = ns.const_get(part, false)
end
cls = ns
break
rescue NameError, LoadError => e
if exc.nil?
exc = e
end
end
end
if cls.nil?
# Raise the first exception, this is from the most specific namespace
raise exc
end
cls
end | TODO Make a pull request with this | resolve_name | ruby | cenit-io/cenit | config/initializers/mongoid_monkey_patch.rb | https://github.com/cenit-io/cenit/blob/master/config/initializers/mongoid_monkey_patch.rb | MIT |
def json_value_of(value)
return value unless value.is_a?(String)
value = value.strip
if value.blank?
nil
elsif value.start_with?('"') && value.end_with?('"')
value[1..value.length - 2]
else
begin
JSON.parse(value)
rescue
if (v = value.to_i).to_s == value
v
elsif (v = value.to_f).to_s == value
v
else
case value
when 'true'
true
when 'false'
false
else
value
end
end
end
end
end | TODO Remove this methods (used by rails_admin custom fields) since blank string are actually valid JSON values | json_value_of | ruby | cenit-io/cenit | lib/cenit/utility.rb | https://github.com/cenit-io/cenit/blob/master/lib/cenit/utility.rb | MIT |
def bucket(file)
unless (_bucket = file.instance_variable_get(:@_aws_s3_bucket))
_bucket = resource.bucket(bucket_name(file))
_bucket.create unless _bucket.exists?
end
_bucket
end | ##
Returns bucket reference for a given file | bucket | ruby | cenit-io/cenit | lib/cenit/file_store/aws_s3_default.rb | https://github.com/cenit-io/cenit/blob/master/lib/cenit/file_store/aws_s3_default.rb | MIT |
def check_type(types, instance, _, _, options, schema)
return if instance.nil? && options[:skip_nulls]
if types
types = [types] unless types.is_a?(Array)
types = types.map(&:to_s).map(&:to_sym)
super_types = types.map do |type|
case type
when :object
if instance.is_a?(Mongoff::Record) && instance.orm_model.modelable?
Mongoff::Record
elsif instance.is_a?(Setup::OrmModelAware)
Setup::OrmModelAware
else
TYPE_MAP[type]
end
when :array
if instance.is_a?(Mongoff::RecordArray) && instance.orm_model.modelable?
Mongoff::RecordArray
elsif instance.is_a?(Mongoid::Association::Referenced::HasMany::Enumerable)
Mongoid::Association::Referenced::HasMany::Enumerable
else
TYPE_MAP[type]
end
when :string
if !instance.is_a?(String) && schema.key?('format')
Object
else
TYPE_MAP[type]
end
else
TYPE_MAP[type]
end
end
unless super_types.any? { |type| instance.is_a?(type) }
msg =
if super_types.length == 1
"of type #{instance.class} is not an instance of type #{types[0]}"
else
"of type #{instance.class} is not an instance of any type #{types.to_sentence}"
end
raise_path_less_error msg
end
else
raise_path_less_error "of type #{instance.class} is not a valid JSON type" unless Cenit::Utility.json_object?(instance)
end
end | Validation Keywords for Any Instance Type | check_type | ruby | cenit-io/cenit | lib/mongoff/validator.rb | https://github.com/cenit-io/cenit/blob/master/lib/mongoff/validator.rb | MIT |
def check_schema_multipleOf(value)
_check_type(:multipleOf, value, Numeric)
raise_path_less_error "Invalid value for multipleOf, strictly greater than zero is expected" unless value.positive?
end | Validation Keywords for Numeric Instances (number and integer) | check_schema_multipleOf | ruby | cenit-io/cenit | lib/mongoff/validator.rb | https://github.com/cenit-io/cenit/blob/master/lib/mongoff/validator.rb | MIT |
def check_schema_items(items_schema)
_check_type(:items, items_schema, Hash, Array)
if items_schema.is_a?(Hash)
begin
validate(items_schema)
rescue Error => ex
raise_path_less_error "Items schema is not valid: #{ex.message}"
end
else # Is an array
errors = {}
items_schema.each_with_index do |item_schema, index|
begin
validate(item_schema)
rescue Error => ex
errors[index] = ex.message
end
end
unless errors.empty?
msg = errors.map do |index, msg|
"item schema ##{index} is not valid (#{msg})"
end.to_sentence.capitalize
raise_path_less_error msg
end
end
end | Keywords for Applying Subschemas to Arrays | check_schema_items | ruby | cenit-io/cenit | lib/mongoff/validator.rb | https://github.com/cenit-io/cenit/blob/master/lib/mongoff/validator.rb | MIT |
def check_schema_required(value)
_check_type(:properties, value, Array, Mongoid::Boolean) # TODO Mongoid::Boolean is only for legacy support
if value.is_a?(Array)
hash = {}
value.each do |property_name|
hash[property_name] = (hash[property_name] || 0) + 1
_check_type('property name', property_name, String)
end
repeated_properties = hash.keys.select { |prop| hash[prop] > 1 }
if repeated_properties.count > 0
raise_path_less_error "Required properties are not unique: #{repeated_properties.to_sentence}"
end
else
Tenant.notify(message: "JSON Schema keyword require is expected to be an Array and does not support #{value.class} values")
end
end | Keywords for Applying Subschemas to Objects | check_schema_required | ruby | cenit-io/cenit | lib/mongoff/validator.rb | https://github.com/cenit-io/cenit/blob/master/lib/mongoff/validator.rb | MIT |
def check_schema_allOf(schemas)
_check_type(:allOf, schemas, Array)
raise_path_less_error 'allOf schemas should not be empty' if schemas.length == 0
schemas.each_with_index do |schema, index|
begin
validate(schema)
rescue Error => ex
raise_path_less_error "allOf schema##{index} is not valid: #{ex.message}"
end
end
end | Keywords for Applying Subschemas With Mongoid::Boolean Logic | check_schema_allOf | ruby | cenit-io/cenit | lib/mongoff/validator.rb | https://github.com/cenit-io/cenit/blob/master/lib/mongoff/validator.rb | MIT |
def remove
if @handle
raise WinApiError, "RemoveDllDirectory failed for #{@path}" if RemoveDllDirectory.call(@handle) == 0
elsif @path
ENV['PATH'] = ENV['PATH'].sub(@path + ";", "")
end
end | This method removes the given directory from the active DLL search paths. | remove | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/dll_directory.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/dll_directory.rb | BSD-3-Clause |
def q(text)
meth = case @co.result_filename
when /\.iss$/ then :q_inno
else raise "can not determine quote rules for #{@co.result_filename}"
end
send(meth, text)
end | Quote a text string with the quotation rules of the resulting files. | q | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/erb_compiler.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/erb_compiler.rb | BSD-3-Clause |
def initialize(erb_file_rel, result_file_rel=nil)
@erb_filename = erb_file_rel
@erb_filename_abs = ovl_expand_file(erb_file_rel)
@erb = ERB.new(File.read(@erb_filename_abs, encoding: "UTF-8"))
@result_file_rel = result_file_rel || erb_file_rel.sub(/\.erb$/, "")
@erb.filename = @result_file_rel
end | Create a new ERB object to process a template.
The ERB template +erb_file_rel+ should be a relative path.
It is either taken from the current directory or, if it doesn't exist, from the gem root directory. | initialize | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/erb_compiler.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/erb_compiler.rb | BSD-3-Clause |
def result(task=nil)
box = Box.new(self, task)
@erb.result(box.binding)
end | Returns the ERB content as String with UTF-8 encoding.
A Box instance is used as binding to process the ERB template.
All method calls are redirected to the +task+ object. | result | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/erb_compiler.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/erb_compiler.rb | BSD-3-Clause |
def write_result(task=nil, filename=nil)
filename ||= result_filename
FileUtils.mkdir_p File.dirname(filename)
File.binwrite(filename, result(task))
filename
end | Write the ERB result to a file in UTF-8 encoding.
See #result
If no file name is given, it is derived from the template file name by cutting the +.erb+ extension.
If the file path contains non-exising directories, they are created. | write_result | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/erb_compiler.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/erb_compiler.rb | BSD-3-Clause |
def enable_msys_apps_per_cmd
vars = with_msys_install_hint{ msys_apps_envvars }
if (path=vars.delete("PATH")) && !ENV['PATH'].include?(path)
vars['PATH'] = path + ";" + ENV['PATH']
end
vars.map do |key, val|
"#{key}=#{val}"
end.join("\n")
end | This method is used for the ridk command. | enable_msys_apps_per_cmd | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/msys2_installation.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/msys2_installation.rb | BSD-3-Clause |
def disable_msys_apps_per_cmd
vars = with_msys_install_hint{ msys_apps_envvars }
str = "".dup
if path=vars.delete("PATH")
str << "PATH=#{ ENV['PATH'].gsub(path + ";", "") }\n"
end
str << vars.map do |key, val|
"#{key}="
end.join("\n")
end | This method is used for the ridk command. | disable_msys_apps_per_cmd | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/msys2_installation.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/msys2_installation.rb | BSD-3-Clause |
def enable_msys_apps_per_ps1
vars = with_msys_install_hint{ msys_apps_envvars }
if (path=vars.delete("PATH")) && !ENV['PATH'].include?(path)
vars['PATH'] = path + ";" + ENV['PATH']
end
vars.map do |key, val|
"$env:#{key}=\"#{val.gsub('"', '`"')}\""
end.join(";")
end | This method is used for the ridk command. | enable_msys_apps_per_ps1 | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/msys2_installation.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/msys2_installation.rb | BSD-3-Clause |
def disable_msys_apps_per_ps1
vars = with_msys_install_hint{ msys_apps_envvars }
str = "".dup
if path=vars.delete("PATH")
str << "$env:PATH=\"#{ ENV['PATH'].gsub(path + ";", "").gsub('"', '`"') }\";"
end
str << vars.map do |key, val|
"$env:#{key}=''"
end.join(";")
end | This method is used for the ridk command. | disable_msys_apps_per_ps1 | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/msys2_installation.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/msys2_installation.rb | BSD-3-Clause |
def add_dll_directory(path, &block)
DllDirectory.new(path, &block)
end | Add +path+ as a search path for DLLs
This can be used to allow ruby extension files (typically named +<extension>.so+ ) to import dependent DLLs from another directory.
The search order of added directories is not defined according to microsoft docs, but practically is the last added directory preferred.
If this method is called with a block, the path is temporary added until the block is finished.
The method returns a DllDirectory instance, when called without a block.
It can be used to remove the directory later. | add_dll_directory | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/singleton.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/singleton.rb | BSD-3-Clause |
def enable_dll_search_paths
ENV['RUBY_DLL_PATH'].to_s.split(File::PATH_SEPARATOR).each do |path|
DllDirectory.new(path) rescue DllDirectory::Error
end
msys2_installation.enable_dll_search_paths
end | Switch to explicit DLL search paths added by add_dll_directory().
Then enable paths set by RUBY_DLL_PATH environment variable and the MSYS2-MINGW directory, if available. | enable_dll_search_paths | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/singleton.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/singleton.rb | BSD-3-Clause |
def rubyinstaller_build_gem_files
spec = Gem.loaded_specs["rubyinstaller-build"]
if spec
# A loaded gemspec has empty #files -> fetch the files from its path.
# This is preferred to gemspec loading to avoid a dependency to git.
Dir["**/*", base: spec.full_gem_path].select do |f|
FileTest.file?(File.join(spec.full_gem_path, f))
end
else
# Not yet loaded -> load the gemspec and return the files added to the gemspec.
Gem::Specification.load(File.join(GEM_ROOT, "rubyinstaller-build.gemspec")).files
end
end | Return the gem files of "rubyinstaller-build"
The gemspec is either already loaded or taken from our root directory. | rubyinstaller_build_gem_files | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def ovl_glob(rel_pattern)
gem_files = Dir.glob(File.join(GEM_ROOT, rel_pattern)).map do |path|
path.sub(GEM_ROOT+"/", "")
end
(gem_files + Dir.glob(rel_pattern)).uniq
end | Scan the current and the gem root directory for files matching +rel_pattern+.
All paths returned are relative. | ovl_glob | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def ovl_expand_file(rel_file)
if File.exist?(rel_file)
File.expand_path(rel_file)
elsif File.exist?(a=File.join(GEM_ROOT, rel_file))
File.expand_path(a)
else
raise Errno::ENOENT, rel_file
end
end | Returns the absolute path of +rel_file+ within the current directory or,
if it doesn't exist, from the gem root directory.
Raises Errno::ENOENT if neither of them exist. | ovl_expand_file | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def ovl_read_file(rel_file)
File.read(ovl_expand_file(rel_file), encoding: "UTF-8")
end | Read +rel_file+ from the current directory or, if it doesn't exist, from the gem root directory.
Raises Errno::ENOENT if neither of them exist.
Returns the file content as String with UTF-8 encoding. | ovl_read_file | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def q_inno(text)
'"' + text.to_s.gsub('"', '""') + '"'
end | Quote a string according to the rules of Inno-Setup | q_inno | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def file(name, *args, &block)
task_once(name, block) do
super(name, *args) do |ta|
block&.call(ta).tap do
raise "file #{ta.name} is missing after task executed" unless File.exist?(ta.name)
end
end
end
end | Extend rake's file task to be defined only once and to check the expected file is indeed generated
The same as #task, but for #file.
In addition this file task raises an error, if the file that is expected to be generated is not present after the block was executed. | file | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def task(name, *args, &block)
task_once(name, block) do
super
end
end | Extend rake's task definition to be defined only once, even if called several times
This allows to define common tasks next to specific tasks.
It is expected that any variation of the task's block is reflected in the task name or namespace.
If the task name is identical, the task block is executed only once, even if the file task definition is executed twice. | task | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/utils.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/utils.rb | BSD-3-Clause |
def shell_escape(str)
str = str.to_s
# An empty argument will be skipped, so return empty quotes.
return '""' if str.empty?
str = str.dup
str.gsub!(/((?:\\)*)"/){ "\\" * ($1.length*2) + "\\\"" }
if str =~ /\s/
str.gsub!(/(\\+)\z/){ "\\" * ($1.length*2) }
str = "\"#{str}\""
end
return str
end | This is extracted from https://github.com/larskanis/shellwords | shell_escape | ruby | oneclick/rubyinstaller2 | lib/ruby_installer/build/components/base.rb | https://github.com/oneclick/rubyinstaller2/blob/master/lib/ruby_installer/build/components/base.rb | BSD-3-Clause |
def operating_system_defaults
defaults = ["--install-dir", Gem.user_dir]
bindir = File.join(Gem.user_home, 'AppData/Local/Microsoft/WindowsApps')
defaults += ["--bindir", bindir] if File.directory?(bindir)
{ 'gem' => defaults }
end | Set default options for the gem command | operating_system_defaults | ruby | oneclick/rubyinstaller2 | resources/files/operating_system.rb | https://github.com/oneclick/rubyinstaller2/blob/master/resources/files/operating_system.rb | BSD-3-Clause |
def test_gem_install
res = system <<-EOT.gsub("\n", "&")
cd test/helper/testgem
gem build testgem.gemspec
gem install testgem-1.0.0.gem --verbose
EOT
assert res, "shell commands should succeed"
out = IO.popen("ruby -rtestgem -e \"puts Libguess.determine_encoding('abc', 'Greek')\"", &:read)
assert_match(/UTF-8/, out.scrub, "call the ruby API of the testgem")
out = RubyInstaller::Runtime.msys2_installation.with_msys_apps_enabled do
IO.popen("ed --version", &:read)
end
assert_match(/GNU ed/, out.scrub, "execute the installed MSYS2 program, requested by the testgem")
out = IO.popen("testgem-exe", &:read)
assert_match(/UTF-8/, out.scrub, "execute the bin file of the testgem")
assert system("gem uninstall testgem --executables --force"), "uninstall testgem"
FileUtils.rm("test/helper/testgem/testgem-1.0.0.gem")
end | Remove installed packages per:
pacman -R %MINGW_PACKAGE_PREFIX%-libmowgli %MINGW_PACKAGE_PREFIX%-libguess ed | test_gem_install | ruby | oneclick/rubyinstaller2 | test/test_gem_install.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_gem_install.rb | BSD-3-Clause |
def test_https_external
uri = URI(EXTERNAL_HTTPS)
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |https|
https.head('/').code
end
assert_equal("200", res)
end | Can we connect to a external host with our default RubyInstaller CA list? | test_https_external | ruby | oneclick/rubyinstaller2 | test/test_ssl_cacerts.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_ssl_cacerts.rb | BSD-3-Clause |
def test_SSL_CERT_FILE
if ENV['SSL_CERT_FILE']
# Connect per system CA list (overwritten per SSL_CERT_FILE)
sclient = connect_ssl_client("localhost", 23456)
res = read_and_close_ssl(sclient, "hello client->server")
assert_equal "hello server->client", res
else
server = TCPServer.new "localhost", 23456
server_th = Thread.new do
sserver = run_ssl_server(server, pki)
read_and_close_ssl(sserver, "hello server->client")
end
Tempfile.open(["cert", ".pem"]) do |fd|
fd.write pki.ca_cert.to_pem
fd.close
ENV['SSL_CERT_FILE'] = fd.path
cmd = ["ruby", __FILE__, "-n", __method__.to_s]
res = IO.popen(cmd, &:read)
assert_equal 0, $?.exitstatus, "res #{cmd.join(" ")} failed: #{res}"
ENV.delete('SSL_CERT_FILE')
end
assert_equal "hello client->server", server_th.value
end
end | Can CA certificates overwritten per SSL_CERT_FILE environment variable? | test_SSL_CERT_FILE | ruby | oneclick/rubyinstaller2 | test/test_ssl_cacerts.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_ssl_cacerts.rb | BSD-3-Clause |
def test_ssl_certs_dir
certfile = "#{RbConfig::TOPDIR}/ssl/certs/#{pki.ca_cert.subject.hash.to_s(16)}.0"
File.write(certfile, pki.ca_cert.to_pem)
server = TCPServer.new "localhost", 0
server_th = Thread.new do
run_ssl_server(server, pki)
end
# Connect per system CA list (with addition of our certificate)
sclient = connect_ssl_client("localhost", server.local_address.ip_port)
assert_ssl_connection_is_usable(server_th.value, sclient)
File.unlink(certfile)
end | Can CA certificates added into C:/Ruby32/ssl/certs/<hash>.0 ? | test_ssl_certs_dir | ruby | oneclick/rubyinstaller2 | test/test_ssl_cacerts.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_ssl_cacerts.rb | BSD-3-Clause |
def test_gmp
assert_match(/GMP \d/, Integer::GMP_VERSION)
end | Make sure ruby is linked to libgmp | test_gmp | ruby | oneclick/rubyinstaller2 | test/test_stdlib.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_stdlib.rb | BSD-3-Clause |
def test_openssl_version
require "openssl"
case RUBY_VERSION
when /^2\.[34]\./
assert_match(/OpenSSL 1\.0\./, OpenSSL::OPENSSL_VERSION)
assert_match(/OpenSSL 1\.0\./, OpenSSL::OPENSSL_LIBRARY_VERSION)
when /^2\.[567]\.|^3\.[01]\./
assert_match(/OpenSSL 1\.1\./, OpenSSL::OPENSSL_VERSION)
assert_match(/OpenSSL 1\.1\./, OpenSSL::OPENSSL_LIBRARY_VERSION)
else
assert_match(/OpenSSL 3\./, OpenSSL::OPENSSL_VERSION)
assert_match(/OpenSSL 3\./, OpenSSL::OPENSSL_LIBRARY_VERSION)
end
end | Make sure we're using the expected OpenSSL version | test_openssl_version | ruby | oneclick/rubyinstaller2 | test/test_stdlib.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/test_stdlib.rb | BSD-3-Clause |
def test_enable_msys_apps_with_msys_installed
skip unless File.directory?(msys_path)
RubyInstaller::Runtime.disable_msys_apps
refute_operator ENV['PATH'].downcase, :include?, msys_path, "msys in the path at the start of the test"
out, _err = capture_subprocess_io do
system("touch", "--version")
end
refute_match(/GNU coreutils/, out, "touch.exe shoudn't be in the path after disable_msys_apps")
RubyInstaller::Runtime.enable_msys_apps
assert_operator ENV['PATH'].downcase, :include?, msys_path, "msys should be in the path after enable_msys_apps"
assert_equal msys_path, ENV['RI_DEVKIT'].downcase, "enable_msys_apps should set RI_DEVKIT"
msystem = case RUBY_PLATFORM
when "x64-mingw32" then "MINGW64"
when "x64-mingw-ucrt" then "UCRT64"
when "i386-mingw32" then "MINGW32"
end
assert_equal msystem, ENV['MSYSTEM'], "enable_msys_apps should set MSYSTEM according to RUBY_PLATFORM"
assert_match(/./, ENV['LANG'], "enable_msys_apps should set LANG")
out, _err = capture_subprocess_io do
system("touch", "--version")
end
assert_match(/GNU coreutils/, out, "touch.exe shoud be found after enable_msys_apps")
RubyInstaller::Runtime.disable_msys_apps
refute_operator ENV['PATH'].downcase, :include?, msys_path, "no msys in the path after disable_msys_apps"
assert_nil ENV['RI_DEVKIT']
assert_nil ENV['MSYSTEM']
end | The following tests require that MSYS2 is installed on c:/msys64 per MSYS2-installer. | test_enable_msys_apps_with_msys_installed | ruby | oneclick/rubyinstaller2 | test/ruby_installer/test_module.rb | https://github.com/oneclick/rubyinstaller2/blob/master/test/ruby_installer/test_module.rb | BSD-3-Clause |
def sign!(request, access_id, secret_key, options = {})
options = { override_http_method: nil, digest: 'sha1' }.merge(options)
headers = Headers.new(request)
headers.calculate_hash
headers.set_date
headers.sign_header auth_header(headers, access_id, secret_key, options)
end | Signs an HTTP request using the client's access id and secret key.
Returns the HTTP request object with the modified headers.
request: The request can be a Net::HTTP, ActionDispatch::Request,
Curb (Curl::Easy), RestClient object or Faraday::Request.
access_id: The public unique identifier for the client
secret_key: assigned secret key that is known to both parties | sign! | ruby | mgomes/api_auth | lib/api_auth/base.rb | https://github.com/mgomes/api_auth/blob/master/lib/api_auth/base.rb | MIT |
def authentic?(request, secret_key, options = {})
return false if secret_key.nil?
options = { override_http_method: nil, authorize_md5: false }.merge(options)
headers = Headers.new(request, authorize_md5: options[:authorize_md5])
# 900 seconds is 15 minutes
clock_skew = options.fetch(:clock_skew, 900)
if headers.content_hash_mismatch?
false
elsif !signatures_match?(headers, secret_key, options)
false
elsif !request_within_time_window?(headers, clock_skew)
false
else
true
end
end | Determines if the request is authentic given the request and the client's
secret key. Returns true if the request is authentic and false otherwise. | authentic? | ruby | mgomes/api_auth | lib/api_auth/base.rb | https://github.com/mgomes/api_auth/blob/master/lib/api_auth/base.rb | MIT |
def access_id(request)
headers = Headers.new(request)
if match_data = parse_auth_header(headers.authorization_header)
return match_data[2]
end
nil
end | Returns the access id from the request's authorization header | access_id | ruby | mgomes/api_auth | lib/api_auth/base.rb | https://github.com/mgomes/api_auth/blob/master/lib/api_auth/base.rb | MIT |
def generate_secret_key
random_bytes = OpenSSL::Random.random_bytes(512)
b64_encode(Digest::SHA2.new(512).digest(random_bytes))
end | Generates a Base64 encoded, randomized secret key
Store this key along with the access key that will be used for
authenticating the client | generate_secret_key | ruby | mgomes/api_auth | lib/api_auth/base.rb | https://github.com/mgomes/api_auth/blob/master/lib/api_auth/base.rb | MIT |
def sign_header(header)
@request.set_auth_header header
end | Sets the request's authorization header with the passed in value.
The header should be the ApiAuth HMAC signature.
This will return the original request object with the signed Authorization
header already in place. | sign_header | ruby | mgomes/api_auth | lib/api_auth/headers.rb | https://github.com/mgomes/api_auth/blob/master/lib/api_auth/headers.rb | MIT |
def functions
@functions ||= @api_info.fetch("functions").inject({}) do |acc, func|
function = Function.new(func)
acc.merge(function.name => function)
end
end | Return all functions defined by the API. | functions | ruby | neovim/neovim-ruby | lib/neovim/api.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/api.rb | MIT |
def types
@types ||= @api_info.fetch("types")
end | Return information about +nvim+ types. Used for registering MessagePack
+ext+ types. | types | ruby | neovim/neovim-ruby | lib/neovim/api.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/api.rb | MIT |
def inspect
format("#<#{self.class}:0x%x @channel_id=#{@channel_id.inspect}>", object_id << 1)
end | Truncate the output of inspect so console sessions are more pleasant. | inspect | ruby | neovim/neovim-ruby | lib/neovim/api.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/api.rb | MIT |
def call(session, *args)
session.request(name, *args)
end | Apply this function to a running RPC session. | call | ruby | neovim/neovim-ruby | lib/neovim/api.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/api.rb | MIT |
def delete(index)
check_index(index, 1)
@lines.delete(index - 1)
nil
end | Delete the given line (1-indexed).
@param index [Integer]
@return [void] | delete | ruby | neovim/neovim-ruby | lib/neovim/buffer.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/buffer.rb | MIT |
def append(index, str)
check_index(index, 0)
window = @session.request(:nvim_get_current_win)
cursor = window.cursor
set_lines(index, index, true, [*str.split($/)])
window.set_cursor(cursor)
str
end | Append a line after the given line (1-indexed).
Unlike the other methods, `0` is a valid index argument here, and inserts
into the first line of the buffer.
To maintain backwards compatibility with +vim+, the cursor is forced back
to its previous position after inserting the line.
@param index [Integer]
@param str [String]
@return [String] | append | ruby | neovim/neovim-ruby | lib/neovim/buffer.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/buffer.rb | MIT |
def line
@session.request(:nvim_get_current_line) if active?
end | Get the current line of an active buffer.
@return [String, nil] | line | ruby | neovim/neovim-ruby | lib/neovim/buffer.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/buffer.rb | MIT |
def line_number
@session.request(:nvim_get_current_win).get_cursor[0] if active?
end | Get the current line number of an active buffer.
@return [Integer, nil] | line_number | ruby | neovim/neovim-ruby | lib/neovim/buffer.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/buffer.rb | MIT |
def active?
@session.request(:nvim_get_current_buf) == self
end | Determine if the buffer is active.
@return [Boolean] | active? | ruby | neovim/neovim-ruby | lib/neovim/buffer.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/buffer.rb | MIT |
def method_missing(method_name, *args)
if (func = @api.function_for_object_method(self, method_name))
func.call(@session, *args)
else
super
end
end | Intercept method calls and delegate to appropriate RPC methods. | method_missing | ruby | neovim/neovim-ruby | lib/neovim/client.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/client.rb | MIT |
def methods(*args)
super | rpc_methods.to_a
end | Extend +methods+ to include RPC methods. | methods | ruby | neovim/neovim-ruby | lib/neovim/client.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/client.rb | MIT |
def current
@current ||= Current.new(@session)
end | Access to objects belonging to the current +nvim+ context.
@return [Current]
@example Get the current buffer
client.current.buffer
@example Set the current line
client.current.line = "New line"
@see Current | current | ruby | neovim/neovim-ruby | lib/neovim/client.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/client.rb | MIT |
def evaluate(expr)
@api.function_for_object_method(self, :eval).call(@session, expr)
end | Evaluate the VimL expression (alias for +nvim_eval+).
@param expr [String] A VimL expression.
@return [Object]
@example Return a list from VimL
client.evaluate('[1, 2]') # => [1, 2] | evaluate | ruby | neovim/neovim-ruby | lib/neovim/client.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/client.rb | MIT |
def set_option(*args)
if args.size > 1
@api.function_for_object_method(self, :set_option).call(@session, *args)
else
@api.function_for_object_method(self, :command).call(@session, "set #{args.first}")
end
end | Set an option.
@overload set_option(key, value)
@param [String] key
@param [String] value
@overload set_option(optstr)
@param [String] optstr
@example Set the +timeoutlen+ option
client.set_option("timeoutlen", 0)
client.set_option("timeoutlen=0") | set_option | ruby | neovim/neovim-ruby | lib/neovim/client.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/client.rb | MIT |
def version
@version ||= IO.popen([@path, "--version"]) do |io|
io.gets[VERSION_PATTERN, 1]
end
rescue => e
raise Error, "Couldn't load #{@path}: #{e}"
end | Fetch the +nvim+ version.
@return [String] | version | ruby | neovim/neovim-ruby | lib/neovim/executable.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/executable.rb | MIT |
def each(&block)
([email protected]).each_slice(5000) do |linenos|
start, stop = linenos[0], linenos[-1] + 1
@buffer.get_lines(start, stop, true).each(&block)
end
end | Satisfy the +Enumerable+ interface by yielding each line.
@yieldparam line [String] | each | ruby | neovim/neovim-ruby | lib/neovim/line_range.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/line_range.rb | MIT |
def to_a
map { |line| line }
end | Resolve to an array of lines as strings.
@return [Array<String>] | to_a | ruby | neovim/neovim-ruby | lib/neovim/line_range.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/line_range.rb | MIT |
def replace(other)
self[0..-1] = other.to_ary
self
end | Replace the range of lines.
@param other [Array] The replacement lines | replace | ruby | neovim/neovim-ruby | lib/neovim/line_range.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/line_range.rb | MIT |
def delete(index)
i = Integer(index)
self[i].tap { self[i, 1] = [] }
rescue TypeError
end | Delete the line at the given index within the range.
@param index [Integer] | delete | ruby | neovim/neovim-ruby | lib/neovim/line_range.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/line_range.rb | MIT |
def method_missing(method_name, *args)
if (func = @api.function_for_object_method(self, method_name))
func.call(@session, @index, *args)
else
super
end
end | Intercept method calls and delegate to appropriate RPC methods. | method_missing | ruby | neovim/neovim-ruby | lib/neovim/remote_object.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/remote_object.rb | MIT |
def methods(*args)
super | rpc_methods.to_a
end | Extend +methods+ to include RPC methods | methods | ruby | neovim/neovim-ruby | lib/neovim/remote_object.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/remote_object.rb | MIT |
def request(method, *args)
main_thread_only do
@request_id += 1
blocking = Fiber.current == @main_fiber
log(:debug) do
{
method_name: method,
request_id: @request_id,
blocking: blocking,
arguments: args
}
end
@event_loop.request(@request_id, method, *args)
response = blocking ? blocking_response : yielding_response
raise(Disconnected) if response.nil?
raise(response.error) if response.error
response.value
end
end | Make an RPC request and return its response.
If this method is called inside a callback, we are already inside a
+Fiber+ handler. In that case, we write to the stream and yield the
+Fiber+. Once the response is received, resume the +Fiber+ and
return the result.
If this method is called outside a callback, write to the stream and
run the event loop until a response is received. Messages received
in the meantime are enqueued to be handled later. | request | ruby | neovim/neovim-ruby | lib/neovim/session.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/session.rb | MIT |
def command(name, options={}, &block)
register_handler(:command, name, options, block)
end | Register an +nvim+ command. See +:h command+.
@param name [String] The name of the command.
@param options [Hash] Command options.
@param &block [Proc, nil] The body of the command.
@option options [Integer] :nargs The number of arguments to accept. See
+:h command-nargs+.
@option options [String, Boolean] :range The range argument.
See +:h command-range+.
@option options [Integer] :count The default count argument.
See +:h command-count+.
@option options [Boolean] :bang Whether the command can take a +!+
modifier. See +:h command-bang+.
@option options [Boolean] :register Whether the command can accept a
register name. See +:h command-register+.
@option options [String] :complete Set the completion attributes of the
command. See +:h command-completion+.
@option options [String] :eval An +nvim+ expression. Gets evaluated and
passed as an argument to the block.
@option options [Boolean] :sync (false) Whether +nvim+ should receive
the return value of the block. | command | ruby | neovim/neovim-ruby | lib/neovim/plugin/dsl.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/plugin/dsl.rb | MIT |
def function(name, options={}, &block)
register_handler(:function, name, options, block)
end | Register an +nvim+ function. See +:h function+.
@param name [String] The name of the function.
@param options [Hash] Function options.
@param &block [Proc, nil] The body of the function.
@option options [String, Boolean] :range The range argument.
See +:h func-range+.
@option options [String] :eval An +nvim+ expression. Gets evaluated and
passed as an argument to the block.
@option options [Boolean] :sync (false) Whether +nvim+ should receive
the return value of the block. | function | ruby | neovim/neovim-ruby | lib/neovim/plugin/dsl.rb | https://github.com/neovim/neovim-ruby/blob/master/lib/neovim/plugin/dsl.rb | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.