_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
language
stringclasses
1 value
meta_information
dict
q11500
Responders.ControllerMethod.responders
train
def responders(*responders) self.responder = responders.inject(Class.new(responder)) do |klass, responder| responder = case responder when Module responder when String, Symbol Responders.const_get("#{responder.to_s.camelize}Responder") else ...
ruby
{ "resource": "" }
q11501
ActionController.RespondWith.respond_with
train
def respond_with(*resources, &block) if self.class.mimes_for_respond_to.empty? raise "In order to use respond_with, first you need to declare the " \ "formats your controller responds to in the class level." end mimes = collect_mimes_from_class_level collector = ActionControll...
ruby
{ "resource": "" }
q11502
ActionController.RespondWith.collect_mimes_from_class_level
train
def collect_mimes_from_class_level #:nodoc: action = action_name.to_sym self.class.mimes_for_respond_to.keys.select do |mime| config = self.class.mimes_for_respond_to[mime] if config[:except] !config[:except].include?(action) elsif config[:only] config[:only].in...
ruby
{ "resource": "" }
q11503
AlgoliaSearch.ClassMethods.algolia_reindex
train
def algolia_reindex(batch_size = AlgoliaSearch::IndexSettings::DEFAULT_BATCH_SIZE, synchronous = false) return if algolia_without_auto_index_scope algolia_configurations.each do |options, settings| next if algolia_indexing_disabled?(options) next if options[:slave] || options[:replica] ...
ruby
{ "resource": "" }
q11504
AlgoliaSearch.SafeIndex.get_settings
train
def get_settings(*args) SafeIndex.log_or_throw(:get_settings, @raise_on_failure) do begin @index.get_settings(*args) rescue Algolia::AlgoliaError => e return {} if e.code == 404 # not fatal raise e end end end
ruby
{ "resource": "" }
q11505
Filterrific.ParamSet.define_and_assign_attr_accessors_for_each_filter
train
def define_and_assign_attr_accessors_for_each_filter(fp) model_class.filterrific_available_filters.each do |filter_name| self.class.send(:attr_accessor, filter_name) v = fp[filter_name] self.send("#{ filter_name }=", v) if v.present? end end
ruby
{ "resource": "" }
q11506
Filterrific.ActionControllerExtension.compute_filterrific_params
train
def compute_filterrific_params(model_class, filterrific_params, opts, persistence_id) opts = { "sanitize_params" => true }.merge(opts.stringify_keys) r = ( filterrific_params.presence || # start with passed in params (persistence_id && session[persistence_id].presence) || # then try session ...
ruby
{ "resource": "" }
q11507
Filterrific.ActionViewExtension.form_for_filterrific
train
def form_for_filterrific(record, options = {}, &block) options[:as] ||= :filterrific options[:html] ||= {} options[:html][:method] ||= :get options[:html][:id] ||= :filterrific_filter options[:url] ||= url_for( :controller => controller.controller_name, :action => controlle...
ruby
{ "resource": "" }
q11508
Filterrific.ActionViewExtension.filterrific_sorting_link_reverse_order
train
def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts) # current sort column, toggle search_direction new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc' new_sorting = safe_join([new_sort_key, new_sort_direction], '_') css_classes = safe_join([ ...
ruby
{ "resource": "" }
q11509
VagrantVbguest.Config.to_hash
train
def to_hash { :installer => installer, :installer_arguments => installer_arguments, :iso_path => iso_path, :iso_upload_path => iso_upload_path, :iso_mount_point => iso_mount_point, :auto_update => auto_update, :auto_reboot => auto_reboot, :no_install...
ruby
{ "resource": "" }
q11510
VagrantVbguest.Command.execute_on_vm
train
def execute_on_vm(vm, options) check_runable_on(vm) options = options.clone _method = options.delete(:_method) _rebootable = options.delete(:_rebootable) options = vm.config.vbguest.to_hash.merge(options) machine = VagrantVbguest::Machine.new(vm, options) status = ma...
ruby
{ "resource": "" }
q11511
Cocoon.ViewHelpers.link_to_add_association
train
def link_to_add_association(*args, &block) if block_given? link_to_add_association(capture(&block), *args) elsif args.first.respond_to?(:object) association = args.second name = I18n.translate("cocoon.#{association}.add", default: I18n.translate('cocoon.defaults.add')) link_...
ruby
{ "resource": "" }
q11512
Raven.Instance.capture
train
def capture(options = {}) if block_given? begin yield rescue Error raise # Don't capture Raven errors rescue Exception => e capture_type(e, options) raise end else install_at_exit_hook(options) end end
ruby
{ "resource": "" }
q11513
Raven.Instance.annotate_exception
train
def annotate_exception(exc, options = {}) notes = (exc.instance_variable_defined?(:@__raven_context) && exc.instance_variable_get(:@__raven_context)) || {} Raven::Utils::DeepMergeHash.deep_merge!(notes, options) exc.instance_variable_set(:@__raven_context, notes) exc end
ruby
{ "resource": "" }
q11514
Raven.SidekiqErrorHandler.filter_context
train
def filter_context(context) case context when Array context.map { |arg| filter_context(arg) } when Hash Hash[context.map { |key, value| filter_context_hash(key, value) }] else format_globalid(context) end end
ruby
{ "resource": "" }
q11515
Ohai.System.run_plugins
train
def run_plugins(safe = false, attribute_filter = nil) begin @provides_map.all_plugins(attribute_filter).each do |plugin| @runner.run_plugin(plugin) end rescue Ohai::Exceptions::AttributeNotFound, Ohai::Exceptions::DependencyCycle => e logger.error("Encountered error while r...
ruby
{ "resource": "" }
q11516
Ohai.System.json_pretty_print
train
def json_pretty_print(item = nil) FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data) end
ruby
{ "resource": "" }
q11517
Ohai.ProvidesMap.find_providers_for
train
def find_providers_for(attributes) plugins = [] attributes.each do |attribute| attrs = select_subtree(@map, attribute) raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless attrs raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing...
ruby
{ "resource": "" }
q11518
Ohai.ProvidesMap.deep_find_providers_for
train
def deep_find_providers_for(attributes) plugins = [] attributes.each do |attribute| attrs = select_subtree(@map, attribute) unless attrs attrs = select_closest_subtree(@map, attribute) unless attrs raise Ohai::Exceptions::AttributeNotFound, "No such attribut...
ruby
{ "resource": "" }
q11519
Ohai.ProvidesMap.find_closest_providers_for
train
def find_closest_providers_for(attributes) plugins = [] attributes.each do |attribute| parts = normalize_and_validate(attribute) raise Ohai::Exceptions::AttributeNotFound, "No such attribute: \'#{attribute}\'" unless @map[parts[0]] attrs = select_closest_subtree(@map, attribute) ...
ruby
{ "resource": "" }
q11520
Ohai.ProvidesMap.collect_plugins_in
train
def collect_plugins_in(provides_map, collected) provides_map.each_key do |plugin| if plugin.eql?("_plugins") collected.concat(provides_map[plugin]) else collect_plugins_in(provides_map[plugin], collected) end end collected end
ruby
{ "resource": "" }
q11521
Ohai.Loader.plugin_files_by_dir
train
def plugin_files_by_dir(plugin_dir = Ohai.config[:plugin_path]) Array(plugin_dir).map do |path| if Dir.exist?(path) Ohai::Log.trace("Searching for Ohai plugins in #{path}") escaped = ChefConfig::PathHelper.escape_glob_dir(path) Dir[File.join(escaped, "**", "*.rb")] e...
ruby
{ "resource": "" }
q11522
Ohai.Loader.load_additional
train
def load_additional(from) from = [ Ohai.config[:plugin_path], from].flatten plugin_files_by_dir(from).collect do |plugin_file| logger.trace "Loading additional plugin: #{plugin_file}" plugin = load_plugin_class(plugin_file) load_v7_plugin(plugin) end end
ruby
{ "resource": "" }
q11523
Ohai.Loader.load_plugin
train
def load_plugin(plugin_path) plugin_class = load_plugin_class(plugin_path) return nil unless plugin_class.kind_of?(Class) if plugin_class < Ohai::DSL::Plugin::VersionVII load_v7_plugin(plugin_class) else raise Exceptions::IllegalPluginDefinition, "cannot create plugin of type #{p...
ruby
{ "resource": "" }
q11524
Ohai.Runner.get_cycle
train
def get_cycle(plugins, cycle_start) cycle = plugins.drop_while { |plugin| !plugin.eql?(cycle_start) } names = [] cycle.each { |plugin| names << plugin.name } names end
ruby
{ "resource": "" }
q11525
Ruby2D.Triangle.contains?
train
def contains?(x, y) self_area = triangle_area(@x1, @y1, @x2, @y2, @x3, @y3) questioned_area = triangle_area(@x1, @y1, @x2, @y2, x, y) + triangle_area(@x2, @y2, @x3, @y3, x, y) + triangle_area(@x3, @y3, @x1, @y1, x, y) questioned_area <= self_area end
ruby
{ "resource": "" }
q11526
Ruby2D.Sprite.play
train
def play(opts = {}, &done_proc) animation = opts[:animation] loop = opts[:loop] flip = opts[:flip] if !@playing || (animation != @playing_animation && animation != nil) || flip != @flip @playing = true @playing_animation = animation || :default frames = @animations[@pl...
ruby
{ "resource": "" }
q11527
Ruby2D.Sprite.set_frame
train
def set_frame frames = @animations[@playing_animation] case frames when Range reset_clipping_rect @clip_x = @current_frame * @clip_width when Array f = frames[@current_frame] @clip_x = f[:x] || @defaults[:clip_x] @clip_y = f[:y] || @def...
ruby
{ "resource": "" }
q11528
Ruby2D.Line.points_distance
train
def points_distance(x1, y1, x2, y2) Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) end
ruby
{ "resource": "" }
q11529
Ruby2D.Window.set
train
def set(opts) # Store new window attributes, or ignore if nil @title = opts[:title] || @title if Color.is_valid? opts[:background] @background = Color.new(opts[:background]) end @icon = opts[:icon] || @icon @width = opts[...
ruby
{ "resource": "" }
q11530
Ruby2D.Window.add
train
def add(o) case o when nil raise Error, "Cannot add '#{o.class}' to window!" when Array o.each { |x| add_object(x) } else add_object(o) end end
ruby
{ "resource": "" }
q11531
Ruby2D.Window.remove
train
def remove(o) if o == nil raise Error, "Cannot remove '#{o.class}' from window!" end if i = @objects.index(o) @objects.delete_at(i) true else false end end
ruby
{ "resource": "" }
q11532
Ruby2D.Window.on
train
def on(event, &proc) unless @events.has_key? event raise Error, "`#{event}` is not a valid event type" end event_id = new_event_key @events[event][event_id] = proc EventDescriptor.new(event, event_id) end
ruby
{ "resource": "" }
q11533
Ruby2D.Window.key_callback
train
def key_callback(type, key) key = key.downcase # All key events @events[:key].each do |id, e| e.call(KeyEvent.new(type, key)) end case type # When key is pressed, fired once when :down @events[:key_down].each do |id, e| e.call(KeyEvent.new(type, key)...
ruby
{ "resource": "" }
q11534
Ruby2D.Window.mouse_callback
train
def mouse_callback(type, button, direction, x, y, delta_x, delta_y) # All mouse events @events[:mouse].each do |id, e| e.call(MouseEvent.new(type, button, direction, x, y, delta_x, delta_y)) end case type # When mouse button pressed when :down @events[:mouse_down].ea...
ruby
{ "resource": "" }
q11535
Ruby2D.Window.controller_callback
train
def controller_callback(which, type, axis, value, button) # All controller events @events[:controller].each do |id, e| e.call(ControllerEvent.new(which, type, axis, value, button)) end case type # When controller axis motion, like analog sticks when :axis @events[:co...
ruby
{ "resource": "" }
q11536
Ruby2D.Window.update_callback
train
def update_callback @update_proc.call # Accept and eval commands if in console mode if @console if STDIN.ready? cmd = STDIN.gets begin res = eval(cmd, TOPLEVEL_BINDING) STDOUT.puts "=> #{res.inspect}" STDOUT.flush rescue Syntax...
ruby
{ "resource": "" }
q11537
Ruby2D.Window.add_object
train
def add_object(o) if !@objects.include?(o) index = @objects.index do |object| object.z > o.z end if index @objects.insert(index, o) else @objects.push(o) end true else false end end
ruby
{ "resource": "" }
q11538
Scenic.Statements.create_view
train
def create_view(name, version: nil, sql_definition: nil, materialized: false) if version.present? && sql_definition.present? raise( ArgumentError, "sql_definition and version cannot both be set", ) end if version.blank? && sql_definition.blank? version = 1 ...
ruby
{ "resource": "" }
q11539
Scenic.Statements.drop_view
train
def drop_view(name, revert_to_version: nil, materialized: false) if materialized Scenic.database.drop_materialized_view(name) else Scenic.database.drop_view(name) end end
ruby
{ "resource": "" }
q11540
Scenic.Statements.update_view
train
def update_view(name, version: nil, sql_definition: nil, revert_to_version: nil, materialized: false) if version.blank? && sql_definition.blank? raise( ArgumentError, "sql_definition or version must be specified", ) end if version.present? && sql_definition.present...
ruby
{ "resource": "" }
q11541
Scenic.Statements.replace_view
train
def replace_view(name, version: nil, revert_to_version: nil, materialized: false) if version.blank? raise ArgumentError, "version is required" end if materialized raise ArgumentError, "Cannot replace materialized views" end sql_definition = definition(name, version) ...
ruby
{ "resource": "" }
q11542
RubyEventStore.Event.to_h
train
def to_h { event_id: event_id, metadata: metadata.to_h, data: data, type: type, } end
ruby
{ "resource": "" }
q11543
RubyEventStore.Client.publish
train
def publish(events, stream_name: GLOBAL_STREAM, expected_version: :any) enriched_events = enrich_events_metadata(events) serialized_events = serialize_events(enriched_events) append_to_stream_serialized_events(serialized_events, stream_name: stream_name, expected_version: expected_version) enric...
ruby
{ "resource": "" }
q11544
SecureHeaders.Middleware.call
train
def call(env) req = Rack::Request.new(env) status, headers, response = @app.call(env) config = SecureHeaders.config_for(req) flag_cookies!(headers, override_secure(env, config.cookies)) unless config.cookies == OPT_OUT headers.merge!(SecureHeaders.header_hash_for(req)) [status, head...
ruby
{ "resource": "" }
q11545
SecureHeaders.Middleware.override_secure
train
def override_secure(env, config = {}) if scheme(env) != "https" && config != OPT_OUT config[:secure] = OPT_OUT end config end
ruby
{ "resource": "" }
q11546
SecureHeaders.CookiesConfig.validate_samesite_boolean_config!
train
def validate_samesite_boolean_config! if config[:samesite].key?(:lax) && config[:samesite][:lax].is_a?(TrueClass) && config[:samesite].key?(:strict) raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitte...
ruby
{ "resource": "" }
q11547
SecureHeaders.CookiesConfig.validate_exclusive_use_of_hash_constraints!
train
def validate_exclusive_use_of_hash_constraints!(conf, attribute) return unless is_hash?(conf) if conf.key?(:only) && conf.key?(:except) raise CookiesConfigError.new("#{attribute} cookie config is invalid, simultaneous use of conditional arguments `only` and `except` is not permitted.") end ...
ruby
{ "resource": "" }
q11548
SecureHeaders.CookiesConfig.validate_exclusive_use_of_samesite_enforcement!
train
def validate_exclusive_use_of_samesite_enforcement!(attribute) if (intersection = (config[:samesite][:lax].fetch(attribute, []) & config[:samesite][:strict].fetch(attribute, []))).any? raise CookiesConfigError.new("samesite cookie config is invalid, cookie(s) #{intersection.join(', ')} cannot be enforced ...
ruby
{ "resource": "" }
q11549
SecureHeaders.ContentSecurityPolicy.reject_all_values_if_none
train
def reject_all_values_if_none(source_list) if source_list.length > 1 source_list.reject { |value| value == NONE } else source_list end end
ruby
{ "resource": "" }
q11550
SecureHeaders.ContentSecurityPolicy.dedup_source_list
train
def dedup_source_list(sources) sources = sources.uniq wild_sources = sources.select { |source| source =~ STAR_REGEXP } if wild_sources.any? sources.reject do |source| !wild_sources.include?(source) && wild_sources.any? { |pattern| File.fnmatch(pattern, source) } ...
ruby
{ "resource": "" }
q11551
Recaptcha.ClientHelper.invisible_recaptcha_tags
train
def invisible_recaptcha_tags(options = {}) options = {callback: 'invisibleRecaptchaSubmit', ui: :button}.merge options text = options.delete(:text) html, tag_attributes = Recaptcha::ClientHelper.recaptcha_components(options) html << recaptcha_default_callback(options) if recaptcha_default_callba...
ruby
{ "resource": "" }
q11552
Recaptcha.Verify.verify_recaptcha
train
def verify_recaptcha(options = {}) options = {model: options} unless options.is_a? Hash return true if Recaptcha::Verify.skip?(options[:env]) model = options[:model] attribute = options[:attribute] || :base recaptcha_response = options[:response] || params['g-recaptcha-response'].to_s ...
ruby
{ "resource": "" }
q11553
HamlLint.Configuration.for_linter
train
def for_linter(linter) linter_name = case linter when Class linter.name.split('::').last when HamlLint::Linter linter.name end @hash['linters'].fetch(linter_name, {}).dup.freeze end
ruby
{ "resource": "" }
q11554
HamlLint.Configuration.smart_merge
train
def smart_merge(parent, child) parent.merge(child) do |_key, old, new| case old when Hash smart_merge(old, new) else new end end end
ruby
{ "resource": "" }
q11555
HamlLint.Reporter::DisabledConfigReporter.display_report
train
def display_report(report) super File.write(ConfigurationLoader::AUTO_GENERATED_FILE, config_file_contents) log.log "Created #{ConfigurationLoader::AUTO_GENERATED_FILE}." log.log "Run `haml-lint --config #{ConfigurationLoader::AUTO_GENERATED_FILE}`" \ ", or add `inherits_from: #{Configu...
ruby
{ "resource": "" }
q11556
HamlLint.Reporter::DisabledConfigReporter.finished_file
train
def finished_file(file, lints) super if lints.any? lints.each do |lint| linters_with_lints[lint.linter.name] |= [lint.filename] linters_lint_count[lint.linter.name] += 1 end end end
ruby
{ "resource": "" }
q11557
HamlLint.Reporter::DisabledConfigReporter.config_file_contents
train
def config_file_contents output = [] output << HEADING output << 'linters:' if linters_with_lints.any? linters_with_lints.each do |linter, files| output << generate_config_for_linter(linter, files) end output.join("\n\n") end
ruby
{ "resource": "" }
q11558
HamlLint.Reporter::DisabledConfigReporter.generate_config_for_linter
train
def generate_config_for_linter(linter, files) [].tap do |output| output << " # Offense count: #{linters_lint_count[linter]}" output << " #{linter}:" # disable the linter when there are many files with offenses. # exclude the affected files otherwise. if files.count > excl...
ruby
{ "resource": "" }
q11559
HamlLint.Options.load_reporter_class
train
def load_reporter_class(reporter_name) HamlLint::Reporter.const_get("#{reporter_name}Reporter") rescue NameError raise HamlLint::Exceptions::InvalidCLIOption, "#{reporter_name}Reporter does not exist" end
ruby
{ "resource": "" }
q11560
HamlLint.Linter::InstanceVariables.visit_root
train
def visit_root(node) @enabled = matcher.match(File.basename(node.file)) ? true : false end
ruby
{ "resource": "" }
q11561
HamlLint.Linter::InstanceVariables.visit_tag
train
def visit_tag(node) return unless enabled? visit_script(node) || if node.parsed_attributes.contains_instance_variables? record_lint(node, "Avoid using instance variables in #{file_types} views") end end
ruby
{ "resource": "" }
q11562
HamlLint.Runner.run
train
def run(options = {}) @config = load_applicable_config(options) @files = extract_applicable_files(config, options) @linter_selector = HamlLint::LinterSelector.new(config, options) @fail_fast = options.fetch(:fail_fast, false) report(options) end
ruby
{ "resource": "" }
q11563
HamlLint.Runner.collect_lints
train
def collect_lints(file, linter_selector, config) begin document = HamlLint::Document.new(File.read(file), file: file, config: config) rescue HamlLint::Exceptions::ParseError => e return [HamlLint::Lint.new(HamlLint::Linter::Syntax.new(config), file, e.line,...
ruby
{ "resource": "" }
q11564
HamlLint.Runner.extract_applicable_files
train
def extract_applicable_files(config, options) included_patterns = options[:files] excluded_patterns = config['exclude'] excluded_patterns += options.fetch(:excluded_files, []) HamlLint::FileFinder.new(config).find(included_patterns, excluded_patterns) end
ruby
{ "resource": "" }
q11565
HamlLint.Runner.process_files
train
def process_files(report) files.each do |file| process_file(file, report) break if report.failed? && fail_fast? end end
ruby
{ "resource": "" }
q11566
HamlLint.Runner.process_file
train
def process_file(file, report) lints = collect_lints(file, linter_selector, config) lints.each { |lint| report.add_lint(lint) } report.finish_file(file, lints) end
ruby
{ "resource": "" }
q11567
HamlLint.Runner.report
train
def report(options) report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level]) report.start(@files) process_files(report) report end
ruby
{ "resource": "" }
q11568
HamlLint.FileFinder.find
train
def find(patterns, excluded_patterns) excluded_patterns = excluded_patterns.map { |pattern| normalize_path(pattern) } extract_files_from(patterns).reject do |file| excluded_patterns.any? do |exclusion_glob| HamlLint::Utils.any_glob_matches?(exclusion_glob, file) end end ...
ruby
{ "resource": "" }
q11569
HamlLint.FileFinder.extract_files_from
train
def extract_files_from(patterns) # rubocop:disable MethodLength files = [] patterns.each do |pattern| if File.file?(pattern) files << pattern else begin ::Find.find(pattern) do |file| files << file if haml_file?(file) end r...
ruby
{ "resource": "" }
q11570
HamlLint.FileFinder.haml_file?
train
def haml_file?(file) return false unless ::FileTest.file?(file) VALID_EXTENSIONS.include?(::File.extname(file)) end
ruby
{ "resource": "" }
q11571
HamlLint.Linter::UnnecessaryStringOutput.starts_with_reserved_character?
train
def starts_with_reserved_character?(stringish) string = stringish.respond_to?(:children) ? stringish.children.first : stringish string =~ %r{\A\s*[/#-=%~]} end
ruby
{ "resource": "" }
q11572
HamlLint.Linter.run
train
def run(document) @document = document @lints = [] visit(document.tree) @lints rescue Parser::SyntaxError => e location = e.diagnostic.location @lints << HamlLint::Lint.new( HamlLint::Linter::Syntax.new(config), document.file, location.line, ...
ruby
{ "resource": "" }
q11573
HamlLint.Linter.inline_content_is_string?
train
def inline_content_is_string?(node) tag_with_inline_content = tag_with_inline_text(node) inline_content = inline_node_content(node) index = tag_with_inline_content.rindex(inline_content) - 1 %w[' "].include?(tag_with_inline_content[index]) end
ruby
{ "resource": "" }
q11574
HamlLint.Linter.inline_node_content
train
def inline_node_content(node) inline_content = node.script if contains_interpolation?(inline_content) strip_surrounding_quotes(inline_content) else inline_content end end
ruby
{ "resource": "" }
q11575
HamlLint.Linter.next_node
train
def next_node(node) return unless node siblings = node.parent ? node.parent.children : [node] next_sibling = siblings[siblings.index(node) + 1] if siblings.count > 1 return next_sibling if next_sibling next_node(node.parent) end
ruby
{ "resource": "" }
q11576
HamlLint.RubyParser.parse
train
def parse(source) buffer = ::Parser::Source::Buffer.new('(string)') buffer.source = source @parser.reset @parser.parse(buffer) end
ruby
{ "resource": "" }
q11577
HamlLint.CLI.act_on_options
train
def act_on_options(options) configure_logger(options) if options[:help] print_help(options) Sysexits::EX_OK elsif options[:version] || options[:verbose_version] print_version(options) Sysexits::EX_OK elsif options[:show_linters] print_available_linters ...
ruby
{ "resource": "" }
q11578
HamlLint.CLI.configure_logger
train
def configure_logger(options) log.color_enabled = options.fetch(:color, log.tty?) log.summary_enabled = options.fetch(:summary, true) end
ruby
{ "resource": "" }
q11579
HamlLint.CLI.handle_exception
train
def handle_exception(exception) case exception when HamlLint::Exceptions::ConfigurationError log.error exception.message Sysexits::EX_CONFIG when HamlLint::Exceptions::InvalidCLIOption log.error exception.message log.log "Run `#{APP_NAME}` --help for usage documentation...
ruby
{ "resource": "" }
q11580
HamlLint.CLI.reporter_from_options
train
def reporter_from_options(options) if options[:auto_gen_config] HamlLint::Reporter::DisabledConfigReporter.new(log, limit: options[:auto_gen_exclude_limit] || 15) # rubocop:disable Metrics/LineLength else options.fetch(:reporter, HamlLint::Reporter::DefaultReporter).new(log) end en...
ruby
{ "resource": "" }
q11581
HamlLint.CLI.scan_for_lints
train
def scan_for_lints(options) reporter = reporter_from_options(options) report = Runner.new.run(options.merge(reporter: reporter)) report.display report.failed? ? Sysexits::EX_DATAERR : Sysexits::EX_OK end
ruby
{ "resource": "" }
q11582
HamlLint.CLI.print_available_linters
train
def print_available_linters log.info 'Available linters:' linter_names = HamlLint::LinterRegistry.linters.map do |linter| linter.name.split('::').last end linter_names.sort.each do |linter_name| log.log " - #{linter_name}" end end
ruby
{ "resource": "" }
q11583
HamlLint.CLI.print_available_reporters
train
def print_available_reporters log.info 'Available reporters:' HamlLint::Reporter.available.map(&:cli_name).sort.each do |reporter_name| log.log " - #{reporter_name}" end end
ruby
{ "resource": "" }
q11584
HamlLint.CLI.print_version
train
def print_version(options) log.log "#{HamlLint::APP_NAME} #{HamlLint::VERSION}" if options[:verbose_version] log.log "haml #{Gem.loaded_specs['haml'].version}" log.log "rubocop #{Gem.loaded_specs['rubocop'].version}" log.log RUBY_DESCRIPTION end end
ruby
{ "resource": "" }
q11585
HamlLint.CLI.print_unexpected_exception
train
def print_unexpected_exception(exception) # rubocop:disable Metrics/AbcSize log.bold_error exception.message log.error exception.backtrace.join("\n") log.warning 'Report this bug at ', false log.info HamlLint::BUG_REPORT_URL log.newline log.success 'To help fix this issue, please inc...
ruby
{ "resource": "" }
q11586
HamlLint.Document.strip_frontmatter
train
def strip_frontmatter(source) frontmatter = / # From the start of the string \A # First-capture match --- followed by optional whitespace up # to a newline then 0 or more chars followed by an optional newline. # This matches the --- and the contents of the frontmatter ...
ruby
{ "resource": "" }
q11587
HamlLint::Tree.Node.disabled?
train
def disabled?(visitor) visitor.is_a?(HamlLint::Linter) && comment_configuration.disabled?(visitor.name) end
ruby
{ "resource": "" }
q11588
HamlLint::Tree.Node.each
train
def each return to_enum(__callee__) unless block_given? node = self loop do yield node break unless (node = node.next_node) end end
ruby
{ "resource": "" }
q11589
HamlLint::Tree.Node.line_numbers
train
def line_numbers return (line..line) unless @value && text end_line = line + lines.count end_line = nontrivial_end_line if line == end_line (line..end_line) end
ruby
{ "resource": "" }
q11590
HamlLint::Tree.Node.nontrivial_end_line
train
def nontrivial_end_line if (last_child = children.last) last_child.line_numbers.end - 1 elsif successor successor.line_numbers.begin - 1 else @document.source_lines.count end end
ruby
{ "resource": "" }
q11591
HamlLint::Tree.RootNode.node_for_line
train
def node_for_line(line) find(-> { HamlLint::Tree::NullNode.new }) { |node| node.line_numbers.cover?(line) } end
ruby
{ "resource": "" }
q11592
HamlLint.LinterSelector.extract_enabled_linters
train
def extract_enabled_linters(config, options) included_linters = LinterRegistry.extract_linters_from(options.fetch(:included_linters, [])) included_linters = LinterRegistry.linters if included_linters.empty? excluded_linters = LinterRegistry.extract_linters_from(options.fetch(:exclude...
ruby
{ "resource": "" }
q11593
HamlLint.LinterSelector.run_linter_on_file?
train
def run_linter_on_file?(config, linter, file) linter_config = config.for_linter(linter) if linter_config['include'].any? && !HamlLint::Utils.any_glob_matches?(linter_config['include'], file) return false end if HamlLint::Utils.any_glob_matches?(linter_config['exclude'], file) ...
ruby
{ "resource": "" }
q11594
HamlLint::Tree.TagNode.attributes_source
train
def attributes_source @attributes_source ||= begin _explicit_tag, static_attrs, rest = source_code.scan(/\A\s*(%[-:\w]+)?([-:\w\.\#]*)(.*)/m)[0] attr_types = { '{' => [:hash, %w[{ }]], '(' => [:html, %w[( )]], '[' => [:object_ref, %w[[ ]...
ruby
{ "resource": "" }
q11595
HamlLint.Linter::RuboCop.find_lints
train
def find_lints(ruby, source_map) rubocop = ::RuboCop::CLI.new filename = if document.file "#{document.file}.rb" else 'ruby_script.rb' end with_ruby_from_stdin(ruby) do extract_lints_from_offenses(lint_file(rubocop, filename), source_map) end ...
ruby
{ "resource": "" }
q11596
HamlLint.Linter::RuboCop.with_ruby_from_stdin
train
def with_ruby_from_stdin(ruby, &_block) original_stdin = $stdin stdin = StringIO.new stdin.write(ruby) stdin.rewind $stdin = stdin yield ensure $stdin = original_stdin end
ruby
{ "resource": "" }
q11597
HamlLint.Utils.get_abs_and_rel_path
train
def get_abs_and_rel_path(path) original_path = Pathname.new(path) root_dir_path = Pathname.new(File.expand_path(Dir.pwd)) if original_path.absolute? [path, original_path.relative_path_from(root_dir_path)] else [root_dir_path + original_path, path] end end
ruby
{ "resource": "" }
q11598
HamlLint.Utils.extract_interpolated_values
train
def extract_interpolated_values(text) # rubocop:disable Metrics/AbcSize dumped_text = text.dump newline_positions = extract_substring_positions(dumped_text, '\\\n') Haml::Util.handle_interpolation(dumped_text) do |scan| line = (newline_positions.find_index { |marker| scan.pos <= marker } || ...
ruby
{ "resource": "" }
q11599
HamlLint.Utils.for_consecutive_items
train
def for_consecutive_items(items, satisfies, min_consecutive = 2) current_index = -1 while (current_index += 1) < items.count next unless satisfies[items[current_index]] count = count_consecutive(items, current_index, &satisfies) next unless count >= min_consecutive # Yield...
ruby
{ "resource": "" }