Dataset Viewer
Auto-converted to Parquet
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 exact_match?(arguments, keyword_arguments) definition.exact_match?(arguments, keyword_arguments) end
Double#exact_match? returns true when the passed in arguments exactly match the ArgumentEqualityExpectation arguments.
exact_match?
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def wildcard_match?(arguments, keyword_arguments) definition.wildcard_match?(arguments, keyword_arguments) end
Double#wildcard_match? returns true when the passed in arguments wildcard match the ArgumentEqualityExpectation arguments.
wildcard_match?
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def attempt? verify_times_matcher_is_set times_called_expectation.attempt? end
Double#attempt? returns true when the TimesCalledExpectation is satisfied.
attempt?
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def verify verify_times_matcher_is_set times_called_expectation.verify! true end
Double#verify verifies the the TimesCalledExpectation is satisfied for this double. A TimesCalledError is raised if the TimesCalledExpectation is not met.
verify
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def expected_arguments verify_argument_expectation_is_set argument_expectation.expected_arguments end
The Arguments that this Double expects
expected_arguments
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def expected_keyword_arguments verify_argument_expectation_is_set argument_expectation.expected_keyword_arguments end
The keyword arguments that this Double expects
expected_keyword_arguments
ruby
rr/rr
lib/rr/double.rb
https://github.com/rr/rr/blob/master/lib/rr/double.rb
MIT
def satisfy(expectation_proc=nil, &block) expectation_proc ||= block RR::WildcardMatchers::Satisfy.new(expectation_proc) end
Sets up a Satisfy wildcard ArgumentEqualityExpectation that succeeds when the passed argument causes the expectation's proc to return true. mock(object).method_name(satisfy {|arg| arg == :foo}) {return_value} object.method_name(:foo) # passes
satisfy
ruby
rr/rr
lib/rr/dsl.rb
https://github.com/rr/rr/blob/master/lib/rr/dsl.rb
MIT
def register_ordered_double(double) @ordered_doubles << double unless ordered_doubles.include?(double) end
Registers the ordered Double to be verified.
register_ordered_double
ruby
rr/rr
lib/rr/space.rb
https://github.com/rr/rr/blob/master/lib/rr/space.rb
MIT
def verify_ordered_double(double) unless double.terminal? raise RR::Errors.build_error(:DoubleOrderError, "Ordered Doubles cannot have a NonTerminal TimesCalledExpectation") end unless @ordered_doubles.first == double message = Double.formatted_name(double.method_name, double.expected_arguments) message << " called out of order in list\n" message << Double.list_message_part(@ordered_doubles) raise RR::Errors.build_error(:DoubleOrderError, message) end @ordered_doubles.shift unless double.attempt? double end
Verifies that the passed in ordered Double is being called in the correct position.
verify_ordered_double
ruby
rr/rr
lib/rr/space.rb
https://github.com/rr/rr/blob/master/lib/rr/space.rb
MIT
def reset RR.trim_backtrace = false RR.overridden_error_class = nil reset_ordered_doubles Injections::DoubleInjection.reset reset_method_missing_injections reset_singleton_method_added_injections reset_recorded_calls reset_bound_objects end
Resets the registered Doubles and ordered Doubles
reset
ruby
rr/rr
lib/rr/space.rb
https://github.com/rr/rr/blob/master/lib/rr/space.rb
MIT
def verify_double(subject, method_name) Injections::DoubleInjection.verify_double(class << subject; self; end, method_name) end
Verifies the DoubleInjection for the passed in subject and method_name.
verify_double
ruby
rr/rr
lib/rr/space.rb
https://github.com/rr/rr/blob/master/lib/rr/space.rb
MIT
def reset_double(subject, method_name) Injections::DoubleInjection.reset_double(class << subject; self; end, method_name) end
Resets the DoubleInjection for the passed in subject and method_name.
reset_double
ruby
rr/rr
lib/rr/space.rb
https://github.com/rr/rr/blob/master/lib/rr/space.rb
MIT
def with(*args, **kwargs, &return_value_block) @argument_expectation = Expectations::ArgumentEqualityExpectation.new(args, kwargs) install_method_callback return_value_block self end
Double#with sets the expectation that the Double will receive the passed in arguments. Passing in a block sets the return value. mock(subject).method_name.with(1, 2) {:return_value}
with
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def with_any_args(&return_value_block) @argument_expectation = Expectations::AnyArgumentExpectation.new install_method_callback return_value_block self end
Double#with_any_args sets the expectation that the Double can receive any arguments. Passing in a block sets the return value. mock(subject).method_name.with_any_args {:return_value}
with_any_args
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def with_no_args(&return_value_block) @argument_expectation = Expectations::ArgumentEqualityExpectation.new([], {}) install_method_callback return_value_block self end
Double#with_no_args sets the expectation that the Double will receive no arguments. Passing in a block sets the return value. mock(subject).method_name.with_no_args {:return_value}
with_no_args
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def never @times_matcher = TimesCalledMatchers::NeverMatcher.new self end
Double#never sets the expectation that the Double will never be called. This method does not accept a block because it will never be called. mock(subject).method_name.never
never
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def once(&return_value_block) @times_matcher = TimesCalledMatchers::IntegerMatcher.new(1) install_method_callback return_value_block self end
Double#once sets the expectation that the Double will be called 1 time. Passing in a block sets the return value. mock(subject).method_name.once {:return_value}
once
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def twice(&return_value_block) @times_matcher = TimesCalledMatchers::IntegerMatcher.new(2) install_method_callback return_value_block self end
Double#twice sets the expectation that the Double will be called 2 times. Passing in a block sets the return value. mock(subject).method_name.twice {:return_value}
twice
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def at_least(number, &return_value_block) @times_matcher = TimesCalledMatchers::AtLeastMatcher.new(number) install_method_callback return_value_block self end
Double#at_least sets the expectation that the Double will be called at least n times. It works by creating a TimesCalledExpectation. Passing in a block sets the return value. mock(subject).method_name.at_least(4) {:return_value}
at_least
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def at_most(number, &return_value_block) @times_matcher = TimesCalledMatchers::AtMostMatcher.new(number) install_method_callback return_value_block self end
Double#at_most allows sets the expectation that the Double will be called at most n times. It works by creating a TimesCalledExpectation. Passing in a block sets the return value. mock(subject).method_name.at_most(4) {:return_value}
at_most
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def any_number_of_times(&return_value_block) @times_matcher = TimesCalledMatchers::AnyTimesMatcher.new install_method_callback return_value_block self end
Double#any_number_of_times sets an that the Double will be called any number of times. This effectively removes the times called expectation from the Doublen Passing in a block sets the return value. mock(subject).method_name.any_number_of_times
any_number_of_times
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def times(matcher_value, &return_value_block) @times_matcher = TimesCalledMatchers::TimesCalledMatcher.create(matcher_value) install_method_callback return_value_block self end
Double#times creates an TimesCalledExpectation of the passed in number. Passing in a block sets the return value. mock(subject).method_name.times(4) {:return_value}
times
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def ordered(&return_value_block) raise( Errors::DoubleDefinitionError, "Double Definitions must have a dedicated Double to be ordered. " << "For example, using instance_of does not allow ordered to be used. " << "proxy the class's #new method instead." ) unless @double @ordered = true space.register_ordered_double(@double) install_method_callback return_value_block DoubleDefinitionCreateBlankSlate.new(double_definition_create) end
Double#ordered sets the Double to have an ordered expectation. Passing in a block sets the return value. mock(subject).method_name.ordered {return_value}
ordered
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def yields(*args, &return_value_block) @yields_value = args install_method_callback return_value_block self end
Double#yields sets the Double to invoke a passed in block when the Double is called. An Expection will be raised if no block is passed in when the Double is called. Passing in a block sets the return value. mock(subject).method_name.yields(yield_arg1, yield_arg2) {return_value} subject.method_name {|yield_arg1, yield_arg2|}
yields
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def after_call(&after_call_proc) raise ArgumentError, "after_call expects a block" unless after_call_proc @after_call_proc = after_call_proc self end
Double#after_call creates a callback that occurs after call is called. The passed in block receives the return value of the Double being called. An Expection will be raised if no block is passed in. mock(subject).method_name {return_value}.after_call {|return_value|} subject.method_name # return_value This feature is built into proxies. mock.proxy(User).find('1') {|user| mock(user).valid? {false}}
after_call
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def verbose(&after_call_proc) @verbose = true @after_call_proc = after_call_proc self end
Double#verbose sets the Double to print out each method call it receives. Passing in a block sets the return value
verbose
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def returns(*args, &implementation) if !args.empty? && implementation raise ArgumentError, "returns cannot accept both an argument and a block" end if implementation install_method_callback implementation else install_method_callback(lambda do |*lambda_args| args.first end) end self end
Double#returns accepts an argument value or a block. It will raise an ArgumentError if both are passed in. Passing in a block causes Double to return the return value of the passed in block. Passing in an argument causes Double to return the argument.
returns
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def implemented_by(implementation) @implementation = implementation self end
Double#implemented_by sets the implementation of the Double. This method takes a Proc or a Method. Passing in a Method allows the Double to accept blocks. obj = Object.new def obj.foobar yield(1) end mock(obj).method_name.implemented_by(obj.method(:foobar))
implemented_by
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def verbose? @verbose ? true : false end
Double#verbose? returns true when verbose has been called on it. It returns true when the double is set to print each method call it receives.
verbose?
ruby
rr/rr
lib/rr/double_definitions/double_definition.rb
https://github.com/rr/rr/blob/master/lib/rr/double_definitions/double_definition.rb
MIT
def verify_double(subject_class, method_name) Injections::DoubleInjection.find(subject_class, method_name).verify ensure reset_double subject_class, method_name end
Verifies the DoubleInjection for the passed in subject and method_name.
verify_double
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def reset_double(subject_class, method_name) double_injection = Injections::DoubleInjection.instances[subject_class].delete(method_name) double_injection.reset Injections::DoubleInjection.instances.delete(subject_class) if Injections::DoubleInjection.instances[subject_class].empty? end
Resets the DoubleInjection for the passed in subject and method_name.
reset_double
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def register_double(double) @doubles << double end
RR::DoubleInjection#register_double adds the passed in Double into this DoubleInjection's list of Double objects.
register_double
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def bind if subject_has_method_defined?(method_name) if subject_has_original_method? bind_method else bind_method_with_alias end else Injections::MethodMissingInjection.find_or_create(subject_class) Injections::SingletonMethodAddedInjection.find_or_create(subject_class) bind_method_that_self_destructs_and_delegates_to_method_missing end self end
RR::DoubleInjection#bind injects a method that acts as a dispatcher that dispatches to the matching Double when the method is called.
bind
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def verify @doubles.each do |double| double.verify end end
RR::DoubleInjection#verify verifies each Double TimesCalledExpectation are met.
verify
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def reset if subject_has_original_method? subject_class.__send__(:remove_method, method_name) subject_class.__send__(:alias_method, method_name, original_method_alias_name) subject_class.__send__(:remove_method, original_method_alias_name) else if subject_has_method_defined?(method_name) subject_class.__send__(:remove_method, method_name) end end end
RR::DoubleInjection#reset removes the injected dispatcher method. It binds the original method implementation on the subject if one exists.
reset
ruby
rr/rr
lib/rr/injections/double_injection.rb
https://github.com/rr/rr/blob/master/lib/rr/injections/double_injection.rb
MIT
def from_installed_gems(*deprecated) if deprecated.empty? from_gems_in(*installed_spec_directories) else from_gems_in(*deprecated) # HACK warn end end
# Factory method to construct a source index instance for a given path. deprecated:: If supplied, from_installed_gems will act just like +from_gems_in+. This argument is deprecated and is provided just for backwards compatibility, and should not generally be used. return:: SourceIndex instance
from_installed_gems
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def installed_spec_directories Gem.path.collect { |dir| File.join(dir, "specifications") } end
# Returns a list of directories from Gem.path that contain specifications.
installed_spec_directories
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def from_gems_in(*spec_dirs) source_index = new source_index.spec_dirs = spec_dirs source_index.refresh! end
# Creates a new SourceIndex from the ruby format gem specifications in +spec_dirs+.
from_gems_in
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def load_specification(file_name) return nil unless file_name and File.exist? file_name spec_code = if defined? Encoding then File.read file_name, :encoding => 'UTF-8' else File.read file_name end.untaint begin gemspec = eval spec_code, binding, file_name if gemspec.is_a?(Gem::Specification) gemspec.loaded_from = file_name return gemspec end alert_warning "File '#{file_name}' does not evaluate to a gem specification" rescue SignalException, SystemExit raise rescue SyntaxError => e alert_warning e alert_warning spec_code rescue Exception => e alert_warning "#{e.inspect}\n#{spec_code}" alert_warning "Invalid .gemspec format in '#{file_name}'" end return nil end
# Loads a ruby-format specification from +file_name+ and returns the loaded spec.
load_specification
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def initialize(specifications={}) @gems = {} specifications.each{ |full_name, spec| add_spec spec } @spec_dirs = nil end
# Constructs a source index instance from the provided specifications, which is a Hash of gem full names and Gem::Specifications. -- TODO merge @gems and @prerelease_gems and provide a separate method #prerelease_gems
initialize
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def load_gems_in(*spec_dirs) @gems.clear spec_dirs.reverse_each do |spec_dir| spec_files = Dir.glob File.join(spec_dir, '*.gemspec') spec_files.each do |spec_file| gemspec = self.class.load_specification spec_file.untaint add_spec gemspec if gemspec end end self end
# Reconstruct the source index from the specifications in +spec_dirs+.
load_gems_in
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def latest_specs result = Hash.new { |h,k| h[k] = [] } latest = {} sort.each do |_, spec| name = spec.name curr_ver = spec.version prev_ver = latest.key?(name) ? latest[name].version : nil next if curr_ver.prerelease? next unless prev_ver.nil? or curr_ver >= prev_ver or latest[name].platform != Gem::Platform::RUBY if prev_ver.nil? or (curr_ver > prev_ver and spec.platform == Gem::Platform::RUBY) then result[name].clear latest[name] = spec end if spec.platform != Gem::Platform::RUBY then result[name].delete_if do |result_spec| result_spec.platform == spec.platform end end result[name] << spec end # TODO: why is this a hash while @gems is an array? Seems like # structural similarity would be good. result.values.flatten end
# Returns an Array specifications for the latest released versions of each gem in this index.
latest_specs
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def add_spec(gem_spec, name = gem_spec.full_name) # No idea why, but the Indexer wants to insert them using original_name # instead of full_name. So we make it an optional arg. @gems[name] = gem_spec end
# Add a gem specification to the source index.
add_spec
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def add_specs(*gem_specs) gem_specs.each do |spec| add_spec spec end end
# Add gem specifications to the source index.
add_specs
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def index_signature require 'digest' Digest::SHA256.new.hexdigest(@gems.keys.sort.join(',')).to_s end
# The signature for the source index. Changes in the signature indicate a change in the index.
index_signature
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def gem_signature(gem_full_name) require 'digest' Digest::SHA256.new.hexdigest(@gems[gem_full_name].to_yaml).to_s end
# The signature for the given gem specification.
gem_signature
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def find_name(gem_name, version_requirement = Gem::Requirement.default) dep = Gem::Dependency.new gem_name, version_requirement search dep end
# Find a gem by an exact match on the short name.
find_name
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def search(gem_pattern, platform_only = false) version_requirement = nil only_platform = false # TODO - Remove support and warning for legacy arguments after 2008/11 unless Gem::Dependency === gem_pattern warn "#{Gem.location_of_caller.join ':'}:Warning: Gem::SourceIndex#search support for #{gem_pattern.class} patterns is deprecated, use #find_name" end case gem_pattern when Regexp then version_requirement = platform_only || Gem::Requirement.default when Gem::Dependency then only_platform = platform_only version_requirement = gem_pattern.requirement gem_pattern = if Regexp === gem_pattern.name then gem_pattern.name elsif gem_pattern.name.empty? then // else /^#{Regexp.escape gem_pattern.name}$/ end else version_requirement = platform_only || Gem::Requirement.default gem_pattern = /#{gem_pattern}/i end unless Gem::Requirement === version_requirement then version_requirement = Gem::Requirement.create version_requirement end specs = all_gems.values.select do |spec| spec.name =~ gem_pattern and version_requirement.satisfied_by? spec.version end if only_platform then specs = specs.select do |spec| Gem::Platform.match spec.platform end end specs.sort_by { |s| s.sort_obj } end
# Search for a gem by Gem::Dependency +gem_pattern+. If +only_platform+ is true, only gems matching Gem::Platform.local will be returned. An Array of matching Gem::Specification objects is returned. For backwards compatibility, a String or Regexp pattern may be passed as +gem_pattern+, and a Gem::Requirement for +platform_only+. This behavior is deprecated and will be removed.
search
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def refresh! raise 'source index not created from disk' if @spec_dirs.nil? load_gems_in(*@spec_dirs) end
# Replaces the gems in the source index from specifications in the directories this source index was created from. Raises an exception if this source index wasn't created from a directory (via from_gems_in or from_installed_gems, or having spec_dirs set).
refresh!
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def outdated outdateds = [] latest_specs.each do |local| dependency = Gem::Dependency.new local.name, ">= #{local.version}" begin fetcher = Gem::SpecFetcher.fetcher remotes = fetcher.find_matching dependency remotes = remotes.map { |(name, version,_),_| version } rescue Gem::RemoteFetcher::FetchError => e raise unless fetcher.warn_legacy e do require 'rubygems/source_info_cache' specs = Gem::SourceInfoCache.search_with_source dependency, true remotes = specs.map { |spec,| spec.version } end end latest = remotes.sort.last outdateds << local.name if latest and local.version < latest end outdateds end
# Returns an Array of Gem::Specifications that are not up to date.
outdated
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def update(source_uri, all) source_uri = URI.parse source_uri unless URI::Generic === source_uri source_uri.path += '/' unless source_uri.path =~ /\/$/ use_incremental = false begin gem_names = fetch_quick_index source_uri, all remove_extra gem_names missing_gems = find_missing gem_names return false if missing_gems.size.zero? say "Missing metadata for #{missing_gems.size} gems" if missing_gems.size > 0 and Gem.configuration.really_verbose use_incremental = missing_gems.size <= Gem.configuration.bulk_threshold rescue Gem::OperationNotSupportedError => ex alert_error "Falling back to bulk fetch: #{ex.message}" if Gem.configuration.really_verbose use_incremental = false end if use_incremental then update_with_missing(source_uri, missing_gems) else new_index = fetch_bulk_index(source_uri) @gems.replace(new_index.gems) end true end
# Updates this SourceIndex from +source_uri+. If +all+ is false, only the latest gems are fetched.
update
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def fetch_quick_index(source_uri, all) index = all ? 'index' : 'latest_index' zipped_index = fetcher.fetch_path source_uri + "quick/#{index}.rz" unzip(zipped_index).split("\n") rescue ::Exception => e unless all then say "Latest index not found, using quick index" if Gem.configuration.really_verbose fetch_quick_index source_uri, true else raise Gem::OperationNotSupportedError, "No quick index found: #{e.message}" end end
# Get the quick index needed for incremental updates.
fetch_quick_index
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def find_missing(spec_names) unless defined? @originals then @originals = {} each do |full_name, spec| @originals[spec.original_name] = spec end end spec_names.find_all { |full_name| @originals[full_name].nil? } end
# Make a list of full names for all the missing gemspecs.
find_missing
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def fetch_single_spec(source_uri, spec_name) @fetch_error = nil begin marshal_uri = source_uri + "quick/Marshal.#{Gem.marshal_version}/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path marshal_uri return Marshal.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch marshal gemspec #{marshal_uri}: #{ex.class} - #{ex}" end end begin yaml_uri = source_uri + "quick/#{spec_name}.gemspec.rz" zipped = fetcher.fetch_path yaml_uri return YAML.load(unzip(zipped)) rescue => ex @fetch_error = ex if Gem.configuration.really_verbose then say "unable to fetch YAML gemspec #{yaml_uri}: #{ex.class} - #{ex}" end end nil end
# Tries to fetch Marshal representation first, then YAML
fetch_single_spec
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def update_with_missing(source_uri, missing_names) progress = ui.progress_reporter(missing_names.size, "Updating metadata for #{missing_names.size} gems from #{source_uri}") missing_names.each do |spec_name| gemspec = fetch_single_spec(source_uri, spec_name) if gemspec.nil? then ui.say "Failed to download spec #{spec_name} from #{source_uri}:\n" \ "\t#{@fetch_error.message}" else add_spec gemspec progress.updated spec_name end @fetch_error = nil end progress.done progress.count end
# Update the cached source index with the missing names.
update_with_missing
ruby
rr/rr
spec/fixtures/rubygems_patch_for_187.rb
https://github.com/rr/rr/blob/master/spec/fixtures/rubygems_patch_for_187.rb
MIT
def add_working_test_case_with_adapter_tests add_working_test_case do |test_case| test_case.add_to_before_tests <<-EOT include AdapterTests::RSpec EOT yield test_case if block_given? end end
XXX: Do we need this if this is already in RSpecTestCase?
add_working_test_case_with_adapter_tests
ruby
rr/rr
spec/support/test_file/rspec.rb
https://github.com/rr/rr/blob/master/spec/support/test_file/rspec.rb
MIT
def add_working_test_case_with_adapter_tests add_working_test_case do |test_case| test_case.add_to_before_tests <<-EOT include AdapterTests::TestUnit EOT yield test_case if block_given? end end
XXX: Do we need this if this is already in TestUnitTestCase?
add_working_test_case_with_adapter_tests
ruby
rr/rr
spec/support/test_file/test_unit.rb
https://github.com/rr/rr/blob/master/spec/support/test_file/test_unit.rb
MIT
def join_association(table, association, join_type = Arel::Nodes::InnerJoin, options = {}, &block) if version >= "7.2.0" join_association_7_2_0(table, association, join_type, options, &block) elsif version >= '6.1.0' join_association_6_1_0(table, association, join_type, options, &block) elsif version >= '6.0.0' join_association_6_0_0(table, association, join_type, options, &block) elsif version >= '5.2.1' join_association_5_2_1(table, association, join_type, options, &block) elsif version >= '5.2.0' join_association_5_2(table, association, join_type, options, &block) elsif version >= '5.0.0' join_association_5_0(table, association, join_type, options, &block) elsif version >= '4.2.0' join_association_4_2(table, association, join_type, options, &block) elsif version >= '4.1.0' join_association_4_1(table, association, join_type, options, &block) else join_association_3_1(table, association, join_type, options, &block) end end
activerecord uses JoinDependency to automagically generate inner join statements for any type of association (belongs_to, has_many, and has_and_belongs_to_many). For example, for HABTM associations, two join statements are required. This method encapsulates that functionality and yields an intermediate object for chaining. It also allows you to use an outer join instead of the default inner via the join_type arg.
join_association
ruby
camertron/arel-helpers
lib/arel-helpers/join_association.rb
https://github.com/camertron/arel-helpers/blob/master/lib/arel-helpers/join_association.rb
MIT
def join_association_4_2(table, association, join_type, options = {}) aliases = options.fetch(:aliases, []).index_by(&:table_name) associations = association.is_a?(Array) ? association : [association] join_dependency = ActiveRecord::Associations::JoinDependency.new(table, associations, []) constraints = join_dependency.join_constraints([]) binds = constraints.flat_map do |info| info.binds.map { |bv| table.connection.quote(*bv.reverse) } end joins = constraints.flat_map do |constraint| constraint.joins.map do |join| right = if block_given? yield join.left.name.to_sym, join.right else join.right end join.left.table_alias = aliases[join.left.name].name if aliases.key?(join.left.name) join_type.new(join.left, right) end end join_strings = joins.map do |join| to_sql(join, table, binds) end join_strings.join(' ') end
ActiveRecord 4.2 moves bind variables out of the join classes and into the relation. For this reason, a method like join_association isn't able to add to the list of bind variables dynamically. To get around the problem, this method must return a string.
join_association_4_2
ruby
camertron/arel-helpers
lib/arel-helpers/join_association.rb
https://github.com/camertron/arel-helpers/blob/master/lib/arel-helpers/join_association.rb
MIT
def directory return environment if environment? return xdg if xdg? return home if home? # No project directory specified or existent, default to XDG: FileUtils::mkdir_p(xdg) xdg end
The directory (created if needed) in which to store new projects
directory
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def xdg XDG["CONFIG"].to_s + "/tmuxinator" end
~/.config/tmuxinator unless $XDG_CONFIG_HOME has been configured to use a custom value. (e.g. if $XDG_CONFIG_HOME is set to ~/my-config, the return value will be ~/my-config/tmuxinator)
xdg
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def global_project(name) project_in(environment, name) || project_in(xdg, name) || project_in(home, name) end
Pathname of given project searching only global directories
global_project
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def active_sessions `tmux list-sessions -F "#S"`.split("\n") end
List of all active tmux sessions
active_sessions
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def configs(active: nil) configs = config_file_basenames if active == true configs &= active_sessions elsif active == false configs -= active_sessions end configs end
Sorted list of all project file basenames, including duplicates. @param active filter configs by active project sessions @return [Array<String>] list of project names
configs
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def config_file_basenames directories.flat_map do |directory| Dir["#{directory}/**/*.yml"].map do |path| path.gsub("#{directory}/", "").gsub(".yml", "") end end.sort end
List the names of all config files relative to the config directory. If sub-folders are used, those are part of the name too. Example: $CONFIG_DIR/project.yml -> project $CONFIG_DIR/sub/project.yml -> sub/project $HOME_CONFIG_DIR/project.yml -> project @return [Array<String] a list of config file names
config_file_basenames
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def directories if environment? [environment] else [xdg, home].select { |d| File.directory? d } end end
Existent directories which may contain project files Listed in search order Used by `implode` and `list` commands
directories
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def project_in(directory, name) return nil if String(directory).empty? projects = Dir.glob("#{directory}/**/*.{yml,yaml}").sort projects.detect { |project| File.basename(project, ".*") == name } end
The first pathname of the project named 'name' found while recursively searching 'directory'
project_in
ruby
tmuxinator/tmuxinator
lib/tmuxinator/config.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/config.rb
MIT
def root return _project_root unless _yaml_root File.expand_path(_yaml_root, _project_root).shellescape end
The expanded, joined window root path Relative paths are joined to the project root
root
ruby
tmuxinator/tmuxinator
lib/tmuxinator/window.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/window.rb
MIT
def hook_on_project_start # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_start" end
Commands specified in this hook run when "tmuxinator start project" command is issued
hook_on_project_start
ruby
tmuxinator/tmuxinator
lib/tmuxinator/hooks/project.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/hooks/project.rb
MIT
def hook_on_project_first_start # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_first_start" end
Commands specified in this hook run when "tmuxinator start project" command is issued and there is no tmux session available named "project"
hook_on_project_first_start
ruby
tmuxinator/tmuxinator
lib/tmuxinator/hooks/project.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/hooks/project.rb
MIT
def hook_on_project_restart # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_restart" end
Commands specified in this hook run when "tmuxinator start project" command is issued and there is no tmux session available named "project"
hook_on_project_restart
ruby
tmuxinator/tmuxinator
lib/tmuxinator/hooks/project.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/hooks/project.rb
MIT
def hook_on_project_exit # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_exit" end
Commands specified in this hook run when you exit from a project ( aka detach from a tmux session )
hook_on_project_exit
ruby
tmuxinator/tmuxinator
lib/tmuxinator/hooks/project.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/hooks/project.rb
MIT
def hook_on_project_stop # this method can only be used from inside Tmuxinator::Project Tmuxinator::Hooks.commands_from self, "on_project_stop" end
Command specified in this hook run when "tmuxinator stop project" command is issued
hook_on_project_stop
ruby
tmuxinator/tmuxinator
lib/tmuxinator/hooks/project.rb
https://github.com/tmuxinator/tmuxinator/blob/master/lib/tmuxinator/hooks/project.rb
MIT
def nginx_custom_configuration(app_info) empty_conf = { "before_server" => "", "server_main" => "", "server_app" => "", "server_ssl" => "", "server_ssl_app" => "", "upstream" => "", "after_server" => "", } empty_conf.merge(app_info["nginx_custom"] || {}) end
# Create a default set of custom config Assure we always send certain hash keys to the template
nginx_custom_configuration
ruby
intercity/chef-repo
vendor/cookbooks/rails/libraries/default.rb
https://github.com/intercity/chef-repo/blob/master/vendor/cookbooks/rails/libraries/default.rb
MIT
def affected_rows(*args, &blk) execute(false) do |conn| conn.send(:affected_rows, *args, &blk) end end
via method_missing affected_rows will be recognized as async method
affected_rows
ruby
igrigorik/em-synchrony
lib/em-synchrony/activerecord.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/activerecord.rb
MIT
def execute(async) f = Fiber.current begin conn = acquire(f) yield conn ensure release(f) if not async end end
Choose first available connection and pass it to the supplied block. This will block indefinitely until there is an available connection to service the request.
execute
ruby
igrigorik/em-synchrony
lib/em-synchrony/connection_pool.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/connection_pool.rb
MIT
def pool_status { available: @available.size, reserved: @reserved.size, pending: @pending.size } end
Returns current pool utilization. @return [Hash] Current utilization.
pool_status
ruby
igrigorik/em-synchrony
lib/em-synchrony/connection_pool.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/connection_pool.rb
MIT
def acquire(fiber) if conn = @available.pop @reserved[fiber.object_id] = conn conn else Fiber.yield @pending.push fiber acquire(fiber) end end
Acquire a lock on a connection and assign it to executing fiber - if connection is available, pass it back to the calling block - if pool is full, yield the current fiber until connection is available
acquire
ruby
igrigorik/em-synchrony
lib/em-synchrony/connection_pool.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/connection_pool.rb
MIT
def release(fiber) @available.push(@reserved.delete(fiber.object_id)) if pending = @pending.shift pending.resume end end
Release connection assigned to the supplied fiber and resume any other pending connections (which will immediately try to run acquire on the pool)
release
ruby
igrigorik/em-synchrony
lib/em-synchrony/connection_pool.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/connection_pool.rb
MIT
def method_missing(method, *args, &blk) async = (method[0,1] == "a") execute(async) do |conn| df = conn.__send__(method, *args, &blk) if async fiber = Fiber.current df.callback { release(fiber) } df.errback { release(fiber) } end df end end
Allow the pool to behave as the underlying connection If the requesting method begins with "a" prefix, then hijack the callbacks and errbacks to fire a connection pool release whenever the request is complete. Otherwise yield the connection within execute method and release once it is complete (assumption: fiber will yield until data is available, or request is complete)
method_missing
ruby
igrigorik/em-synchrony
lib/em-synchrony/connection_pool.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/connection_pool.rb
MIT
def afind_one(spec_or_object_id=nil, opts={}) spec = case spec_or_object_id when nil {} when BSON::ObjectId {:_id => spec_or_object_id} when Hash spec_or_object_id else raise TypeError, "spec_or_object_id must be an instance of ObjectId or Hash, or nil" end afind(spec, opts.merge(:limit => -1)).next_document end
need to rewrite afind_one manually, as it calls 'find' (reasonably expecting it to be what is now known as 'afind')
afind_one
ruby
igrigorik/em-synchrony
lib/em-synchrony/em-mongo.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/em-mongo.rb
MIT
def afirst(selector={}, opts={}, &blk) opts[:limit] = 1 afind(selector, opts) do |res| yield res.first end end
need to rewrite afirst manually, as it calls 'find' (reasonably expecting it to be what is now known as 'afind')
afirst
ruby
igrigorik/em-synchrony
lib/em-synchrony/em-mongo.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/em-mongo.rb
MIT
def amapped_mget(*keys) self.amget(*keys) do |response| result = {} response.each do |value| key = keys.shift result.merge!(key => value) unless value.nil? end yield result if block_given? end end
adapted from em-redis' implementation to use the asynchronous version of mget
amapped_mget
ruby
igrigorik/em-synchrony
lib/em-synchrony/em-redis.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/em-redis.rb
MIT
def each(foreach=nil, after=nil, &blk) fe = Proc.new do |obj, iter| Fiber.new { (foreach || blk).call(obj, iter); iter.next }.resume end super(fe, after) end
execute each iterator block within its own fiber and auto-advance the iterator after each call
each
ruby
igrigorik/em-synchrony
lib/em-synchrony/fiber_iterator.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/fiber_iterator.rb
MIT
def each(foreach=nil, after=nil, &blk) fiber = Fiber.current fe = (foreach || blk) cb = Proc.new do after.call if after fiber.resume end Fiber.yield super(fe, cb) end
synchronous iterator which will wait until all the jobs are done before returning. Unfortunately this means that you loose ability to choose concurrency on the fly (see iterator documentation in EM)
each
ruby
igrigorik/em-synchrony
lib/em-synchrony/iterator.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/iterator.rb
MIT
def sync(direction) req = self.instance_variable_set "@#{direction.to_s}_req", EventMachine::DefaultDeferrable.new EventMachine::Synchrony.sync req ensure self.instance_variable_set "@#{direction.to_s}_req", nil end
direction must be one of :in or :out
sync
ruby
igrigorik/em-synchrony
lib/em-synchrony/tcpsocket.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/tcpsocket.rb
MIT
def unbind(reason) @unbind_reason = reason @remote_closed = true unless @closed if @opening @in_req.fail nil if @in_req else @in_req.succeed read_data if @in_req end @out_req.fail nil if @out_req @in_req = @out_req = nil end
Can't set a default value for reason (e.g. reason=nil), as in that case EM fails to pass in the reason argument and you'll always get the default value.
unbind
ruby
igrigorik/em-synchrony
lib/em-synchrony/tcpsocket.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/tcpsocket.rb
MIT
def wait(mutex, timeout=nil) current = Fiber.current pair = [mutex, current] @waiters << pair mutex.sleep timeout do @waiters.delete pair end self end
Releases the lock held in +mutex+ and waits; reacquires the lock on wakeup. If +timeout+ is given, this method returns after +timeout+ seconds passed, even if no other thread doesn't signal.
wait
ruby
igrigorik/em-synchrony
lib/em-synchrony/thread.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/thread.rb
MIT
def signal while (pair = @waiters.shift) break if _wakeup(*pair) end self end
Wakes up the first thread in line waiting for this lock.
signal
ruby
igrigorik/em-synchrony
lib/em-synchrony/thread.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/thread.rb
MIT
def broadcast @waiters.each do |mutex, fiber| _wakeup(mutex, fiber) end @waiters.clear self end
Wakes up all threads waiting for this lock.
broadcast
ruby
igrigorik/em-synchrony
lib/em-synchrony/thread.rb
https://github.com/igrigorik/em-synchrony/blob/master/lib/em-synchrony/thread.rb
MIT
def formatted_json if @options.jsonl @resources.map { |r| JSON.generate(r) }.join("\n") else @resources.to_json end end
Format @resources as either JSON or JSONL
formatted_json
ruby
joshlarsen/aws-recon
lib/aws_recon/aws_recon.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/aws_recon.rb
MIT
def collect resources = [] # # list_projects # @client.list_projects.each_with_index do |response, page| log(response.context.operation_name, page) # batch_get_projects response.projects.each do |project_name| @client.batch_get_projects({ names: [project_name] }).projects.each do |project| struct = OpenStruct.new(project.to_h) struct.type = 'project' resources.push(struct.to_h) end end end resources end
Returns an array of resources. TODO: group projects in chucks to minimize batch_get calls
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/codebuild.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/codebuild.rb
MIT
def collect resources = [] # # describe_directories # @client.describe_directories.each_with_index do |response, page| log(response.context.operation_name, page) response.directory_descriptions.each do |directory| struct = OpenStruct.new(directory.to_h) struct.type = 'directory' struct.arn = "arn:aws:#{@service}:#{@region}::directory/#{directory.directory_id}" resources.push(struct.to_h) end end resources end
Returns an array of resources. TODO: confirm paging behavior
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/directoryservice.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/directoryservice.rb
MIT
def collect resources = [] # # list_delivery_streams # @client.list_delivery_streams.each_with_index do |response, page| log(response.context.operation_name, page) # describe_delivery_stream response.delivery_stream_names.each do |stream| struct = OpenStruct.new(@client.describe_delivery_stream({ delivery_stream_name: stream }).delivery_stream_description.to_h) struct.type = 'stream' struct.arn = struct.delivery_stream_arn resources.push(struct.to_h) end end resources end
Returns an array of resources. TODO: test live TODO: confirm paging behavior
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/firehose.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/firehose.rb
MIT
def collect resources = [] # # list_clusters # @client.list_clusters.each_with_index do |response, page| log(response.context.operation_name, page) response.cluster_info_list.each do |cluster| struct = OpenStruct.new(cluster.to_h) struct.type = 'cluster' struct.arn = cluster.cluster_arn resources.push(struct.to_h) end end resources end
Returns an array of resources. TODO: test live
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/kafka.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/kafka.rb
MIT
def collect resources = [] # # describe_db_clusters # @client.describe_db_clusters.each_with_index do |response, page| log(response.context.operation_name, page) response.db_clusters.each do |cluster| log(response.context.operation_name, cluster.db_cluster_identifier) struct = OpenStruct.new(cluster.to_h) struct.type = 'db_cluster' struct.arn = cluster.db_cluster_arn resources.push(struct.to_h) end end # # describe_db_instances # @client.describe_db_instances.each_with_index do |response, page| log(response.context.operation_name, page) response.db_instances.each do |instance| log(response.context.operation_name, instance.db_instance_identifier) struct = OpenStruct.new(instance.to_h) struct.type = 'db_instance' struct.arn = instance.db_instance_arn struct.parent_id = instance.db_cluster_identifier # TODO: describe_db_snapshots here (with public flag) resources.push(struct.to_h) end end # # describe_db_snapshots # @client.describe_db_snapshots.each_with_index do |response, page| log(response.context.operation_name, page) response.db_snapshots.each do |snapshot| log(response.context.operation_name, snapshot.db_snapshot_identifier) struct = OpenStruct.new(snapshot.to_h) struct.type = 'db_snapshot' struct.arn = snapshot.db_snapshot_arn struct.parent_id = snapshot.db_instance_identifier resources.push(struct.to_h) end end # # describe_db_cluster_snapshots # @client.describe_db_cluster_snapshots.each_with_index do |response, page| log(response.context.operation_name, page) response.db_cluster_snapshots.each do |snapshot| log(response.context.operation_name, snapshot.db_cluster_snapshot_identifier) struct = OpenStruct.new(snapshot.to_h) struct.type = 'db_cluster_snapshot' struct.arn = snapshot.db_cluster_snapshot_arn struct.parent_id = snapshot.db_cluster_identifier resources.push(struct.to_h) end end # # describe_db_engine_versions # ### unless @options.skip_slow ### @client.describe_db_engine_versions.each_with_index do |response, page| ### log(response.context.operation_name, page) ### response.db_engine_versions.each do |version| ### struct = OpenStruct.new(version.to_h) ### struct.type = 'db_engine_version' ### resources.push(struct.to_h) ### end ### end ### end resources end
Returns an array of resources. describe_db_engine_versions is skipped with @options.skip_slow
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/rds.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/rds.rb
MIT
def collect resources = [] # # list_buckets # @client.list_buckets.each_with_index do |response, page| log(response.context.operation_name, page) Parallel.map(response.buckets.each, in_threads: @options.threads) do |bucket| @thread = Parallel.worker_number log(response.context.operation_name, bucket.name) struct = OpenStruct.new(bucket) struct.type = 'bucket' struct.arn = "arn:aws:s3:::#{bucket.name}" # check bucket region constraint location = @client.get_bucket_location({ bucket: bucket.name }).location_constraint # if you use a region other than the us-east-1 endpoint # to create a bucket, you must set the location_constraint # bucket parameter to the same region. (https://docs.aws.amazon.com/general/latest/gr/s3.html) client = if location.empty? struct.location = 'us-east-1' @client else location = 'eu-west-1' if location == 'EU' struct.location = location Aws::S3::Client.new({ region: location }) end operations = [ { func: 'get_bucket_acl', key: 'acl', field: nil }, { func: 'get_bucket_encryption', key: 'encryption', field: 'server_side_encryption_configuration' }, { func: 'get_bucket_replication', key: 'replication', field: 'replication_configuration' }, { func: 'get_bucket_policy', key: 'policy', field: 'policy' }, { func: 'get_bucket_policy_status', key: 'public', field: 'policy_status' }, { func: 'get_public_access_block', key: 'public_access_block', field: 'public_access_block_configuration' }, { func: 'get_object_lock_configuration', key: 'object_lock_configuration', field: 'object_lock_configuration' }, { func: 'get_bucket_tagging', key: 'tagging', field: nil }, { func: 'get_bucket_logging', key: 'logging', field: 'logging_enabled' }, { func: 'get_bucket_versioning', key: 'versioning', field: nil }, { func: 'get_bucket_website', key: 'website', field: nil }, { func: 'get_bucket_ownership_controls', key: 'ownership_controls', field: 'ownership_controls' } ] operations.each do |operation| op = OpenStruct.new(operation) resp = client.send(op.func, { bucket: bucket.name }) struct[op.key] = if op.key == 'policy' resp.policy.string.parse_policy else op.field ? resp.send(op.field).to_h : resp.to_h end rescue Aws::S3::Errors::ServiceError => e log_error(bucket.name, op.func, e.code) raise e unless suppressed_errors.include?(e.code) && [email protected]_on_exception end resources.push(struct.to_h) rescue Aws::S3::Errors::NoSuchBucket # skip missing bucket end end resources end
Returns an array of resources. Since S3 is a global service, the bucket operation calls can be parallelized.
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/s3.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/s3.rb
MIT
def collect resources = [] # # list_web_acls # # %w[CLOUDFRONT REGIONAL].each do |scope| %w[REGIONAL].each do |scope| @client.list_web_acls({ scope: scope }).each_with_index do |response, page| log(response.context.operation_name, page) response.web_acls.each do |acl| struct = OpenStruct.new(acl.to_h) struct.type = 'web_acl' params = { name: acl.name, scope: scope, id: acl.id } # get_web_acl @client.get_web_acl(params).each do |r| struct.arn = r.web_acl.arn struct.details = r.web_acl end # list_resources_for_web_acl @client.list_resources_for_web_acl({ web_acl_arn: acl.arn }).each do |r| struct.resources = r.resource_arns.map(&:to_h) end resources.push(struct.to_h) end end end resources end
Returns an array of resources. TODO: resolve scope (e.g. CLOUDFRONT supported?)
collect
ruby
joshlarsen/aws-recon
lib/aws_recon/collectors/wafv2.rb
https://github.com/joshlarsen/aws-recon/blob/master/lib/aws_recon/collectors/wafv2.rb
MIT
def new(relation, **new_options) self.class.new(relation, **options, **new_options) end
Return a new changeset with provided relation New options can be provided too @param [Relation] relation @param [Hash] new_options @return [Changeset] @api public
new
ruby
rom-rb/rom
changeset/lib/rom/changeset.rb
https://github.com/rom-rb/rom/blob/master/changeset/lib/rom/changeset.rb
MIT
def inspect %(#<#{self.class} relation=#{relation.name.inspect}>) end
Return string representation of the changeset @return [String] @api public
inspect
ruby
rom-rb/rom
changeset/lib/rom/changeset.rb
https://github.com/rom-rb/rom/blob/master/changeset/lib/rom/changeset.rb
MIT
End of preview. Expand in Data Studio

Ruby CodeSearch Dataset (Shuu12121/ruby-treesitter-filtered-datasetsV2)

Dataset Description

This dataset contains Ruby functions and methods paired with their documentation comments, extracted from open-source Ruby repositories on GitHub. It is formatted similarly to the CodeSearchNet challenge dataset.

Each entry includes:

  • code: The source code of a ruby function or method.
  • docstring: The docstring or Javadoc associated with the function/method.
  • func_name: The name of the function/method.
  • language: The programming language (always "ruby").
  • repo: The GitHub repository from which the code was sourced (e.g., "owner/repo").
  • path: The file path within the repository where the function/method is located.
  • url: A direct URL to the function/method's source file on GitHub (approximated to master/main branch).
  • license: The SPDX identifier of the license governing the source repository (e.g., "MIT", "Apache-2.0"). Additional metrics if available (from Lizard tool):
  • ccn: Cyclomatic Complexity Number.
  • params: Number of parameters of the function/method.
  • nloc: Non-commenting lines of code.
  • token_count: Number of tokens in the function/method.

Dataset Structure

The dataset is divided into the following splits:

  • train: 138,807 examples
  • validation: 1,979 examples
  • test: 25,537 examples

Data Collection

The data was collected by:

  1. Identifying popular and relevant Ruby repositories on GitHub.
  2. Cloning these repositories.
  3. Parsing Ruby files (.rb) using tree-sitter to extract functions/methods and their docstrings/Javadoc.
  4. Filtering functions/methods based on code length and presence of a non-empty docstring/Javadoc.
  5. Using the lizard tool to calculate code metrics (CCN, NLOC, params).
  6. Storing the extracted data in JSONL format, including repository and license information.
  7. Splitting the data by repository to ensure no data leakage between train, validation, and test sets.

Intended Use

This dataset can be used for tasks such as:

  • Training and evaluating models for code search (natural language to code).
  • Code summarization / docstring generation (code to natural language).
  • Studies on Ruby code practices and documentation habits.

Licensing

The code examples within this dataset are sourced from repositories with permissive licenses (typically MIT, Apache-2.0, BSD). Each sample includes its original license information in the license field. The dataset compilation itself is provided under a permissive license (e.g., MIT or CC-BY-SA-4.0), but users should respect the original licenses of the underlying code.

Example Usage

from datasets import load_dataset

# Load the dataset
dataset = load_dataset("Shuu12121/ruby-treesitter-filtered-datasetsV2")

# Access a split (e.g., train)
train_data = dataset["train"]

# Print the first example
print(train_data[0])
Downloads last month
39

Models trained or fine-tuned on Shuu12121/ruby-treesitter-filtered-datasetsV2

Collection including Shuu12121/ruby-treesitter-filtered-datasetsV2