id
int32 0
24.9k
| repo
stringlengths 5
58
| path
stringlengths 9
168
| func_name
stringlengths 9
130
| original_string
stringlengths 66
10.5k
| language
stringclasses 1
value | code
stringlengths 66
10.5k
| code_tokens
list | docstring
stringlengths 8
16k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 94
266
|
|---|---|---|---|---|---|---|---|---|---|---|---|
11,500
|
plataformatec/responders
|
lib/responders/controller_method.rb
|
Responders.ControllerMethod.responders
|
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
raise "responder has to be a string, a symbol or a module"
end
klass.send(:include, responder)
klass
end
end
|
ruby
|
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
raise "responder has to be a string, a symbol or a module"
end
klass.send(:include, responder)
klass
end
end
|
[
"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",
"raise",
"\"responder has to be a string, a symbol or a module\"",
"end",
"klass",
".",
"send",
"(",
":include",
",",
"responder",
")",
"klass",
"end",
"end"
] |
Adds the given responders to the current controller's responder, allowing you to cherry-pick
which responders you want per controller.
class InvitationsController < ApplicationController
responders :flash, :http_cache
end
Takes symbols and strings and translates them to VariableResponder (eg. :flash becomes FlashResponder).
Also allows passing in the responders modules in directly, so you could do:
responders FlashResponder, HttpCacheResponder
Or a mix of both methods:
responders :flash, MyCustomResponder
|
[
"Adds",
"the",
"given",
"responders",
"to",
"the",
"current",
"controller",
"s",
"responder",
"allowing",
"you",
"to",
"cherry",
"-",
"pick",
"which",
"responders",
"you",
"want",
"per",
"controller",
"."
] |
a1a2706091d4ffcbbe387407ddfc5671a59ad842
|
https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/responders/controller_method.rb#L19-L33
|
11,501
|
plataformatec/responders
|
lib/action_controller/respond_with.rb
|
ActionController.RespondWith.respond_with
|
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 = ActionController::MimeResponds::Collector.new(mimes, request.variant)
block.call(collector) if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
options = resources.size == 1 ? {} : resources.extract_options!
options = options.clone
options[:default_response] = collector.response
(options.delete(:responder) || self.class.responder).call(self, resources, options)
else
raise ActionController::UnknownFormat
end
end
|
ruby
|
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 = ActionController::MimeResponds::Collector.new(mimes, request.variant)
block.call(collector) if block_given?
if format = collector.negotiate_format(request)
_process_format(format)
options = resources.size == 1 ? {} : resources.extract_options!
options = options.clone
options[:default_response] = collector.response
(options.delete(:responder) || self.class.responder).call(self, resources, options)
else
raise ActionController::UnknownFormat
end
end
|
[
"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",
"=",
"ActionController",
"::",
"MimeResponds",
"::",
"Collector",
".",
"new",
"(",
"mimes",
",",
"request",
".",
"variant",
")",
"block",
".",
"call",
"(",
"collector",
")",
"if",
"block_given?",
"if",
"format",
"=",
"collector",
".",
"negotiate_format",
"(",
"request",
")",
"_process_format",
"(",
"format",
")",
"options",
"=",
"resources",
".",
"size",
"==",
"1",
"?",
"{",
"}",
":",
"resources",
".",
"extract_options!",
"options",
"=",
"options",
".",
"clone",
"options",
"[",
":default_response",
"]",
"=",
"collector",
".",
"response",
"(",
"options",
".",
"delete",
"(",
":responder",
")",
"||",
"self",
".",
"class",
".",
"responder",
")",
".",
"call",
"(",
"self",
",",
"resources",
",",
"options",
")",
"else",
"raise",
"ActionController",
"::",
"UnknownFormat",
"end",
"end"
] |
For a given controller action, respond_with generates an appropriate
response based on the mime-type requested by the client.
If the method is called with just a resource, as in this example -
class PeopleController < ApplicationController
respond_to :html, :xml, :json
def index
@people = Person.all
respond_with @people
end
end
then the mime-type of the response is typically selected based on the
request's Accept header and the set of available formats declared
by previous calls to the controller's class method +respond_to+. Alternatively
the mime-type can be selected by explicitly setting <tt>request.format</tt> in
the controller.
If an acceptable format is not identified, the application returns a
'406 - not acceptable' status. Otherwise, the default response is to render
a template named after the current action and the selected format,
e.g. <tt>index.html.erb</tt>. If no template is available, the behavior
depends on the selected format:
* for an html response - if the request method is +get+, an exception
is raised but for other requests such as +post+ the response
depends on whether the resource has any validation errors (i.e.
assuming that an attempt has been made to save the resource,
e.g. by a +create+ action) -
1. If there are no errors, i.e. the resource
was saved successfully, the response +redirect+'s to the resource
i.e. its +show+ action.
2. If there are validation errors, the response
renders a default action, which is <tt>:new</tt> for a
+post+ request or <tt>:edit</tt> for +patch+ or +put+.
Thus an example like this -
respond_to :html, :xml
def create
@user = User.new(params[:user])
flash[:notice] = 'User was successfully created.' if @user.save
respond_with(@user)
end
is equivalent, in the absence of <tt>create.html.erb</tt>, to -
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash[:notice] = 'User was successfully created.'
format.html { redirect_to(@user) }
format.xml { render xml: @user }
else
format.html { render action: "new" }
format.xml { render xml: @user }
end
end
end
* for a JavaScript request - if the template isn't found, an exception is
raised.
* for other requests - i.e. data formats such as xml, json, csv etc, if
the resource passed to +respond_with+ responds to <code>to_<format></code>,
the method attempts to render the resource in the requested format
directly, e.g. for an xml request, the response is equivalent to calling
<code>render xml: resource</code>.
=== Nested resources
As outlined above, the +resources+ argument passed to +respond_with+
can play two roles. It can be used to generate the redirect url
for successful html requests (e.g. for +create+ actions when
no template exists), while for formats other than html and JavaScript
it is the object that gets rendered, by being converted directly to the
required format (again assuming no template exists).
For redirecting successful html requests, +respond_with+ also supports
the use of nested resources, which are supplied in the same way as
in <code>form_for</code> and <code>polymorphic_url</code>. For example -
def create
@project = Project.find(params[:project_id])
@task = @project.comments.build(params[:task])
flash[:notice] = 'Task was successfully created.' if @task.save
respond_with(@project, @task)
end
This would cause +respond_with+ to redirect to <code>project_task_url</code>
instead of <code>task_url</code>. For request formats other than html or
JavaScript, if multiple resources are passed in this way, it is the last
one specified that is rendered.
=== Customizing response behavior
Like +respond_to+, +respond_with+ may also be called with a block that
can be used to overwrite any of the default responses, e.g. -
def create
@user = User.new(params[:user])
flash[:notice] = "User was successfully created." if @user.save
respond_with(@user) do |format|
format.html { render }
end
end
The argument passed to the block is an ActionController::MimeResponds::Collector
object which stores the responses for the formats defined within the
block. Note that formats with responses defined explicitly in this way
do not have to first be declared using the class method +respond_to+.
Also, a hash passed to +respond_with+ immediately after the specified
resource(s) is interpreted as a set of options relevant to all
formats. Any option accepted by +render+ can be used, e.g.
respond_with @people, status: 200
However, note that these options are ignored after an unsuccessful attempt
to save a resource, e.g. when automatically rendering <tt>:new</tt>
after a post request.
Three additional options are relevant specifically to +respond_with+ -
1. <tt>:location</tt> - overwrites the default redirect location used after
a successful html +post+ request.
2. <tt>:action</tt> - overwrites the default render action used after an
unsuccessful html +post+ request.
3. <tt>:render</tt> - allows to pass any options directly to the <tt>:render<tt/>
call after unsuccessful html +post+ request. Usefull if for example you
need to render a template which is outside of controller's path or you
want to override the default http <tt>:status</tt> code, e.g.
respond_with(resource, render: { template: 'path/to/template', status: 422 })
|
[
"For",
"a",
"given",
"controller",
"action",
"respond_with",
"generates",
"an",
"appropriate",
"response",
"based",
"on",
"the",
"mime",
"-",
"type",
"requested",
"by",
"the",
"client",
"."
] |
a1a2706091d4ffcbbe387407ddfc5671a59ad842
|
https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/action_controller/respond_with.rb#L196-L215
|
11,502
|
plataformatec/responders
|
lib/action_controller/respond_with.rb
|
ActionController.RespondWith.collect_mimes_from_class_level
|
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].include?(action)
else
true
end
end
end
|
ruby
|
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].include?(action)
else
true
end
end
end
|
[
"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",
"]",
".",
"include?",
"(",
"action",
")",
"else",
"true",
"end",
"end",
"end"
] |
Collect mimes declared in the class method respond_to valid for the
current action.
|
[
"Collect",
"mimes",
"declared",
"in",
"the",
"class",
"method",
"respond_to",
"valid",
"for",
"the",
"current",
"action",
"."
] |
a1a2706091d4ffcbbe387407ddfc5671a59ad842
|
https://github.com/plataformatec/responders/blob/a1a2706091d4ffcbbe387407ddfc5671a59ad842/lib/action_controller/respond_with.rb#L240-L254
|
11,503
|
algolia/algoliasearch-rails
|
lib/algoliasearch-rails.rb
|
AlgoliaSearch.ClassMethods.algolia_reindex
|
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]
# fetch the master settings
master_index = algolia_ensure_init(options, settings)
master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings
# remove the replicas of the temporary index
master_settings.delete :slaves
master_settings.delete 'slaves'
master_settings.delete :replicas
master_settings.delete 'replicas'
# init temporary index
index_name = algolia_index_name(options)
tmp_options = options.merge({ :index_name => "#{index_name}.tmp" })
tmp_options.delete(:per_environment) # already included in the temporary index_name
tmp_settings = settings.dup
tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)
algolia_find_in_batches(batch_size) do |group|
if algolia_conditional_index?(tmp_options)
# select only indexable objects
group = group.select { |o| algolia_indexable?(o, tmp_options) }
end
objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
tmp_index.save_objects(objects)
end
move_task = SafeIndex.move_index(tmp_index.name, index_name)
master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous]
end
nil
end
|
ruby
|
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]
# fetch the master settings
master_index = algolia_ensure_init(options, settings)
master_settings = master_index.get_settings rescue {} # if master doesn't exist yet
master_settings.merge!(JSON.parse(settings.to_settings.to_json)) # convert symbols to strings
# remove the replicas of the temporary index
master_settings.delete :slaves
master_settings.delete 'slaves'
master_settings.delete :replicas
master_settings.delete 'replicas'
# init temporary index
index_name = algolia_index_name(options)
tmp_options = options.merge({ :index_name => "#{index_name}.tmp" })
tmp_options.delete(:per_environment) # already included in the temporary index_name
tmp_settings = settings.dup
tmp_index = algolia_ensure_init(tmp_options, tmp_settings, master_settings)
algolia_find_in_batches(batch_size) do |group|
if algolia_conditional_index?(tmp_options)
# select only indexable objects
group = group.select { |o| algolia_indexable?(o, tmp_options) }
end
objects = group.map { |o| tmp_settings.get_attributes(o).merge 'objectID' => algolia_object_id_of(o, tmp_options) }
tmp_index.save_objects(objects)
end
move_task = SafeIndex.move_index(tmp_index.name, index_name)
master_index.wait_task(move_task["taskID"]) if synchronous || options[:synchronous]
end
nil
end
|
[
"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",
"]",
"# fetch the master settings",
"master_index",
"=",
"algolia_ensure_init",
"(",
"options",
",",
"settings",
")",
"master_settings",
"=",
"master_index",
".",
"get_settings",
"rescue",
"{",
"}",
"# if master doesn't exist yet",
"master_settings",
".",
"merge!",
"(",
"JSON",
".",
"parse",
"(",
"settings",
".",
"to_settings",
".",
"to_json",
")",
")",
"# convert symbols to strings",
"# remove the replicas of the temporary index",
"master_settings",
".",
"delete",
":slaves",
"master_settings",
".",
"delete",
"'slaves'",
"master_settings",
".",
"delete",
":replicas",
"master_settings",
".",
"delete",
"'replicas'",
"# init temporary index",
"index_name",
"=",
"algolia_index_name",
"(",
"options",
")",
"tmp_options",
"=",
"options",
".",
"merge",
"(",
"{",
":index_name",
"=>",
"\"#{index_name}.tmp\"",
"}",
")",
"tmp_options",
".",
"delete",
"(",
":per_environment",
")",
"# already included in the temporary index_name",
"tmp_settings",
"=",
"settings",
".",
"dup",
"tmp_index",
"=",
"algolia_ensure_init",
"(",
"tmp_options",
",",
"tmp_settings",
",",
"master_settings",
")",
"algolia_find_in_batches",
"(",
"batch_size",
")",
"do",
"|",
"group",
"|",
"if",
"algolia_conditional_index?",
"(",
"tmp_options",
")",
"# select only indexable objects",
"group",
"=",
"group",
".",
"select",
"{",
"|",
"o",
"|",
"algolia_indexable?",
"(",
"o",
",",
"tmp_options",
")",
"}",
"end",
"objects",
"=",
"group",
".",
"map",
"{",
"|",
"o",
"|",
"tmp_settings",
".",
"get_attributes",
"(",
"o",
")",
".",
"merge",
"'objectID'",
"=>",
"algolia_object_id_of",
"(",
"o",
",",
"tmp_options",
")",
"}",
"tmp_index",
".",
"save_objects",
"(",
"objects",
")",
"end",
"move_task",
"=",
"SafeIndex",
".",
"move_index",
"(",
"tmp_index",
".",
"name",
",",
"index_name",
")",
"master_index",
".",
"wait_task",
"(",
"move_task",
"[",
"\"taskID\"",
"]",
")",
"if",
"synchronous",
"||",
"options",
"[",
":synchronous",
"]",
"end",
"nil",
"end"
] |
reindex whole database using a extra temporary index + move operation
|
[
"reindex",
"whole",
"database",
"using",
"a",
"extra",
"temporary",
"index",
"+",
"move",
"operation"
] |
360e47d733476e6611d9874cf89e57942b7f2939
|
https://github.com/algolia/algoliasearch-rails/blob/360e47d733476e6611d9874cf89e57942b7f2939/lib/algoliasearch-rails.rb#L540-L577
|
11,504
|
algolia/algoliasearch-rails
|
lib/algoliasearch-rails.rb
|
AlgoliaSearch.SafeIndex.get_settings
|
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
|
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
|
[
"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"
] |
special handling of get_settings to avoid raising errors on 404
|
[
"special",
"handling",
"of",
"get_settings",
"to",
"avoid",
"raising",
"errors",
"on",
"404"
] |
360e47d733476e6611d9874cf89e57942b7f2939
|
https://github.com/algolia/algoliasearch-rails/blob/360e47d733476e6611d9874cf89e57942b7f2939/lib/algoliasearch-rails.rb#L328-L337
|
11,505
|
jhund/filterrific
|
lib/filterrific/param_set.rb
|
Filterrific.ParamSet.define_and_assign_attr_accessors_for_each_filter
|
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
|
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
|
[
"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"
] |
Defines attr accessors for each available_filter on self and assigns
values based on fp.
@param fp [Hash] filterrific_params with stringified keys
|
[
"Defines",
"attr",
"accessors",
"for",
"each",
"available_filter",
"on",
"self",
"and",
"assigns",
"values",
"based",
"on",
"fp",
"."
] |
811edc57d3e2a3e538c1f0e9554e0909be052881
|
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/param_set.rb#L120-L126
|
11,506
|
jhund/filterrific
|
lib/filterrific/action_controller_extension.rb
|
Filterrific.ActionControllerExtension.compute_filterrific_params
|
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 persisted params if persistence_id is present
opts['default_filter_params'] || # then use passed in opts
model_class.filterrific_default_filter_params # finally use model_class defaults
).stringify_keys
r.slice!(*opts['available_filters'].map(&:to_s)) if opts['available_filters']
# Sanitize params to prevent reflected XSS attack
if opts["sanitize_params"]
r.each { |k,v| r[k] = sanitize_filterrific_param(r[k]) }
end
r
end
|
ruby
|
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 persisted params if persistence_id is present
opts['default_filter_params'] || # then use passed in opts
model_class.filterrific_default_filter_params # finally use model_class defaults
).stringify_keys
r.slice!(*opts['available_filters'].map(&:to_s)) if opts['available_filters']
# Sanitize params to prevent reflected XSS attack
if opts["sanitize_params"]
r.each { |k,v| r[k] = sanitize_filterrific_param(r[k]) }
end
r
end
|
[
"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 persisted params if persistence_id is present",
"opts",
"[",
"'default_filter_params'",
"]",
"||",
"# then use passed in opts",
"model_class",
".",
"filterrific_default_filter_params",
"# finally use model_class defaults",
")",
".",
"stringify_keys",
"r",
".",
"slice!",
"(",
"opts",
"[",
"'available_filters'",
"]",
".",
"map",
"(",
":to_s",
")",
")",
"if",
"opts",
"[",
"'available_filters'",
"]",
"# Sanitize params to prevent reflected XSS attack",
"if",
"opts",
"[",
"\"sanitize_params\"",
"]",
"r",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"r",
"[",
"k",
"]",
"=",
"sanitize_filterrific_param",
"(",
"r",
"[",
"k",
"]",
")",
"}",
"end",
"r",
"end"
] |
Computes filterrific params using a number of strategies. Limits params
to 'available_filters' if given via opts.
@param model_class [ActiveRecord::Base]
@param filterrific_params [ActionController::Params, Hash]
@param opts [Hash]
@option opts [Boolean, optional] "sanitize_params"
if true, sanitizes all filterrific params to prevent reflected (or stored) XSS attacks.
Defaults to true.
@param persistence_id [String, nil]
|
[
"Computes",
"filterrific",
"params",
"using",
"a",
"number",
"of",
"strategies",
".",
"Limits",
"params",
"to",
"available_filters",
"if",
"given",
"via",
"opts",
"."
] |
811edc57d3e2a3e538c1f0e9554e0909be052881
|
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_controller_extension.rb#L70-L84
|
11,507
|
jhund/filterrific
|
lib/filterrific/action_view_extension.rb
|
Filterrific.ActionViewExtension.form_for_filterrific
|
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 => controller.action_name
)
form_for(record, options, &block)
end
|
ruby
|
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 => controller.action_name
)
form_for(record, options, &block)
end
|
[
"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",
"=>",
"controller",
".",
"action_name",
")",
"form_for",
"(",
"record",
",",
"options",
",",
"block",
")",
"end"
] |
Sets all options on form_for to defaults that work with Filterrific
@param record [Filterrific] the @filterrific object
@param options [Hash] standard options for form_for
@param block [Proc] the form body
|
[
"Sets",
"all",
"options",
"on",
"form_for",
"to",
"defaults",
"that",
"work",
"with",
"Filterrific"
] |
811edc57d3e2a3e538c1f0e9554e0909be052881
|
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L14-L24
|
11,508
|
jhund/filterrific
|
lib/filterrific/action_view_extension.rb
|
Filterrific.ActionViewExtension.filterrific_sorting_link_reverse_order
|
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([
opts[:active_column_class],
opts[:html_attrs].delete(:class)
].compact, ' ')
new_filterrific_params = filterrific.to_hash
.with_indifferent_access
.merge(opts[:sorting_scope_name] => new_sorting)
url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params)
link_to(
safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '),
url_for(url_for_attrs),
opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true)
)
end
|
ruby
|
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([
opts[:active_column_class],
opts[:html_attrs].delete(:class)
].compact, ' ')
new_filterrific_params = filterrific.to_hash
.with_indifferent_access
.merge(opts[:sorting_scope_name] => new_sorting)
url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params)
link_to(
safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '),
url_for(url_for_attrs),
opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true)
)
end
|
[
"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",
"(",
"[",
"opts",
"[",
":active_column_class",
"]",
",",
"opts",
"[",
":html_attrs",
"]",
".",
"delete",
"(",
":class",
")",
"]",
".",
"compact",
",",
"' '",
")",
"new_filterrific_params",
"=",
"filterrific",
".",
"to_hash",
".",
"with_indifferent_access",
".",
"merge",
"(",
"opts",
"[",
":sorting_scope_name",
"]",
"=>",
"new_sorting",
")",
"url_for_attrs",
"=",
"opts",
"[",
":url_for_attrs",
"]",
".",
"merge",
"(",
":filterrific",
"=>",
"new_filterrific_params",
")",
"link_to",
"(",
"safe_join",
"(",
"[",
"opts",
"[",
":label",
"]",
",",
"opts",
"[",
":current_sort_direction_indicator",
"]",
"]",
",",
"' '",
")",
",",
"url_for",
"(",
"url_for_attrs",
")",
",",
"opts",
"[",
":html_attrs",
"]",
".",
"reverse_merge",
"(",
":class",
"=>",
"css_classes",
",",
":method",
"=>",
":get",
",",
":remote",
"=>",
"true",
")",
")",
"end"
] |
Renders HTML to reverse sort order on currently sorted column.
@param filterrific [Filterrific::ParamSet]
@param new_sort_key [String]
@param opts [Hash]
@return [String] an HTML fragment
|
[
"Renders",
"HTML",
"to",
"reverse",
"sort",
"order",
"on",
"currently",
"sorted",
"column",
"."
] |
811edc57d3e2a3e538c1f0e9554e0909be052881
|
https://github.com/jhund/filterrific/blob/811edc57d3e2a3e538c1f0e9554e0909be052881/lib/filterrific/action_view_extension.rb#L102-L119
|
11,509
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/config.rb
|
VagrantVbguest.Config.to_hash
|
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 => no_install,
:no_remote => no_remote,
:yes => yes
}
end
|
ruby
|
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 => no_install,
:no_remote => no_remote,
:yes => yes
}
end
|
[
"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",
"=>",
"no_install",
",",
":no_remote",
"=>",
"no_remote",
",",
":yes",
"=>",
"yes",
"}",
"end"
] |
explicit hash, to get symbols in hash keys
|
[
"explicit",
"hash",
"to",
"get",
"symbols",
"in",
"hash",
"keys"
] |
934fd22864c811c951c020cfcfc5c2ef9d79d5ef
|
https://github.com/dotless-de/vagrant-vbguest/blob/934fd22864c811c951c020cfcfc5c2ef9d79d5ef/lib/vagrant-vbguest/config.rb#L42-L55
|
11,510
|
dotless-de/vagrant-vbguest
|
lib/vagrant-vbguest/command.rb
|
VagrantVbguest.Command.execute_on_vm
|
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 = machine.state
vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))
if _method != :status
machine.send(_method)
end
reboot!(vm, options) if _rebootable && machine.reboot?
rescue VagrantVbguest::Installer::NoInstallerFoundError => e
vm.env.ui.error e.message
end
|
ruby
|
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 = machine.state
vm.env.ui.send((:ok == status ? :success : :warn), I18n.t("vagrant_vbguest.status.#{status}", machine.info))
if _method != :status
machine.send(_method)
end
reboot!(vm, options) if _rebootable && machine.reboot?
rescue VagrantVbguest::Installer::NoInstallerFoundError => e
vm.env.ui.error e.message
end
|
[
"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",
"=",
"machine",
".",
"state",
"vm",
".",
"env",
".",
"ui",
".",
"send",
"(",
"(",
":ok",
"==",
"status",
"?",
":success",
":",
":warn",
")",
",",
"I18n",
".",
"t",
"(",
"\"vagrant_vbguest.status.#{status}\"",
",",
"machine",
".",
"info",
")",
")",
"if",
"_method",
"!=",
":status",
"machine",
".",
"send",
"(",
"_method",
")",
"end",
"reboot!",
"(",
"vm",
",",
"options",
")",
"if",
"_rebootable",
"&&",
"machine",
".",
"reboot?",
"rescue",
"VagrantVbguest",
"::",
"Installer",
"::",
"NoInstallerFoundError",
"=>",
"e",
"vm",
".",
"env",
".",
"ui",
".",
"error",
"e",
".",
"message",
"end"
] |
Executes a task on a specific VM.
@param vm [Vagrant::VM]
@param options [Hash] Parsed options from the command line
|
[
"Executes",
"a",
"task",
"on",
"a",
"specific",
"VM",
"."
] |
934fd22864c811c951c020cfcfc5c2ef9d79d5ef
|
https://github.com/dotless-de/vagrant-vbguest/blob/934fd22864c811c951c020cfcfc5c2ef9d79d5ef/lib/vagrant-vbguest/command.rb#L87-L106
|
11,511
|
nathanvda/cocoon
|
lib/cocoon/view_helpers.rb
|
Cocoon.ViewHelpers.link_to_add_association
|
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_to_add_association(name, *args)
else
name, f, association, html_options = *args
html_options ||= {}
render_options = html_options.delete(:render_options)
render_options ||= {}
override_partial = html_options.delete(:partial)
wrap_object = html_options.delete(:wrap_object)
force_non_association_create = html_options.delete(:force_non_association_create) || false
form_parameter_name = html_options.delete(:form_name) || 'f'
count = html_options.delete(:count).to_i
html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ')
html_options[:'data-association'] = association.to_s.singularize
html_options[:'data-associations'] = association.to_s.pluralize
new_object = create_object(f, association, force_non_association_create)
new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call)
html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe
html_options[:'data-count'] = count if count > 0
link_to(name, '#', html_options)
end
end
|
ruby
|
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_to_add_association(name, *args)
else
name, f, association, html_options = *args
html_options ||= {}
render_options = html_options.delete(:render_options)
render_options ||= {}
override_partial = html_options.delete(:partial)
wrap_object = html_options.delete(:wrap_object)
force_non_association_create = html_options.delete(:force_non_association_create) || false
form_parameter_name = html_options.delete(:form_name) || 'f'
count = html_options.delete(:count).to_i
html_options[:class] = [html_options[:class], "add_fields"].compact.join(' ')
html_options[:'data-association'] = association.to_s.singularize
html_options[:'data-associations'] = association.to_s.pluralize
new_object = create_object(f, association, force_non_association_create)
new_object = wrap_object.call(new_object) if wrap_object.respond_to?(:call)
html_options[:'data-association-insertion-template'] = CGI.escapeHTML(render_association(association, f, new_object, form_parameter_name, render_options, override_partial).to_str).html_safe
html_options[:'data-count'] = count if count > 0
link_to(name, '#', html_options)
end
end
|
[
"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_to_add_association",
"(",
"name",
",",
"args",
")",
"else",
"name",
",",
"f",
",",
"association",
",",
"html_options",
"=",
"args",
"html_options",
"||=",
"{",
"}",
"render_options",
"=",
"html_options",
".",
"delete",
"(",
":render_options",
")",
"render_options",
"||=",
"{",
"}",
"override_partial",
"=",
"html_options",
".",
"delete",
"(",
":partial",
")",
"wrap_object",
"=",
"html_options",
".",
"delete",
"(",
":wrap_object",
")",
"force_non_association_create",
"=",
"html_options",
".",
"delete",
"(",
":force_non_association_create",
")",
"||",
"false",
"form_parameter_name",
"=",
"html_options",
".",
"delete",
"(",
":form_name",
")",
"||",
"'f'",
"count",
"=",
"html_options",
".",
"delete",
"(",
":count",
")",
".",
"to_i",
"html_options",
"[",
":class",
"]",
"=",
"[",
"html_options",
"[",
":class",
"]",
",",
"\"add_fields\"",
"]",
".",
"compact",
".",
"join",
"(",
"' '",
")",
"html_options",
"[",
":'",
"'",
"]",
"=",
"association",
".",
"to_s",
".",
"singularize",
"html_options",
"[",
":'",
"'",
"]",
"=",
"association",
".",
"to_s",
".",
"pluralize",
"new_object",
"=",
"create_object",
"(",
"f",
",",
"association",
",",
"force_non_association_create",
")",
"new_object",
"=",
"wrap_object",
".",
"call",
"(",
"new_object",
")",
"if",
"wrap_object",
".",
"respond_to?",
"(",
":call",
")",
"html_options",
"[",
":'",
"'",
"]",
"=",
"CGI",
".",
"escapeHTML",
"(",
"render_association",
"(",
"association",
",",
"f",
",",
"new_object",
",",
"form_parameter_name",
",",
"render_options",
",",
"override_partial",
")",
".",
"to_str",
")",
".",
"html_safe",
"html_options",
"[",
":'",
"'",
"]",
"=",
"count",
"if",
"count",
">",
"0",
"link_to",
"(",
"name",
",",
"'#'",
",",
"html_options",
")",
"end",
"end"
] |
shows a link that will allow to dynamically add a new associated object.
- *name* : the text to show in the link
- *f* : the form this should come in (the formtastic form)
- *association* : the associated objects, e.g. :tasks, this should be the name of the <tt>has_many</tt> relation.
- *html_options*: html options to be passed to <tt>link_to</tt> (see <tt>link_to</tt>)
- *:render_options* : options passed to `simple_fields_for, semantic_fields_for or fields_for`
- *:locals* : the locals hash in the :render_options is handed to the partial
- *:partial* : explicitly override the default partial name
- *:wrap_object* : a proc that will allow to wrap your object, especially suited when using
decorators, or if you want special initialisation
- *:form_name* : the parameter for the form in the nested form partial. Default `f`.
- *:count* : Count of how many objects will be added on a single click. Default `1`.
- *&block*: see <tt>link_to</tt>
|
[
"shows",
"a",
"link",
"that",
"will",
"allow",
"to",
"dynamically",
"add",
"a",
"new",
"associated",
"object",
"."
] |
ec18c446a5475aa4959c699c797ee0fe9b0c9136
|
https://github.com/nathanvda/cocoon/blob/ec18c446a5475aa4959c699c797ee0fe9b0c9136/lib/cocoon/view_helpers.rb#L71-L104
|
11,512
|
getsentry/raven-ruby
|
lib/raven/instance.rb
|
Raven.Instance.capture
|
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
|
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
|
[
"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"
] |
Capture and process any exceptions from the given block.
@example
Raven.capture do
MyApp.run
end
|
[
"Capture",
"and",
"process",
"any",
"exceptions",
"from",
"the",
"given",
"block",
"."
] |
729c22f9284939695f14822683bff1a0b72502bd
|
https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/instance.rb#L90-L103
|
11,513
|
getsentry/raven-ruby
|
lib/raven/instance.rb
|
Raven.Instance.annotate_exception
|
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
|
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
|
[
"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"
] |
Provides extra context to the exception prior to it being handled by
Raven. An exception can have multiple annotations, which are merged
together.
The options (annotation) is treated the same as the ``options``
parameter to ``capture_exception`` or ``Event.from_exception``, and
can contain the same ``:user``, ``:tags``, etc. options as these
methods.
These will be merged with the ``options`` parameter to
``Event.from_exception`` at the top of execution.
@example
begin
raise "Hello"
rescue => exc
Raven.annotate_exception(exc, :user => { 'id' => 1,
'email' => 'foo@example.com' })
end
|
[
"Provides",
"extra",
"context",
"to",
"the",
"exception",
"prior",
"to",
"it",
"being",
"handled",
"by",
"Raven",
".",
"An",
"exception",
"can",
"have",
"multiple",
"annotations",
"which",
"are",
"merged",
"together",
"."
] |
729c22f9284939695f14822683bff1a0b72502bd
|
https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/instance.rb#L159-L164
|
11,514
|
getsentry/raven-ruby
|
lib/raven/integrations/sidekiq.rb
|
Raven.SidekiqErrorHandler.filter_context
|
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
|
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
|
[
"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"
] |
Once an ActiveJob is queued, ActiveRecord references get serialized into
some internal reserved keys, such as _aj_globalid.
The problem is, if this job in turn gets queued back into ActiveJob with
these magic reserved keys, ActiveJob will throw up and error. We want to
capture these and mutate the keys so we can sanely report it.
|
[
"Once",
"an",
"ActiveJob",
"is",
"queued",
"ActiveRecord",
"references",
"get",
"serialized",
"into",
"some",
"internal",
"reserved",
"keys",
"such",
"as",
"_aj_globalid",
"."
] |
729c22f9284939695f14822683bff1a0b72502bd
|
https://github.com/getsentry/raven-ruby/blob/729c22f9284939695f14822683bff1a0b72502bd/lib/raven/integrations/sidekiq.rb#L39-L48
|
11,515
|
chef/ohai
|
lib/ohai/system.rb
|
Ohai.System.run_plugins
|
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 running plugins: #{e.inspect}")
raise
end
critical_failed = Ohai::Config.ohai[:critical_plugins] & @runner.failed_plugins
unless critical_failed.empty?
msg = "The following Ohai plugins marked as critical failed: #{critical_failed}"
if @cli
logger.error(msg)
exit(true)
else
raise Ohai::Exceptions::CriticalPluginFailure, "#{msg}. Failing Chef run."
end
end
# Freeze all strings.
freeze_strings!
end
|
ruby
|
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 running plugins: #{e.inspect}")
raise
end
critical_failed = Ohai::Config.ohai[:critical_plugins] & @runner.failed_plugins
unless critical_failed.empty?
msg = "The following Ohai plugins marked as critical failed: #{critical_failed}"
if @cli
logger.error(msg)
exit(true)
else
raise Ohai::Exceptions::CriticalPluginFailure, "#{msg}. Failing Chef run."
end
end
# Freeze all strings.
freeze_strings!
end
|
[
"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 running plugins: #{e.inspect}\"",
")",
"raise",
"end",
"critical_failed",
"=",
"Ohai",
"::",
"Config",
".",
"ohai",
"[",
":critical_plugins",
"]",
"&",
"@runner",
".",
"failed_plugins",
"unless",
"critical_failed",
".",
"empty?",
"msg",
"=",
"\"The following Ohai plugins marked as critical failed: #{critical_failed}\"",
"if",
"@cli",
"logger",
".",
"error",
"(",
"msg",
")",
"exit",
"(",
"true",
")",
"else",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"CriticalPluginFailure",
",",
"\"#{msg}. Failing Chef run.\"",
"end",
"end",
"# Freeze all strings.",
"freeze_strings!",
"end"
] |
run all plugins or those that match the attribute filter is provided
@param safe [Boolean]
@param [Array<String>] attribute_filter the attributes to run. All will be run if not specified
@return [Mash]
|
[
"run",
"all",
"plugins",
"or",
"those",
"that",
"match",
"the",
"attribute",
"filter",
"is",
"provided"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/system.rb#L109-L131
|
11,516
|
chef/ohai
|
lib/ohai/system.rb
|
Ohai.System.json_pretty_print
|
def json_pretty_print(item = nil)
FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data)
end
|
ruby
|
def json_pretty_print(item = nil)
FFI_Yajl::Encoder.new(pretty: true, validate_utf8: false).encode(item || @data)
end
|
[
"def",
"json_pretty_print",
"(",
"item",
"=",
"nil",
")",
"FFI_Yajl",
"::",
"Encoder",
".",
"new",
"(",
"pretty",
":",
"true",
",",
"validate_utf8",
":",
"false",
")",
".",
"encode",
"(",
"item",
"||",
"@data",
")",
"end"
] |
Pretty Print this object as JSON
|
[
"Pretty",
"Print",
"this",
"object",
"as",
"JSON"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/system.rb#L152-L154
|
11,517
|
chef/ohai
|
lib/ohai/provides_map.rb
|
Ohai.ProvidesMap.find_providers_for
|
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 attribute: \'#{attribute}\'" unless attrs[:_plugins]
plugins += attrs[:_plugins]
end
plugins.uniq
end
|
ruby
|
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 attribute: \'#{attribute}\'" unless attrs[:_plugins]
plugins += attrs[:_plugins]
end
plugins.uniq
end
|
[
"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 attribute: \\'#{attribute}\\'\"",
"unless",
"attrs",
"[",
":_plugins",
"]",
"plugins",
"+=",
"attrs",
"[",
":_plugins",
"]",
"end",
"plugins",
".",
"uniq",
"end"
] |
gather plugins providing exactly the attributes listed
|
[
"gather",
"plugins",
"providing",
"exactly",
"the",
"attributes",
"listed"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L52-L61
|
11,518
|
chef/ohai
|
lib/ohai/provides_map.rb
|
Ohai.ProvidesMap.deep_find_providers_for
|
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 attribute: \'#{attribute}\'"
end
end
collect_plugins_in(attrs, plugins)
end
plugins.uniq
end
|
ruby
|
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 attribute: \'#{attribute}\'"
end
end
collect_plugins_in(attrs, plugins)
end
plugins.uniq
end
|
[
"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 attribute: \\'#{attribute}\\'\"",
"end",
"end",
"collect_plugins_in",
"(",
"attrs",
",",
"plugins",
")",
"end",
"plugins",
".",
"uniq",
"end"
] |
This function is used to fetch the plugins for the attributes specified
in the CLI options to Ohai.
It first attempts to find the plugins for the attributes
or the sub attributes given.
If it can't find any, it looks for plugins that might
provide the parents of a given attribute and returns the
first parent found.
|
[
"This",
"function",
"is",
"used",
"to",
"fetch",
"the",
"plugins",
"for",
"the",
"attributes",
"specified",
"in",
"the",
"CLI",
"options",
"to",
"Ohai",
".",
"It",
"first",
"attempts",
"to",
"find",
"the",
"plugins",
"for",
"the",
"attributes",
"or",
"the",
"sub",
"attributes",
"given",
".",
"If",
"it",
"can",
"t",
"find",
"any",
"it",
"looks",
"for",
"plugins",
"that",
"might",
"provide",
"the",
"parents",
"of",
"a",
"given",
"attribute",
"and",
"returns",
"the",
"first",
"parent",
"found",
"."
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L70-L87
|
11,519
|
chef/ohai
|
lib/ohai/provides_map.rb
|
Ohai.ProvidesMap.find_closest_providers_for
|
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)
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs
plugins += attrs[:_plugins]
end
plugins.uniq
end
|
ruby
|
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)
raise Ohai::Exceptions::ProviderNotFound, "Cannot find plugin providing attribute: \'#{attribute}\'" unless attrs
plugins += attrs[:_plugins]
end
plugins.uniq
end
|
[
"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",
")",
"raise",
"Ohai",
"::",
"Exceptions",
"::",
"ProviderNotFound",
",",
"\"Cannot find plugin providing attribute: \\'#{attribute}\\'\"",
"unless",
"attrs",
"plugins",
"+=",
"attrs",
"[",
":_plugins",
"]",
"end",
"plugins",
".",
"uniq",
"end"
] |
This function is used to fetch the plugins from
'depends "languages"' statements in plugins.
It gathers plugins providing each of the attributes listed, or the
plugins providing the closest parent attribute
|
[
"This",
"function",
"is",
"used",
"to",
"fetch",
"the",
"plugins",
"from",
"depends",
"languages",
"statements",
"in",
"plugins",
".",
"It",
"gathers",
"plugins",
"providing",
"each",
"of",
"the",
"attributes",
"listed",
"or",
"the",
"plugins",
"providing",
"the",
"closest",
"parent",
"attribute"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L93-L103
|
11,520
|
chef/ohai
|
lib/ohai/provides_map.rb
|
Ohai.ProvidesMap.collect_plugins_in
|
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
|
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
|
[
"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"
] |
Takes a section of the map, recursively searches for a `_plugins` key
to find all the plugins in that section of the map. If given the whole
map, it will find all of the plugins that have at least one provided
attribute.
|
[
"Takes",
"a",
"section",
"of",
"the",
"map",
"recursively",
"searches",
"for",
"a",
"_plugins",
"key",
"to",
"find",
"all",
"the",
"plugins",
"in",
"that",
"section",
"of",
"the",
"map",
".",
"If",
"given",
"the",
"whole",
"map",
"it",
"will",
"find",
"all",
"of",
"the",
"plugins",
"that",
"have",
"at",
"least",
"one",
"provided",
"attribute",
"."
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/provides_map.rb#L173-L182
|
11,521
|
chef/ohai
|
lib/ohai/loader.rb
|
Ohai.Loader.plugin_files_by_dir
|
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")]
else
Ohai::Log.debug("The plugin path #{path} does not exist. Skipping...")
[]
end
end.flatten
end
|
ruby
|
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")]
else
Ohai::Log.debug("The plugin path #{path} does not exist. Skipping...")
[]
end
end.flatten
end
|
[
"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\"",
")",
"]",
"else",
"Ohai",
"::",
"Log",
".",
"debug",
"(",
"\"The plugin path #{path} does not exist. Skipping...\"",
")",
"[",
"]",
"end",
"end",
".",
"flatten",
"end"
] |
Searches all plugin paths and returns an Array of file paths to plugins
@param dir [Array, String] directory/directories to load plugins from
@return [Array<String>]
|
[
"Searches",
"all",
"plugin",
"paths",
"and",
"returns",
"an",
"Array",
"of",
"file",
"paths",
"to",
"plugins"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L43-L55
|
11,522
|
chef/ohai
|
lib/ohai/loader.rb
|
Ohai.Loader.load_additional
|
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
|
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
|
[
"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"
] |
load additional plugins classes from a given directory
@param from [String] path to a directory with additional plugins to load
|
[
"load",
"additional",
"plugins",
"classes",
"from",
"a",
"given",
"directory"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L70-L77
|
11,523
|
chef/ohai
|
lib/ohai/loader.rb
|
Ohai.Loader.load_plugin
|
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 #{plugin_class}"
end
end
|
ruby
|
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 #{plugin_class}"
end
end
|
[
"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 #{plugin_class}\"",
"end",
"end"
] |
Load a specified file as an ohai plugin and creates an instance of it.
Not used by ohai itself, but is used in the specs to load plugins for testing
@private
@param plugin_path [String]
|
[
"Load",
"a",
"specified",
"file",
"as",
"an",
"ohai",
"plugin",
"and",
"creates",
"an",
"instance",
"of",
"it",
".",
"Not",
"used",
"by",
"ohai",
"itself",
"but",
"is",
"used",
"in",
"the",
"specs",
"to",
"load",
"plugins",
"for",
"testing"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/loader.rb#L84-L92
|
11,524
|
chef/ohai
|
lib/ohai/runner.rb
|
Ohai.Runner.get_cycle
|
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
|
def get_cycle(plugins, cycle_start)
cycle = plugins.drop_while { |plugin| !plugin.eql?(cycle_start) }
names = []
cycle.each { |plugin| names << plugin.name }
names
end
|
[
"def",
"get_cycle",
"(",
"plugins",
",",
"cycle_start",
")",
"cycle",
"=",
"plugins",
".",
"drop_while",
"{",
"|",
"plugin",
"|",
"!",
"plugin",
".",
"eql?",
"(",
"cycle_start",
")",
"}",
"names",
"=",
"[",
"]",
"cycle",
".",
"each",
"{",
"|",
"plugin",
"|",
"names",
"<<",
"plugin",
".",
"name",
"}",
"names",
"end"
] |
Given a list of plugins and the first plugin in the cycle,
returns the list of plugin source files responsible for the
cycle. Does not include plugins that aren't a part of the cycle
|
[
"Given",
"a",
"list",
"of",
"plugins",
"and",
"the",
"first",
"plugin",
"in",
"the",
"cycle",
"returns",
"the",
"list",
"of",
"plugin",
"source",
"files",
"responsible",
"for",
"the",
"cycle",
".",
"Does",
"not",
"include",
"plugins",
"that",
"aren",
"t",
"a",
"part",
"of",
"the",
"cycle"
] |
8d66449940f04237586b2f928231c6b26e2cc19a
|
https://github.com/chef/ohai/blob/8d66449940f04237586b2f928231c6b26e2cc19a/lib/ohai/runner.rb#L104-L109
|
11,525
|
ruby2d/ruby2d
|
lib/ruby2d/triangle.rb
|
Ruby2D.Triangle.contains?
|
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
|
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
|
[
"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"
] |
A point is inside a triangle if the area of 3 triangles, constructed from
triangle sides and the given point, is equal to the area of triangle.
|
[
"A",
"point",
"is",
"inside",
"a",
"triangle",
"if",
"the",
"area",
"of",
"3",
"triangles",
"constructed",
"from",
"triangle",
"sides",
"and",
"the",
"given",
"point",
"is",
"equal",
"to",
"the",
"area",
"of",
"triangle",
"."
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/triangle.rb#L31-L39
|
11,526
|
ruby2d/ruby2d
|
lib/ruby2d/sprite.rb
|
Ruby2D.Sprite.play
|
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[@playing_animation]
flip_sprite(flip)
@done_proc = done_proc
case frames
# When animation is a range, play through frames horizontally
when Range
@first_frame = frames.first || @defaults[:frame]
@current_frame = frames.first || @defaults[:frame]
@last_frame = frames.last
# When array...
when Array
@first_frame = 0
@current_frame = 0
@last_frame = frames.length - 1
end
# Set looping
@loop = loop == true || @defaults[:loop] ? true : false
set_frame
restart_time
end
end
|
ruby
|
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[@playing_animation]
flip_sprite(flip)
@done_proc = done_proc
case frames
# When animation is a range, play through frames horizontally
when Range
@first_frame = frames.first || @defaults[:frame]
@current_frame = frames.first || @defaults[:frame]
@last_frame = frames.last
# When array...
when Array
@first_frame = 0
@current_frame = 0
@last_frame = frames.length - 1
end
# Set looping
@loop = loop == true || @defaults[:loop] ? true : false
set_frame
restart_time
end
end
|
[
"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",
"[",
"@playing_animation",
"]",
"flip_sprite",
"(",
"flip",
")",
"@done_proc",
"=",
"done_proc",
"case",
"frames",
"# When animation is a range, play through frames horizontally",
"when",
"Range",
"@first_frame",
"=",
"frames",
".",
"first",
"||",
"@defaults",
"[",
":frame",
"]",
"@current_frame",
"=",
"frames",
".",
"first",
"||",
"@defaults",
"[",
":frame",
"]",
"@last_frame",
"=",
"frames",
".",
"last",
"# When array...",
"when",
"Array",
"@first_frame",
"=",
"0",
"@current_frame",
"=",
"0",
"@last_frame",
"=",
"frames",
".",
"length",
"-",
"1",
"end",
"# Set looping",
"@loop",
"=",
"loop",
"==",
"true",
"||",
"@defaults",
"[",
":loop",
"]",
"?",
"true",
":",
"false",
"set_frame",
"restart_time",
"end",
"end"
] |
Play an animation
|
[
"Play",
"an",
"animation"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/sprite.rb#L111-L144
|
11,527
|
ruby2d/ruby2d
|
lib/ruby2d/sprite.rb
|
Ruby2D.Sprite.set_frame
|
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] || @defaults[:clip_y]
@clip_width = f[:width] || @defaults[:clip_width]
@clip_height = f[:height] || @defaults[:clip_height]
@frame_time = f[:time] || @defaults[:frame_time]
end
end
|
ruby
|
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] || @defaults[:clip_y]
@clip_width = f[:width] || @defaults[:clip_width]
@clip_height = f[:height] || @defaults[:clip_height]
@frame_time = f[:time] || @defaults[:frame_time]
end
end
|
[
"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",
"]",
"||",
"@defaults",
"[",
":clip_y",
"]",
"@clip_width",
"=",
"f",
"[",
":width",
"]",
"||",
"@defaults",
"[",
":clip_width",
"]",
"@clip_height",
"=",
"f",
"[",
":height",
"]",
"||",
"@defaults",
"[",
":clip_height",
"]",
"@frame_time",
"=",
"f",
"[",
":time",
"]",
"||",
"@defaults",
"[",
":frame_time",
"]",
"end",
"end"
] |
Set the position of the clipping retangle based on the current frame
|
[
"Set",
"the",
"position",
"of",
"the",
"clipping",
"retangle",
"based",
"on",
"the",
"current",
"frame"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/sprite.rb#L198-L212
|
11,528
|
ruby2d/ruby2d
|
lib/ruby2d/line.rb
|
Ruby2D.Line.points_distance
|
def points_distance(x1, y1, x2, y2)
Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
end
|
ruby
|
def points_distance(x1, y1, x2, y2)
Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
end
|
[
"def",
"points_distance",
"(",
"x1",
",",
"y1",
",",
"x2",
",",
"y2",
")",
"Math",
".",
"sqrt",
"(",
"(",
"x1",
"-",
"x2",
")",
"**",
"2",
"+",
"(",
"y1",
"-",
"y2",
")",
"**",
"2",
")",
"end"
] |
Calculate the distance between two points
|
[
"Calculate",
"the",
"distance",
"between",
"two",
"points"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/line.rb#L44-L46
|
11,529
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.set
|
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[:width] || @width
@height = opts[:height] || @height
@fps_cap = opts[:fps_cap] || @fps_cap
@viewport_width = opts[:viewport_width] || @viewport_width
@viewport_height = opts[:viewport_height] || @viewport_height
@resizable = opts[:resizable] || @resizable
@borderless = opts[:borderless] || @borderless
@fullscreen = opts[:fullscreen] || @fullscreen
@highdpi = opts[:highdpi] || @highdpi
unless opts[:diagnostics].nil?
@diagnostics = opts[:diagnostics]
ext_diagnostics(@diagnostics)
end
end
|
ruby
|
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[:width] || @width
@height = opts[:height] || @height
@fps_cap = opts[:fps_cap] || @fps_cap
@viewport_width = opts[:viewport_width] || @viewport_width
@viewport_height = opts[:viewport_height] || @viewport_height
@resizable = opts[:resizable] || @resizable
@borderless = opts[:borderless] || @borderless
@fullscreen = opts[:fullscreen] || @fullscreen
@highdpi = opts[:highdpi] || @highdpi
unless opts[:diagnostics].nil?
@diagnostics = opts[:diagnostics]
ext_diagnostics(@diagnostics)
end
end
|
[
"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",
"[",
":width",
"]",
"||",
"@width",
"@height",
"=",
"opts",
"[",
":height",
"]",
"||",
"@height",
"@fps_cap",
"=",
"opts",
"[",
":fps_cap",
"]",
"||",
"@fps_cap",
"@viewport_width",
"=",
"opts",
"[",
":viewport_width",
"]",
"||",
"@viewport_width",
"@viewport_height",
"=",
"opts",
"[",
":viewport_height",
"]",
"||",
"@viewport_height",
"@resizable",
"=",
"opts",
"[",
":resizable",
"]",
"||",
"@resizable",
"@borderless",
"=",
"opts",
"[",
":borderless",
"]",
"||",
"@borderless",
"@fullscreen",
"=",
"opts",
"[",
":fullscreen",
"]",
"||",
"@fullscreen",
"@highdpi",
"=",
"opts",
"[",
":highdpi",
"]",
"||",
"@highdpi",
"unless",
"opts",
"[",
":diagnostics",
"]",
".",
"nil?",
"@diagnostics",
"=",
"opts",
"[",
":diagnostics",
"]",
"ext_diagnostics",
"(",
"@diagnostics",
")",
"end",
"end"
] |
Set a window attribute
|
[
"Set",
"a",
"window",
"attribute"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L195-L215
|
11,530
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.add
|
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
|
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
|
[
"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"
] |
Add an object to the window
|
[
"Add",
"an",
"object",
"to",
"the",
"window"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L218-L227
|
11,531
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.remove
|
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
|
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
|
[
"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"
] |
Remove an object from the window
|
[
"Remove",
"an",
"object",
"from",
"the",
"window"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L230-L241
|
11,532
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.on
|
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
|
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
|
[
"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"
] |
Set an event handler
|
[
"Set",
"an",
"event",
"handler"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L260-L267
|
11,533
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.key_callback
|
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))
end
# When key is being held down, fired every frame
when :held
@events[:key_held].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key released, fired once
when :up
@events[:key_up].each do |id, e|
e.call(KeyEvent.new(type, key))
end
end
end
|
ruby
|
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))
end
# When key is being held down, fired every frame
when :held
@events[:key_held].each do |id, e|
e.call(KeyEvent.new(type, key))
end
# When key released, fired once
when :up
@events[:key_up].each do |id, e|
e.call(KeyEvent.new(type, key))
end
end
end
|
[
"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",
")",
")",
"end",
"# When key is being held down, fired every frame",
"when",
":held",
"@events",
"[",
":key_held",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"# When key released, fired once",
"when",
":up",
"@events",
"[",
":key_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"KeyEvent",
".",
"new",
"(",
"type",
",",
"key",
")",
")",
"end",
"end",
"end"
] |
Key callback method, called by the native and web extentions
|
[
"Key",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L275-L300
|
11,534
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.mouse_callback
|
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].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse button released
when :up
@events[:mouse_up].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse motion / movement
when :scroll
@events[:mouse_scroll].each do |id, e|
e.call(MouseEvent.new(type, nil, direction, nil, nil, delta_x, delta_y))
end
# When mouse scrolling, wheel or trackpad
when :move
@events[:mouse_move].each do |id, e|
e.call(MouseEvent.new(type, nil, nil, x, y, delta_x, delta_y))
end
end
end
|
ruby
|
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].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse button released
when :up
@events[:mouse_up].each do |id, e|
e.call(MouseEvent.new(type, button, nil, x, y, nil, nil))
end
# When mouse motion / movement
when :scroll
@events[:mouse_scroll].each do |id, e|
e.call(MouseEvent.new(type, nil, direction, nil, nil, delta_x, delta_y))
end
# When mouse scrolling, wheel or trackpad
when :move
@events[:mouse_move].each do |id, e|
e.call(MouseEvent.new(type, nil, nil, x, y, delta_x, delta_y))
end
end
end
|
[
"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",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"button",
",",
"nil",
",",
"x",
",",
"y",
",",
"nil",
",",
"nil",
")",
")",
"end",
"# When mouse button released",
"when",
":up",
"@events",
"[",
":mouse_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"button",
",",
"nil",
",",
"x",
",",
"y",
",",
"nil",
",",
"nil",
")",
")",
"end",
"# When mouse motion / movement",
"when",
":scroll",
"@events",
"[",
":mouse_scroll",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"nil",
",",
"direction",
",",
"nil",
",",
"nil",
",",
"delta_x",
",",
"delta_y",
")",
")",
"end",
"# When mouse scrolling, wheel or trackpad",
"when",
":move",
"@events",
"[",
":mouse_move",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"MouseEvent",
".",
"new",
"(",
"type",
",",
"nil",
",",
"nil",
",",
"x",
",",
"y",
",",
"delta_x",
",",
"delta_y",
")",
")",
"end",
"end",
"end"
] |
Mouse callback method, called by the native and web extentions
|
[
"Mouse",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L303-L331
|
11,535
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.controller_callback
|
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[:controller_axis].each do |id, e|
e.call(ControllerAxisEvent.new(which, axis, value))
end
# When controller button is pressed
when :button_down
@events[:controller_button_down].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
# When controller button is released
when :button_up
@events[:controller_button_up].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
end
end
|
ruby
|
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[:controller_axis].each do |id, e|
e.call(ControllerAxisEvent.new(which, axis, value))
end
# When controller button is pressed
when :button_down
@events[:controller_button_down].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
# When controller button is released
when :button_up
@events[:controller_button_up].each do |id, e|
e.call(ControllerButtonEvent.new(which, button))
end
end
end
|
[
"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",
"[",
":controller_axis",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerAxisEvent",
".",
"new",
"(",
"which",
",",
"axis",
",",
"value",
")",
")",
"end",
"# When controller button is pressed",
"when",
":button_down",
"@events",
"[",
":controller_button_down",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerButtonEvent",
".",
"new",
"(",
"which",
",",
"button",
")",
")",
"end",
"# When controller button is released",
"when",
":button_up",
"@events",
"[",
":controller_button_up",
"]",
".",
"each",
"do",
"|",
"id",
",",
"e",
"|",
"e",
".",
"call",
"(",
"ControllerButtonEvent",
".",
"new",
"(",
"which",
",",
"button",
")",
")",
"end",
"end",
"end"
] |
Controller callback method, called by the native and web extentions
|
[
"Controller",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L341-L364
|
11,536
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.update_callback
|
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 SyntaxError => se
STDOUT.puts se
STDOUT.flush
rescue Exception => e
STDOUT.puts e
STDOUT.flush
end
end
end
end
|
ruby
|
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 SyntaxError => se
STDOUT.puts se
STDOUT.flush
rescue Exception => e
STDOUT.puts e
STDOUT.flush
end
end
end
end
|
[
"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",
"SyntaxError",
"=>",
"se",
"STDOUT",
".",
"puts",
"se",
"STDOUT",
".",
"flush",
"rescue",
"Exception",
"=>",
"e",
"STDOUT",
".",
"puts",
"e",
"STDOUT",
".",
"flush",
"end",
"end",
"end",
"end"
] |
Update callback method, called by the native and web extentions
|
[
"Update",
"callback",
"method",
"called",
"by",
"the",
"native",
"and",
"web",
"extentions"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L367-L388
|
11,537
|
ruby2d/ruby2d
|
lib/ruby2d/window.rb
|
Ruby2D.Window.add_object
|
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
|
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
|
[
"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"
] |
An an object to the window, used by the public `add` method
|
[
"An",
"an",
"object",
"to",
"the",
"window",
"used",
"by",
"the",
"public",
"add",
"method"
] |
43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4
|
https://github.com/ruby2d/ruby2d/blob/43ce9805a7ae8b82b7ab8c50bf6d4c845d395dc4/lib/ruby2d/window.rb#L419-L433
|
11,538
|
scenic-views/scenic
|
lib/scenic/statements.rb
|
Scenic.Statements.create_view
|
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
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.create_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.create_view(name, sql_definition)
end
end
|
ruby
|
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
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.create_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.create_view(name, sql_definition)
end
end
|
[
"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",
"end",
"sql_definition",
"||=",
"definition",
"(",
"name",
",",
"version",
")",
"if",
"materialized",
"Scenic",
".",
"database",
".",
"create_materialized_view",
"(",
"name",
",",
"sql_definition",
",",
"no_data",
":",
"no_data",
"(",
"materialized",
")",
",",
")",
"else",
"Scenic",
".",
"database",
".",
"create_view",
"(",
"name",
",",
"sql_definition",
")",
"end",
"end"
] |
Create a new database view.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view, used to find the
definition file in `db/views`. This defaults to `1` if not provided.
@param sql_definition [String] The SQL query for the view schema. An error
will be raised if `sql_definition` and `version` are both set,
as they are mutually exclusive.
@param materialized [Boolean, Hash] Set to true to create a materialized
view. Set to { no_data: true } to create materialized view without
loading data. Defaults to false.
@return The database response from executing the create statement.
@example Create from `db/views/searches_v02.sql`
create_view(:searches, version: 2)
@example Create from provided SQL string
create_view(:active_users, sql_definition: <<-SQL)
SELECT * FROM users WHERE users.active = 't'
SQL
|
[
"Create",
"a",
"new",
"database",
"view",
"."
] |
cc6adbde2bded9c895c41025d371c4c0f34c9253
|
https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L25-L48
|
11,539
|
scenic-views/scenic
|
lib/scenic/statements.rb
|
Scenic.Statements.drop_view
|
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
|
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
|
[
"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"
] |
Drop a database view by name.
@param name [String, Symbol] The name of the database view.
@param revert_to_version [Fixnum] Used to reverse the `drop_view` command
on `rake db:rollback`. The provided version will be passed as the
`version` argument to {#create_view}.
@param materialized [Boolean] Set to true if dropping a meterialized view.
defaults to false.
@return The database response from executing the drop statement.
@example Drop a view, rolling back to version 3 on rollback
drop_view(:users_who_recently_logged_in, revert_to_version: 3)
|
[
"Drop",
"a",
"database",
"view",
"by",
"name",
"."
] |
cc6adbde2bded9c895c41025d371c4c0f34c9253
|
https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L63-L69
|
11,540
|
scenic-views/scenic
|
lib/scenic/statements.rb
|
Scenic.Statements.update_view
|
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?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.update_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.update_view(name, sql_definition)
end
end
|
ruby
|
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?
raise(
ArgumentError,
"sql_definition and version cannot both be set",
)
end
sql_definition ||= definition(name, version)
if materialized
Scenic.database.update_materialized_view(
name,
sql_definition,
no_data: no_data(materialized),
)
else
Scenic.database.update_view(name, sql_definition)
end
end
|
[
"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?",
"raise",
"(",
"ArgumentError",
",",
"\"sql_definition and version cannot both be set\"",
",",
")",
"end",
"sql_definition",
"||=",
"definition",
"(",
"name",
",",
"version",
")",
"if",
"materialized",
"Scenic",
".",
"database",
".",
"update_materialized_view",
"(",
"name",
",",
"sql_definition",
",",
"no_data",
":",
"no_data",
"(",
"materialized",
")",
",",
")",
"else",
"Scenic",
".",
"database",
".",
"update_view",
"(",
"name",
",",
"sql_definition",
")",
"end",
"end"
] |
Update a database view to a new version.
The existing view is dropped and recreated using the supplied `version`
parameter.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view.
@param sql_definition [String] The SQL query for the view schema. An error
will be raised if `sql_definition` and `version` are both set,
as they are mutually exclusive.
@param revert_to_version [Fixnum] The version number to rollback to on
`rake db rollback`
@param materialized [Boolean, Hash] True if updating a materialized view.
Set to { no_data: true } to update materialized view without loading
data. Defaults to false.
@return The database response from executing the create statement.
@example
update_view :engagement_reports, version: 3, revert_to_version: 2
|
[
"Update",
"a",
"database",
"view",
"to",
"a",
"new",
"version",
"."
] |
cc6adbde2bded9c895c41025d371c4c0f34c9253
|
https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L91-L117
|
11,541
|
scenic-views/scenic
|
lib/scenic/statements.rb
|
Scenic.Statements.replace_view
|
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)
Scenic.database.replace_view(name, sql_definition)
end
|
ruby
|
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)
Scenic.database.replace_view(name, sql_definition)
end
|
[
"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",
")",
"Scenic",
".",
"database",
".",
"replace_view",
"(",
"name",
",",
"sql_definition",
")",
"end"
] |
Update a database view to a new version using `CREATE OR REPLACE VIEW`.
The existing view is replaced using the supplied `version`
parameter.
Does not work with materialized views due to lack of database support.
@param name [String, Symbol] The name of the database view.
@param version [Fixnum] The version number of the view.
@param revert_to_version [Fixnum] The version number to rollback to on
`rake db rollback`
@return The database response from executing the create statement.
@example
replace_view :engagement_reports, version: 3, revert_to_version: 2
|
[
"Update",
"a",
"database",
"view",
"to",
"a",
"new",
"version",
"using",
"CREATE",
"OR",
"REPLACE",
"VIEW",
"."
] |
cc6adbde2bded9c895c41025d371c4c0f34c9253
|
https://github.com/scenic-views/scenic/blob/cc6adbde2bded9c895c41025d371c4c0f34c9253/lib/scenic/statements.rb#L135-L147
|
11,542
|
RailsEventStore/rails_event_store
|
ruby_event_store/lib/ruby_event_store/event.rb
|
RubyEventStore.Event.to_h
|
def to_h
{
event_id: event_id,
metadata: metadata.to_h,
data: data,
type: type,
}
end
|
ruby
|
def to_h
{
event_id: event_id,
metadata: metadata.to_h,
data: data,
type: type,
}
end
|
[
"def",
"to_h",
"{",
"event_id",
":",
"event_id",
",",
"metadata",
":",
"metadata",
".",
"to_h",
",",
"data",
":",
"data",
",",
"type",
":",
"type",
",",
"}",
"end"
] |
Returns a hash representation of the event.
Metadata is converted to hash as well
@return [Hash] with :event_id, :metadata, :data, :type keys
|
[
"Returns",
"a",
"hash",
"representation",
"of",
"the",
"event",
"."
] |
3ee4f3148499794154ee6fec74ccf6d4670d85ac
|
https://github.com/RailsEventStore/rails_event_store/blob/3ee4f3148499794154ee6fec74ccf6d4670d85ac/ruby_event_store/lib/ruby_event_store/event.rb#L40-L47
|
11,543
|
RailsEventStore/rails_event_store
|
ruby_event_store/lib/ruby_event_store/client.rb
|
RubyEventStore.Client.publish
|
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)
enriched_events.zip(serialized_events) do |event, serialized_event|
with_metadata(
correlation_id: event.metadata[:correlation_id] || event.event_id,
causation_id: event.event_id,
) do
broker.(event, serialized_event)
end
end
self
end
|
ruby
|
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)
enriched_events.zip(serialized_events) do |event, serialized_event|
with_metadata(
correlation_id: event.metadata[:correlation_id] || event.event_id,
causation_id: event.event_id,
) do
broker.(event, serialized_event)
end
end
self
end
|
[
"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",
")",
"enriched_events",
".",
"zip",
"(",
"serialized_events",
")",
"do",
"|",
"event",
",",
"serialized_event",
"|",
"with_metadata",
"(",
"correlation_id",
":",
"event",
".",
"metadata",
"[",
":correlation_id",
"]",
"||",
"event",
".",
"event_id",
",",
"causation_id",
":",
"event",
".",
"event_id",
",",
")",
"do",
"broker",
".",
"(",
"event",
",",
"serialized_event",
")",
"end",
"end",
"self",
"end"
] |
Persists events and notifies subscribed handlers about them
@param events [Array<Event, Proto>, Event, Proto] event(s)
@param stream_name [String] name of the stream for persisting events.
@param expected_version [:any, :auto, :none, Integer] controls optimistic locking strategy. {http://railseventstore.org/docs/expected_version/ Read more}
@return [self]
|
[
"Persists",
"events",
"and",
"notifies",
"subscribed",
"handlers",
"about",
"them"
] |
3ee4f3148499794154ee6fec74ccf6d4670d85ac
|
https://github.com/RailsEventStore/rails_event_store/blob/3ee4f3148499794154ee6fec74ccf6d4670d85ac/ruby_event_store/lib/ruby_event_store/client.rb#L25-L38
|
11,544
|
twitter/secure_headers
|
lib/secure_headers/middleware.rb
|
SecureHeaders.Middleware.call
|
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, headers, response]
end
|
ruby
|
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, headers, response]
end
|
[
"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",
",",
"headers",
",",
"response",
"]",
"end"
] |
merges the hash of headers into the current header set.
|
[
"merges",
"the",
"hash",
"of",
"headers",
"into",
"the",
"current",
"header",
"set",
"."
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/middleware.rb#L9-L17
|
11,545
|
twitter/secure_headers
|
lib/secure_headers/middleware.rb
|
SecureHeaders.Middleware.override_secure
|
def override_secure(env, config = {})
if scheme(env) != "https" && config != OPT_OUT
config[:secure] = OPT_OUT
end
config
end
|
ruby
|
def override_secure(env, config = {})
if scheme(env) != "https" && config != OPT_OUT
config[:secure] = OPT_OUT
end
config
end
|
[
"def",
"override_secure",
"(",
"env",
",",
"config",
"=",
"{",
"}",
")",
"if",
"scheme",
"(",
"env",
")",
"!=",
"\"https\"",
"&&",
"config",
"!=",
"OPT_OUT",
"config",
"[",
":secure",
"]",
"=",
"OPT_OUT",
"end",
"config",
"end"
] |
disable Secure cookies for non-https requests
|
[
"disable",
"Secure",
"cookies",
"for",
"non",
"-",
"https",
"requests"
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/middleware.rb#L34-L40
|
11,546
|
twitter/secure_headers
|
lib/secure_headers/utils/cookies_config.rb
|
SecureHeaders.CookiesConfig.validate_samesite_boolean_config!
|
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 permitted.")
elsif config[:samesite].key?(:strict) && config[:samesite][:strict].is_a?(TrueClass) && config[:samesite].key?(:lax)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
end
end
|
ruby
|
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 permitted.")
elsif config[:samesite].key?(:strict) && config[:samesite][:strict].is_a?(TrueClass) && config[:samesite].key?(:lax)
raise CookiesConfigError.new("samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.")
end
end
|
[
"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 permitted.\"",
")",
"elsif",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":strict",
")",
"&&",
"config",
"[",
":samesite",
"]",
"[",
":strict",
"]",
".",
"is_a?",
"(",
"TrueClass",
")",
"&&",
"config",
"[",
":samesite",
"]",
".",
"key?",
"(",
":lax",
")",
"raise",
"CookiesConfigError",
".",
"new",
"(",
"\"samesite cookie config is invalid, combination use of booleans and Hash to configure lax and strict enforcement is not permitted.\"",
")",
"end",
"end"
] |
when configuring with booleans, only one enforcement is permitted
|
[
"when",
"configuring",
"with",
"booleans",
"only",
"one",
"enforcement",
"is",
"permitted"
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L45-L51
|
11,547
|
twitter/secure_headers
|
lib/secure_headers/utils/cookies_config.rb
|
SecureHeaders.CookiesConfig.validate_exclusive_use_of_hash_constraints!
|
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
end
|
ruby
|
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
end
|
[
"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",
"end"
] |
validate exclusive use of only or except but not both at the same time
|
[
"validate",
"exclusive",
"use",
"of",
"only",
"or",
"except",
"but",
"not",
"both",
"at",
"the",
"same",
"time"
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L73-L78
|
11,548
|
twitter/secure_headers
|
lib/secure_headers/utils/cookies_config.rb
|
SecureHeaders.CookiesConfig.validate_exclusive_use_of_samesite_enforcement!
|
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 as lax and strict")
end
end
|
ruby
|
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 as lax and strict")
end
end
|
[
"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 as lax and strict\"",
")",
"end",
"end"
] |
validate exclusivity of only and except members within strict and lax
|
[
"validate",
"exclusivity",
"of",
"only",
"and",
"except",
"members",
"within",
"strict",
"and",
"lax"
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/utils/cookies_config.rb#L81-L85
|
11,549
|
twitter/secure_headers
|
lib/secure_headers/headers/content_security_policy.rb
|
SecureHeaders.ContentSecurityPolicy.reject_all_values_if_none
|
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
|
def reject_all_values_if_none(source_list)
if source_list.length > 1
source_list.reject { |value| value == NONE }
else
source_list
end
end
|
[
"def",
"reject_all_values_if_none",
"(",
"source_list",
")",
"if",
"source_list",
".",
"length",
">",
"1",
"source_list",
".",
"reject",
"{",
"|",
"value",
"|",
"value",
"==",
"NONE",
"}",
"else",
"source_list",
"end",
"end"
] |
Discard any 'none' values if more directives are supplied since none may override values.
|
[
"Discard",
"any",
"none",
"values",
"if",
"more",
"directives",
"are",
"supplied",
"since",
"none",
"may",
"override",
"values",
"."
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/headers/content_security_policy.rb#L137-L143
|
11,550
|
twitter/secure_headers
|
lib/secure_headers/headers/content_security_policy.rb
|
SecureHeaders.ContentSecurityPolicy.dedup_source_list
|
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) }
end
else
sources
end
end
|
ruby
|
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) }
end
else
sources
end
end
|
[
"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",
")",
"}",
"end",
"else",
"sources",
"end",
"end"
] |
Removes duplicates and sources that already match an existing wild card.
e.g. *.github.com asdf.github.com becomes *.github.com
|
[
"Removes",
"duplicates",
"and",
"sources",
"that",
"already",
"match",
"an",
"existing",
"wild",
"card",
"."
] |
543e6712aadae08f1653ed973e6b6204f7eac26a
|
https://github.com/twitter/secure_headers/blob/543e6712aadae08f1653ed973e6b6204f7eac26a/lib/secure_headers/headers/content_security_policy.rb#L148-L160
|
11,551
|
ambethia/recaptcha
|
lib/recaptcha/client_helper.rb
|
Recaptcha.ClientHelper.invisible_recaptcha_tags
|
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_callback_required?(options)
case options[:ui]
when :button
html << %(<button type="submit" #{tag_attributes}>#{text}</button>\n)
when :invisible
html << %(<div data-size="invisible" #{tag_attributes}></div>\n)
when :input
html << %(<input type="submit" #{tag_attributes} value="#{text}"/>\n)
else
raise(RecaptchaError, "ReCAPTCHA ui `#{options[:ui]}` is not valid.")
end
html.respond_to?(:html_safe) ? html.html_safe : html
end
|
ruby
|
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_callback_required?(options)
case options[:ui]
when :button
html << %(<button type="submit" #{tag_attributes}>#{text}</button>\n)
when :invisible
html << %(<div data-size="invisible" #{tag_attributes}></div>\n)
when :input
html << %(<input type="submit" #{tag_attributes} value="#{text}"/>\n)
else
raise(RecaptchaError, "ReCAPTCHA ui `#{options[:ui]}` is not valid.")
end
html.respond_to?(:html_safe) ? html.html_safe : html
end
|
[
"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_callback_required?",
"(",
"options",
")",
"case",
"options",
"[",
":ui",
"]",
"when",
":button",
"html",
"<<",
"%(<button type=\"submit\" #{tag_attributes}>#{text}</button>\\n)",
"when",
":invisible",
"html",
"<<",
"%(<div data-size=\"invisible\" #{tag_attributes}></div>\\n)",
"when",
":input",
"html",
"<<",
"%(<input type=\"submit\" #{tag_attributes} value=\"#{text}\"/>\\n)",
"else",
"raise",
"(",
"RecaptchaError",
",",
"\"ReCAPTCHA ui `#{options[:ui]}` is not valid.\"",
")",
"end",
"html",
".",
"respond_to?",
"(",
":html_safe",
")",
"?",
"html",
".",
"html_safe",
":",
"html",
"end"
] |
Invisible reCAPTCHA implementation
|
[
"Invisible",
"reCAPTCHA",
"implementation"
] |
fcac97960ce29ebd7473315d9ffe89dccce6615e
|
https://github.com/ambethia/recaptcha/blob/fcac97960ce29ebd7473315d9ffe89dccce6615e/lib/recaptcha/client_helper.rb#L51-L67
|
11,552
|
ambethia/recaptcha
|
lib/recaptcha/verify.rb
|
Recaptcha.Verify.verify_recaptcha
|
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
begin
verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT
false
else
recaptcha_verify_via_api_call(request, recaptcha_response, options)
end
if verified
flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model
true
else
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.verification_failed",
"reCAPTCHA verification failed, please try again."
)
false
end
rescue Timeout::Error
if Recaptcha.configuration.handle_timeouts_gracefully
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.recaptcha_unreachable",
"Oops, we failed to validate your reCAPTCHA response. Please try again."
)
false
else
raise RecaptchaError, "Recaptcha unreachable."
end
rescue StandardError => e
raise RecaptchaError, e.message, e.backtrace
end
end
|
ruby
|
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
begin
verified = if recaptcha_response.empty? || recaptcha_response.length > G_RESPONSE_LIMIT
false
else
recaptcha_verify_via_api_call(request, recaptcha_response, options)
end
if verified
flash.delete(:recaptcha_error) if recaptcha_flash_supported? && !model
true
else
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.verification_failed",
"reCAPTCHA verification failed, please try again."
)
false
end
rescue Timeout::Error
if Recaptcha.configuration.handle_timeouts_gracefully
recaptcha_error(
model,
attribute,
options[:message],
"recaptcha.errors.recaptcha_unreachable",
"Oops, we failed to validate your reCAPTCHA response. Please try again."
)
false
else
raise RecaptchaError, "Recaptcha unreachable."
end
rescue StandardError => e
raise RecaptchaError, e.message, e.backtrace
end
end
|
[
"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",
"begin",
"verified",
"=",
"if",
"recaptcha_response",
".",
"empty?",
"||",
"recaptcha_response",
".",
"length",
">",
"G_RESPONSE_LIMIT",
"false",
"else",
"recaptcha_verify_via_api_call",
"(",
"request",
",",
"recaptcha_response",
",",
"options",
")",
"end",
"if",
"verified",
"flash",
".",
"delete",
"(",
":recaptcha_error",
")",
"if",
"recaptcha_flash_supported?",
"&&",
"!",
"model",
"true",
"else",
"recaptcha_error",
"(",
"model",
",",
"attribute",
",",
"options",
"[",
":message",
"]",
",",
"\"recaptcha.errors.verification_failed\"",
",",
"\"reCAPTCHA verification failed, please try again.\"",
")",
"false",
"end",
"rescue",
"Timeout",
"::",
"Error",
"if",
"Recaptcha",
".",
"configuration",
".",
"handle_timeouts_gracefully",
"recaptcha_error",
"(",
"model",
",",
"attribute",
",",
"options",
"[",
":message",
"]",
",",
"\"recaptcha.errors.recaptcha_unreachable\"",
",",
"\"Oops, we failed to validate your reCAPTCHA response. Please try again.\"",
")",
"false",
"else",
"raise",
"RecaptchaError",
",",
"\"Recaptcha unreachable.\"",
"end",
"rescue",
"StandardError",
"=>",
"e",
"raise",
"RecaptchaError",
",",
"e",
".",
"message",
",",
"e",
".",
"backtrace",
"end",
"end"
] |
Your private API can be specified in the +options+ hash or preferably
using the Configuration.
|
[
"Your",
"private",
"API",
"can",
"be",
"specified",
"in",
"the",
"+",
"options",
"+",
"hash",
"or",
"preferably",
"using",
"the",
"Configuration",
"."
] |
fcac97960ce29ebd7473315d9ffe89dccce6615e
|
https://github.com/ambethia/recaptcha/blob/fcac97960ce29ebd7473315d9ffe89dccce6615e/lib/recaptcha/verify.rb#L10-L54
|
11,553
|
sds/haml-lint
|
lib/haml_lint/configuration.rb
|
HamlLint.Configuration.for_linter
|
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
|
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
|
[
"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"
] |
Compares this configuration with another.
@param other [HamlLint::Configuration]
@return [true,false] whether the given configuration is equivalent
Returns a non-modifiable configuration for the specified linter.
@param linter [HamlLint::Linter,Class]
|
[
"Compares",
"this",
"configuration",
"with",
"another",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/configuration.rb#L43-L53
|
11,554
|
sds/haml-lint
|
lib/haml_lint/configuration.rb
|
HamlLint.Configuration.smart_merge
|
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
|
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
|
[
"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"
] |
Merge two hashes such that nested hashes are merged rather than replaced.
@param parent [Hash]
@param child [Hash]
@return [Hash]
|
[
"Merge",
"two",
"hashes",
"such",
"that",
"nested",
"hashes",
"are",
"merged",
"rather",
"than",
"replaced",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/configuration.rb#L71-L80
|
11,555
|
sds/haml-lint
|
lib/haml_lint/reporter/disabled_config_reporter.rb
|
HamlLint.Reporter::DisabledConfigReporter.display_report
|
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: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a " \
'.haml-lint.yml file.'
end
|
ruby
|
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: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a " \
'.haml-lint.yml file.'
end
|
[
"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: #{ConfigurationLoader::AUTO_GENERATED_FILE}` in a \"",
"'.haml-lint.yml file.'",
"end"
] |
Prints the standard progress reporter output and writes the new config file.
@param report [HamlLint::Report]
@return [void]
|
[
"Prints",
"the",
"standard",
"progress",
"reporter",
"output",
"and",
"writes",
"the",
"new",
"config",
"file",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L56-L64
|
11,556
|
sds/haml-lint
|
lib/haml_lint/reporter/disabled_config_reporter.rb
|
HamlLint.Reporter::DisabledConfigReporter.finished_file
|
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
|
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
|
[
"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"
] |
Prints the standard progress report marks and tracks files with lint.
@param file [String]
@param lints [Array<HamlLint::Lint>]
@return [void]
|
[
"Prints",
"the",
"standard",
"progress",
"report",
"marks",
"and",
"tracks",
"files",
"with",
"lint",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L71-L80
|
11,557
|
sds/haml-lint
|
lib/haml_lint/reporter/disabled_config_reporter.rb
|
HamlLint.Reporter::DisabledConfigReporter.config_file_contents
|
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
|
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
|
[
"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"
] |
The contents of the generated configuration file based on captured lint.
@return [String] a Yaml-formatted configuration file's contents
|
[
"The",
"contents",
"of",
"the",
"generated",
"configuration",
"file",
"based",
"on",
"captured",
"lint",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L87-L95
|
11,558
|
sds/haml-lint
|
lib/haml_lint/reporter/disabled_config_reporter.rb
|
HamlLint.Reporter::DisabledConfigReporter.generate_config_for_linter
|
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 > exclude_limit
output << ' enabled: false'
else
output << ' exclude:'
files.each do |filename|
output << %{ - "#{filename}"}
end
end
end.join("\n")
end
|
ruby
|
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 > exclude_limit
output << ' enabled: false'
else
output << ' exclude:'
files.each do |filename|
output << %{ - "#{filename}"}
end
end
end.join("\n")
end
|
[
"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",
">",
"exclude_limit",
"output",
"<<",
"' enabled: false'",
"else",
"output",
"<<",
"' exclude:'",
"files",
".",
"each",
"do",
"|",
"filename",
"|",
"output",
"<<",
"%{ - \"#{filename}\"}",
"end",
"end",
"end",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] |
Constructs the configuration for excluding a linter in some files.
@param linter [String] the name of the linter to exclude
@param files [Array<String>] the files in which the linter is excluded
@return [String] a Yaml-formatted configuration
|
[
"Constructs",
"the",
"configuration",
"for",
"excluding",
"a",
"linter",
"in",
"some",
"files",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/reporter/disabled_config_reporter.rb#L102-L117
|
11,559
|
sds/haml-lint
|
lib/haml_lint/options.rb
|
HamlLint.Options.load_reporter_class
|
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
|
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
|
[
"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"
] |
Returns the class of the specified Reporter.
@param reporter_name [String]
@raise [HamlLint::Exceptions::InvalidCLIOption] if reporter doesn't exist
@return [Class]
|
[
"Returns",
"the",
"class",
"of",
"the",
"specified",
"Reporter",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/options.rb#L79-L84
|
11,560
|
sds/haml-lint
|
lib/haml_lint/linter/instance_variables.rb
|
HamlLint.Linter::InstanceVariables.visit_root
|
def visit_root(node)
@enabled = matcher.match(File.basename(node.file)) ? true : false
end
|
ruby
|
def visit_root(node)
@enabled = matcher.match(File.basename(node.file)) ? true : false
end
|
[
"def",
"visit_root",
"(",
"node",
")",
"@enabled",
"=",
"matcher",
".",
"match",
"(",
"File",
".",
"basename",
"(",
"node",
".",
"file",
")",
")",
"?",
"true",
":",
"false",
"end"
] |
Enables the linter if the tree is for the right file type.
@param [HamlLint::Tree::RootNode] the root of a syntax tree
@return [true, false] whether the linter is enabled for the tree
|
[
"Enables",
"the",
"linter",
"if",
"the",
"tree",
"is",
"for",
"the",
"right",
"file",
"type",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/instance_variables.rb#L12-L14
|
11,561
|
sds/haml-lint
|
lib/haml_lint/linter/instance_variables.rb
|
HamlLint.Linter::InstanceVariables.visit_tag
|
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
|
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
|
[
"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"
] |
Checks for instance variables in tag nodes when the linter is enabled.
@param [HamlLint::Tree:TagNode]
@return [void]
|
[
"Checks",
"for",
"instance",
"variables",
"in",
"tag",
"nodes",
"when",
"the",
"linter",
"is",
"enabled",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/instance_variables.rb#L39-L46
|
11,562
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.run
|
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
|
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
|
[
"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"
] |
Runs the appropriate linters against the desired files given the specified
options.
@param [Hash] options
@option options :config_file [String] path of configuration file to load
@option options :config [HamlLint::Configuration] configuration to use
@option options :excluded_files [Array<String>]
@option options :included_linters [Array<String>]
@option options :excluded_linters [Array<String>]
@option options :fail_fast [true, false] flag for failing after first failure
@option options :fail_level
@option options :reporter [HamlLint::Reporter]
@return [HamlLint::Report] a summary of all lints found
|
[
"Runs",
"the",
"appropriate",
"linters",
"against",
"the",
"desired",
"files",
"given",
"the",
"specified",
"options",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L19-L26
|
11,563
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.collect_lints
|
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, e.to_s, :error)]
end
linter_selector.linters_for_file(file).map do |linter|
linter.run(document)
end.flatten
end
|
ruby
|
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, e.to_s, :error)]
end
linter_selector.linters_for_file(file).map do |linter|
linter.run(document)
end.flatten
end
|
[
"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",
",",
"e",
".",
"to_s",
",",
":error",
")",
"]",
"end",
"linter_selector",
".",
"linters_for_file",
"(",
"file",
")",
".",
"map",
"do",
"|",
"linter",
"|",
"linter",
".",
"run",
"(",
"document",
")",
"end",
".",
"flatten",
"end"
] |
Runs all provided linters using the specified config against the given
file.
@param file [String] path to file to lint
@param linter_selector [HamlLint::LinterSelector]
@param config [HamlLint::Configuration]
|
[
"Runs",
"all",
"provided",
"linters",
"using",
"the",
"specified",
"config",
"against",
"the",
"given",
"file",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L80-L91
|
11,564
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.extract_applicable_files
|
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
|
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
|
[
"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"
] |
Returns the list of files that should be linted given the specified
configuration and options.
@param config [HamlLint::Configuration]
@param options [Hash]
@return [Array<String>]
|
[
"Returns",
"the",
"list",
"of",
"files",
"that",
"should",
"be",
"linted",
"given",
"the",
"specified",
"configuration",
"and",
"options",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L99-L105
|
11,565
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.process_files
|
def process_files(report)
files.each do |file|
process_file(file, report)
break if report.failed? && fail_fast?
end
end
|
ruby
|
def process_files(report)
files.each do |file|
process_file(file, report)
break if report.failed? && fail_fast?
end
end
|
[
"def",
"process_files",
"(",
"report",
")",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"process_file",
"(",
"file",
",",
"report",
")",
"break",
"if",
"report",
".",
"failed?",
"&&",
"fail_fast?",
"end",
"end"
] |
Process the files and add them to the given report.
@param report [HamlLint::Report]
@return [void]
|
[
"Process",
"the",
"files",
"and",
"add",
"them",
"to",
"the",
"given",
"report",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L111-L116
|
11,566
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.process_file
|
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
|
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
|
[
"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"
] |
Process a file and add it to the given report.
@param file [String] the name of the file to process
@param report [HamlLint::Report]
@return [void]
|
[
"Process",
"a",
"file",
"and",
"add",
"it",
"to",
"the",
"given",
"report",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L123-L127
|
11,567
|
sds/haml-lint
|
lib/haml_lint/runner.rb
|
HamlLint.Runner.report
|
def report(options)
report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level])
report.start(@files)
process_files(report)
report
end
|
ruby
|
def report(options)
report = HamlLint::Report.new(reporter: options[:reporter], fail_level: options[:fail_level])
report.start(@files)
process_files(report)
report
end
|
[
"def",
"report",
"(",
"options",
")",
"report",
"=",
"HamlLint",
"::",
"Report",
".",
"new",
"(",
"reporter",
":",
"options",
"[",
":reporter",
"]",
",",
"fail_level",
":",
"options",
"[",
":fail_level",
"]",
")",
"report",
".",
"start",
"(",
"@files",
")",
"process_files",
"(",
"report",
")",
"report",
"end"
] |
Generates a report based on the given options.
@param options [Hash]
@option options :reporter [HamlLint::Reporter] the reporter to report with
@return [HamlLint::Report]
|
[
"Generates",
"a",
"report",
"based",
"on",
"the",
"given",
"options",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/runner.rb#L134-L139
|
11,568
|
sds/haml-lint
|
lib/haml_lint/file_finder.rb
|
HamlLint.FileFinder.find
|
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
end
|
ruby
|
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
end
|
[
"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",
"end"
] |
Create a file finder using the specified configuration.
@param config [HamlLint::Configuration]
Return list of files to lint given the specified set of paths and glob
patterns.
@param patterns [Array<String>]
@param excluded_patterns [Array<String>]
@raise [HamlLint::Exceptions::InvalidFilePath]
@return [Array<String>] list of actual files
|
[
"Create",
"a",
"file",
"finder",
"using",
"the",
"specified",
"configuration",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L26-L34
|
11,569
|
sds/haml-lint
|
lib/haml_lint/file_finder.rb
|
HamlLint.FileFinder.extract_files_from
|
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
rescue ::Errno::ENOENT
# File didn't exist; it might be a file glob pattern
matches = ::Dir.glob(pattern)
if matches.any?
files += matches
else
# One of the paths specified does not exist; raise a more
# descriptive exception so we know which one
raise HamlLint::Exceptions::InvalidFilePath,
"File path '#{pattern}' does not exist"
end
end
end
end
files.uniq.sort.map { |file| normalize_path(file) }
end
|
ruby
|
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
rescue ::Errno::ENOENT
# File didn't exist; it might be a file glob pattern
matches = ::Dir.glob(pattern)
if matches.any?
files += matches
else
# One of the paths specified does not exist; raise a more
# descriptive exception so we know which one
raise HamlLint::Exceptions::InvalidFilePath,
"File path '#{pattern}' does not exist"
end
end
end
end
files.uniq.sort.map { |file| normalize_path(file) }
end
|
[
"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",
"rescue",
"::",
"Errno",
"::",
"ENOENT",
"# File didn't exist; it might be a file glob pattern",
"matches",
"=",
"::",
"Dir",
".",
"glob",
"(",
"pattern",
")",
"if",
"matches",
".",
"any?",
"files",
"+=",
"matches",
"else",
"# One of the paths specified does not exist; raise a more",
"# descriptive exception so we know which one",
"raise",
"HamlLint",
"::",
"Exceptions",
"::",
"InvalidFilePath",
",",
"\"File path '#{pattern}' does not exist\"",
"end",
"end",
"end",
"end",
"files",
".",
"uniq",
".",
"sort",
".",
"map",
"{",
"|",
"file",
"|",
"normalize_path",
"(",
"file",
")",
"}",
"end"
] |
Extract the list of matching files given the list of glob patterns, file
paths, and directories.
@param patterns [Array<String>]
@return [Array<String>]
|
[
"Extract",
"the",
"list",
"of",
"matching",
"files",
"given",
"the",
"list",
"of",
"glob",
"patterns",
"file",
"paths",
"and",
"directories",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L43-L70
|
11,570
|
sds/haml-lint
|
lib/haml_lint/file_finder.rb
|
HamlLint.FileFinder.haml_file?
|
def haml_file?(file)
return false unless ::FileTest.file?(file)
VALID_EXTENSIONS.include?(::File.extname(file))
end
|
ruby
|
def haml_file?(file)
return false unless ::FileTest.file?(file)
VALID_EXTENSIONS.include?(::File.extname(file))
end
|
[
"def",
"haml_file?",
"(",
"file",
")",
"return",
"false",
"unless",
"::",
"FileTest",
".",
"file?",
"(",
"file",
")",
"VALID_EXTENSIONS",
".",
"include?",
"(",
"::",
"File",
".",
"extname",
"(",
"file",
")",
")",
"end"
] |
Whether the given file should be treated as a Haml file.
@param file [String]
@return [Boolean]
|
[
"Whether",
"the",
"given",
"file",
"should",
"be",
"treated",
"as",
"a",
"Haml",
"file",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/file_finder.rb#L84-L88
|
11,571
|
sds/haml-lint
|
lib/haml_lint/linter/unnecessary_string_output.rb
|
HamlLint.Linter::UnnecessaryStringOutput.starts_with_reserved_character?
|
def starts_with_reserved_character?(stringish)
string = stringish.respond_to?(:children) ? stringish.children.first : stringish
string =~ %r{\A\s*[/#-=%~]}
end
|
ruby
|
def starts_with_reserved_character?(stringish)
string = stringish.respond_to?(:children) ? stringish.children.first : stringish
string =~ %r{\A\s*[/#-=%~]}
end
|
[
"def",
"starts_with_reserved_character?",
"(",
"stringish",
")",
"string",
"=",
"stringish",
".",
"respond_to?",
"(",
":children",
")",
"?",
"stringish",
".",
"children",
".",
"first",
":",
"stringish",
"string",
"=~",
"%r{",
"\\A",
"\\s",
"}",
"end"
] |
Returns whether a string starts with a character that would otherwise be
given special treatment, thus making enclosing it in a string necessary.
|
[
"Returns",
"whether",
"a",
"string",
"starts",
"with",
"a",
"character",
"that",
"would",
"otherwise",
"be",
"given",
"special",
"treatment",
"thus",
"making",
"enclosing",
"it",
"in",
"a",
"string",
"necessary",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/unnecessary_string_output.rb#L44-L47
|
11,572
|
sds/haml-lint
|
lib/haml_lint/linter.rb
|
HamlLint.Linter.run
|
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,
e.to_s,
:error
)
end
|
ruby
|
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,
e.to_s,
:error
)
end
|
[
"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",
",",
"e",
".",
"to_s",
",",
":error",
")",
"end"
] |
Initializes a linter with the specified configuration.
@param config [Hash] configuration for this linter
Runs the linter against the given Haml document.
@param document [HamlLint::Document]
|
[
"Initializes",
"a",
"linter",
"with",
"the",
"specified",
"configuration",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L27-L42
|
11,573
|
sds/haml-lint
|
lib/haml_lint/linter.rb
|
HamlLint.Linter.inline_content_is_string?
|
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
|
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
|
[
"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"
] |
Returns whether the inline content for a node is a string.
For example, the following node has a literal string:
%tag= "A literal #{string}"
whereas this one does not:
%tag A literal #{string}
@param node [HamlLint::Tree::Node]
@return [true,false]
|
[
"Returns",
"whether",
"the",
"inline",
"content",
"for",
"a",
"node",
"is",
"a",
"string",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L118-L125
|
11,574
|
sds/haml-lint
|
lib/haml_lint/linter.rb
|
HamlLint.Linter.inline_node_content
|
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
|
def inline_node_content(node)
inline_content = node.script
if contains_interpolation?(inline_content)
strip_surrounding_quotes(inline_content)
else
inline_content
end
end
|
[
"def",
"inline_node_content",
"(",
"node",
")",
"inline_content",
"=",
"node",
".",
"script",
"if",
"contains_interpolation?",
"(",
"inline_content",
")",
"strip_surrounding_quotes",
"(",
"inline_content",
")",
"else",
"inline_content",
"end",
"end"
] |
Get the inline content for this node.
Inline content is the content that appears inline right after the
tag/script. For example, in the code below...
%tag Some inline content
..."Some inline content" would be the inline content.
@param node [HamlLint::Tree::Node]
@return [String]
|
[
"Get",
"the",
"inline",
"content",
"for",
"this",
"node",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L138-L146
|
11,575
|
sds/haml-lint
|
lib/haml_lint/linter.rb
|
HamlLint.Linter.next_node
|
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
|
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
|
[
"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"
] |
Gets the next node following this node, ascending up the ancestor chain
recursively if this node has no siblings.
@param node [HamlLint::Tree::Node]
@return [HamlLint::Tree::Node,nil]
|
[
"Gets",
"the",
"next",
"node",
"following",
"this",
"node",
"ascending",
"up",
"the",
"ancestor",
"chain",
"recursively",
"if",
"this",
"node",
"has",
"no",
"siblings",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter.rb#L153-L161
|
11,576
|
sds/haml-lint
|
lib/haml_lint/ruby_parser.rb
|
HamlLint.RubyParser.parse
|
def parse(source)
buffer = ::Parser::Source::Buffer.new('(string)')
buffer.source = source
@parser.reset
@parser.parse(buffer)
end
|
ruby
|
def parse(source)
buffer = ::Parser::Source::Buffer.new('(string)')
buffer.source = source
@parser.reset
@parser.parse(buffer)
end
|
[
"def",
"parse",
"(",
"source",
")",
"buffer",
"=",
"::",
"Parser",
"::",
"Source",
"::",
"Buffer",
".",
"new",
"(",
"'(string)'",
")",
"buffer",
".",
"source",
"=",
"source",
"@parser",
".",
"reset",
"@parser",
".",
"parse",
"(",
"buffer",
")",
"end"
] |
Creates a reusable parser.
Parse the given Ruby source into an abstract syntax tree.
@param source [String] Ruby source code
@return [Array] syntax tree in the form returned by Parser gem
|
[
"Creates",
"a",
"reusable",
"parser",
".",
"Parse",
"the",
"given",
"Ruby",
"source",
"into",
"an",
"abstract",
"syntax",
"tree",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/ruby_parser.rb#L25-L31
|
11,577
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.act_on_options
|
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
Sysexits::EX_OK
elsif options[:show_reporters]
print_available_reporters
Sysexits::EX_OK
else
scan_for_lints(options)
end
end
|
ruby
|
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
Sysexits::EX_OK
elsif options[:show_reporters]
print_available_reporters
Sysexits::EX_OK
else
scan_for_lints(options)
end
end
|
[
"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",
"Sysexits",
"::",
"EX_OK",
"elsif",
"options",
"[",
":show_reporters",
"]",
"print_available_reporters",
"Sysexits",
"::",
"EX_OK",
"else",
"scan_for_lints",
"(",
"options",
")",
"end",
"end"
] |
Given the provided options, execute the appropriate command.
@return [Integer] exit status code
|
[
"Given",
"the",
"provided",
"options",
"execute",
"the",
"appropriate",
"command",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L37-L55
|
11,578
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.configure_logger
|
def configure_logger(options)
log.color_enabled = options.fetch(:color, log.tty?)
log.summary_enabled = options.fetch(:summary, true)
end
|
ruby
|
def configure_logger(options)
log.color_enabled = options.fetch(:color, log.tty?)
log.summary_enabled = options.fetch(:summary, true)
end
|
[
"def",
"configure_logger",
"(",
"options",
")",
"log",
".",
"color_enabled",
"=",
"options",
".",
"fetch",
"(",
":color",
",",
"log",
".",
"tty?",
")",
"log",
".",
"summary_enabled",
"=",
"options",
".",
"fetch",
"(",
":summary",
",",
"true",
")",
"end"
] |
Given the provided options, configure the logger.
@return [void]
|
[
"Given",
"the",
"provided",
"options",
"configure",
"the",
"logger",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L60-L63
|
11,579
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.handle_exception
|
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"
Sysexits::EX_USAGE
when HamlLint::Exceptions::InvalidFilePath
log.error exception.message
Sysexits::EX_NOINPUT
when HamlLint::Exceptions::NoLintersError
log.error exception.message
Sysexits::EX_NOINPUT
else
print_unexpected_exception(exception)
Sysexits::EX_SOFTWARE
end
end
|
ruby
|
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"
Sysexits::EX_USAGE
when HamlLint::Exceptions::InvalidFilePath
log.error exception.message
Sysexits::EX_NOINPUT
when HamlLint::Exceptions::NoLintersError
log.error exception.message
Sysexits::EX_NOINPUT
else
print_unexpected_exception(exception)
Sysexits::EX_SOFTWARE
end
end
|
[
"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\"",
"Sysexits",
"::",
"EX_USAGE",
"when",
"HamlLint",
"::",
"Exceptions",
"::",
"InvalidFilePath",
"log",
".",
"error",
"exception",
".",
"message",
"Sysexits",
"::",
"EX_NOINPUT",
"when",
"HamlLint",
"::",
"Exceptions",
"::",
"NoLintersError",
"log",
".",
"error",
"exception",
".",
"message",
"Sysexits",
"::",
"EX_NOINPUT",
"else",
"print_unexpected_exception",
"(",
"exception",
")",
"Sysexits",
"::",
"EX_SOFTWARE",
"end",
"end"
] |
Outputs a message and returns an appropriate error code for the specified
exception.
|
[
"Outputs",
"a",
"message",
"and",
"returns",
"an",
"appropriate",
"error",
"code",
"for",
"the",
"specified",
"exception",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L67-L86
|
11,580
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.reporter_from_options
|
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
end
|
ruby
|
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
end
|
[
"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",
"end"
] |
Instantiates a new reporter based on the options.
@param options [HamlLint::Configuration]
@option options [true, nil] :auto_gen_config whether to use the config
generating reporter
@option options [Class] :reporter the class of reporter to use
@return [HamlLint::Reporter]
|
[
"Instantiates",
"a",
"new",
"reporter",
"based",
"on",
"the",
"options",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L95-L101
|
11,581
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.scan_for_lints
|
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
|
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
|
[
"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"
] |
Scans the files specified by the given options for lints.
@return [Integer] exit status code
|
[
"Scans",
"the",
"files",
"specified",
"by",
"the",
"given",
"options",
"for",
"lints",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L106-L111
|
11,582
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.print_available_linters
|
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
|
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
|
[
"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"
] |
Outputs a list of all currently available linters.
|
[
"Outputs",
"a",
"list",
"of",
"all",
"currently",
"available",
"linters",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L114-L124
|
11,583
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.print_available_reporters
|
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
|
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
|
[
"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"
] |
Outputs a list of currently available reporters.
|
[
"Outputs",
"a",
"list",
"of",
"currently",
"available",
"reporters",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L127-L133
|
11,584
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.print_version
|
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
|
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
|
[
"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"
] |
Outputs the application name and version.
|
[
"Outputs",
"the",
"application",
"name",
"and",
"version",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L141-L149
|
11,585
|
sds/haml-lint
|
lib/haml_lint/cli.rb
|
HamlLint.CLI.print_unexpected_exception
|
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 include:'
log.log '- The above stack trace'
log.log '- Haml-Lint version: ', false
log.info HamlLint::VERSION
log.log '- Haml version: ', false
log.info Gem.loaded_specs['haml'].version
log.log '- RuboCop version: ', false
log.info Gem.loaded_specs['rubocop'].version
log.log '- Ruby version: ', false
log.info RUBY_VERSION
end
|
ruby
|
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 include:'
log.log '- The above stack trace'
log.log '- Haml-Lint version: ', false
log.info HamlLint::VERSION
log.log '- Haml version: ', false
log.info Gem.loaded_specs['haml'].version
log.log '- RuboCop version: ', false
log.info Gem.loaded_specs['rubocop'].version
log.log '- Ruby version: ', false
log.info RUBY_VERSION
end
|
[
"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 include:'",
"log",
".",
"log",
"'- The above stack trace'",
"log",
".",
"log",
"'- Haml-Lint version: '",
",",
"false",
"log",
".",
"info",
"HamlLint",
"::",
"VERSION",
"log",
".",
"log",
"'- Haml version: '",
",",
"false",
"log",
".",
"info",
"Gem",
".",
"loaded_specs",
"[",
"'haml'",
"]",
".",
"version",
"log",
".",
"log",
"'- RuboCop version: '",
",",
"false",
"log",
".",
"info",
"Gem",
".",
"loaded_specs",
"[",
"'rubocop'",
"]",
".",
"version",
"log",
".",
"log",
"'- Ruby version: '",
",",
"false",
"log",
".",
"info",
"RUBY_VERSION",
"end"
] |
Outputs the backtrace of an exception with instructions on how to report
the issue.
|
[
"Outputs",
"the",
"backtrace",
"of",
"an",
"exception",
"with",
"instructions",
"on",
"how",
"to",
"report",
"the",
"issue",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/cli.rb#L153-L169
|
11,586
|
sds/haml-lint
|
lib/haml_lint/document.rb
|
HamlLint.Document.strip_frontmatter
|
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
(---\s*\n.*?\n?)
# From the start of the line
^
# Second capture match --- or ... followed by optional whitespace
# and newline. This matches the closing --- for the frontmatter.
(---|\.\.\.)\s*$\n?/mx
if config['skip_frontmatter'] && match = source.match(frontmatter)
newlines = match[0].count("\n")
source.sub!(frontmatter, "\n" * newlines)
end
source
end
|
ruby
|
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
(---\s*\n.*?\n?)
# From the start of the line
^
# Second capture match --- or ... followed by optional whitespace
# and newline. This matches the closing --- for the frontmatter.
(---|\.\.\.)\s*$\n?/mx
if config['skip_frontmatter'] && match = source.match(frontmatter)
newlines = match[0].count("\n")
source.sub!(frontmatter, "\n" * newlines)
end
source
end
|
[
"def",
"strip_frontmatter",
"(",
"source",
")",
"frontmatter",
"=",
"/",
"\\A",
"\\s",
"\\n",
"\\n",
"\\.",
"\\.",
"\\.",
"\\s",
"\\n",
"/mx",
"if",
"config",
"[",
"'skip_frontmatter'",
"]",
"&&",
"match",
"=",
"source",
".",
"match",
"(",
"frontmatter",
")",
"newlines",
"=",
"match",
"[",
"0",
"]",
".",
"count",
"(",
"\"\\n\"",
")",
"source",
".",
"sub!",
"(",
"frontmatter",
",",
"\"\\n\"",
"*",
"newlines",
")",
"end",
"source",
"end"
] |
Removes YAML frontmatter
|
[
"Removes",
"YAML",
"frontmatter"
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/document.rb#L102-L122
|
11,587
|
sds/haml-lint
|
lib/haml_lint/tree/node.rb
|
HamlLint::Tree.Node.disabled?
|
def disabled?(visitor)
visitor.is_a?(HamlLint::Linter) &&
comment_configuration.disabled?(visitor.name)
end
|
ruby
|
def disabled?(visitor)
visitor.is_a?(HamlLint::Linter) &&
comment_configuration.disabled?(visitor.name)
end
|
[
"def",
"disabled?",
"(",
"visitor",
")",
"visitor",
".",
"is_a?",
"(",
"HamlLint",
"::",
"Linter",
")",
"&&",
"comment_configuration",
".",
"disabled?",
"(",
"visitor",
".",
"name",
")",
"end"
] |
Checks whether a visitor is disabled due to comment configuration.
@param [HamlLint::HamlVisitor]
@return [true, false]
|
[
"Checks",
"whether",
"a",
"visitor",
"is",
"disabled",
"due",
"to",
"comment",
"configuration",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/node.rb#L43-L46
|
11,588
|
sds/haml-lint
|
lib/haml_lint/tree/node.rb
|
HamlLint::Tree.Node.each
|
def each
return to_enum(__callee__) unless block_given?
node = self
loop do
yield node
break unless (node = node.next_node)
end
end
|
ruby
|
def each
return to_enum(__callee__) unless block_given?
node = self
loop do
yield node
break unless (node = node.next_node)
end
end
|
[
"def",
"each",
"return",
"to_enum",
"(",
"__callee__",
")",
"unless",
"block_given?",
"node",
"=",
"self",
"loop",
"do",
"yield",
"node",
"break",
"unless",
"(",
"node",
"=",
"node",
".",
"next_node",
")",
"end",
"end"
] |
Implements the Enumerable interface to walk through an entire tree.
@return [Enumerator, HamlLint::Tree::Node]
|
[
"Implements",
"the",
"Enumerable",
"interface",
"to",
"walk",
"through",
"an",
"entire",
"tree",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/node.rb#L51-L59
|
11,589
|
sds/haml-lint
|
lib/haml_lint/tree/node.rb
|
HamlLint::Tree.Node.line_numbers
|
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
|
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
|
[
"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"
] |
The line numbers that are contained within the node.
@api public
@return [Range]
|
[
"The",
"line",
"numbers",
"that",
"are",
"contained",
"within",
"the",
"node",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/node.rb#L104-L111
|
11,590
|
sds/haml-lint
|
lib/haml_lint/tree/node.rb
|
HamlLint::Tree.Node.nontrivial_end_line
|
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
|
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
|
[
"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"
] |
Discovers the end line of the node when there are no lines.
@return [Integer] the end line of the node
|
[
"Discovers",
"the",
"end",
"line",
"of",
"the",
"node",
"when",
"there",
"are",
"no",
"lines",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/node.rb#L163-L171
|
11,591
|
sds/haml-lint
|
lib/haml_lint/tree/root_node.rb
|
HamlLint::Tree.RootNode.node_for_line
|
def node_for_line(line)
find(-> { HamlLint::Tree::NullNode.new }) { |node| node.line_numbers.cover?(line) }
end
|
ruby
|
def node_for_line(line)
find(-> { HamlLint::Tree::NullNode.new }) { |node| node.line_numbers.cover?(line) }
end
|
[
"def",
"node_for_line",
"(",
"line",
")",
"find",
"(",
"->",
"{",
"HamlLint",
"::",
"Tree",
"::",
"NullNode",
".",
"new",
"}",
")",
"{",
"|",
"node",
"|",
"node",
".",
"line_numbers",
".",
"cover?",
"(",
"line",
")",
"}",
"end"
] |
Gets the node of the syntax tree for a given line number.
@param line [Integer] the line number of the node
@return [HamlLint::Node]
|
[
"Gets",
"the",
"node",
"of",
"the",
"syntax",
"tree",
"for",
"a",
"given",
"line",
"number",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/root_node.rb#L19-L21
|
11,592
|
sds/haml-lint
|
lib/haml_lint/linter_selector.rb
|
HamlLint.LinterSelector.extract_enabled_linters
|
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(:excluded_linters, []))
# After filtering out explicitly included/excluded linters, only include
# linters which are enabled in the configuration
linters = (included_linters - excluded_linters).map do |linter_class|
linter_config = config.for_linter(linter_class)
linter_class.new(linter_config) if linter_config['enabled']
end.compact
# Highlight condition where all linters were filtered out, as this was
# likely a mistake on the user's part
if linters.empty?
raise HamlLint::Exceptions::NoLintersError, 'No linters specified'
end
linters
end
|
ruby
|
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(:excluded_linters, []))
# After filtering out explicitly included/excluded linters, only include
# linters which are enabled in the configuration
linters = (included_linters - excluded_linters).map do |linter_class|
linter_config = config.for_linter(linter_class)
linter_class.new(linter_config) if linter_config['enabled']
end.compact
# Highlight condition where all linters were filtered out, as this was
# likely a mistake on the user's part
if linters.empty?
raise HamlLint::Exceptions::NoLintersError, 'No linters specified'
end
linters
end
|
[
"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",
"(",
":excluded_linters",
",",
"[",
"]",
")",
")",
"# After filtering out explicitly included/excluded linters, only include",
"# linters which are enabled in the configuration",
"linters",
"=",
"(",
"included_linters",
"-",
"excluded_linters",
")",
".",
"map",
"do",
"|",
"linter_class",
"|",
"linter_config",
"=",
"config",
".",
"for_linter",
"(",
"linter_class",
")",
"linter_class",
".",
"new",
"(",
"linter_config",
")",
"if",
"linter_config",
"[",
"'enabled'",
"]",
"end",
".",
"compact",
"# Highlight condition where all linters were filtered out, as this was",
"# likely a mistake on the user's part",
"if",
"linters",
".",
"empty?",
"raise",
"HamlLint",
"::",
"Exceptions",
"::",
"NoLintersError",
",",
"'No linters specified'",
"end",
"linters",
"end"
] |
Returns a list of linters that are enabled given the specified
configuration and additional options.
@param config [HamlLint::Configuration]
@param options [Hash]
@return [Array<HamlLint::Linter>]
|
[
"Returns",
"a",
"list",
"of",
"linters",
"that",
"are",
"enabled",
"given",
"the",
"specified",
"configuration",
"and",
"additional",
"options",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter_selector.rb#L33-L56
|
11,593
|
sds/haml-lint
|
lib/haml_lint/linter_selector.rb
|
HamlLint.LinterSelector.run_linter_on_file?
|
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)
return false
end
true
end
|
ruby
|
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)
return false
end
true
end
|
[
"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",
")",
"return",
"false",
"end",
"true",
"end"
] |
Whether to run the given linter against the specified file.
@param config [HamlLint::Configuration]
@param linter [HamlLint::Linter]
@param file [String]
@return [Boolean]
|
[
"Whether",
"to",
"run",
"the",
"given",
"linter",
"against",
"the",
"specified",
"file",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter_selector.rb#L64-L77
|
11,594
|
sds/haml-lint
|
lib/haml_lint/tree/tag_node.rb
|
HamlLint::Tree.TagNode.attributes_source
|
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[[ ]]],
}
attr_source = { static: static_attrs }
while rest
type, chars = attr_types[rest[0]]
break unless type # Not an attribute opening character, so we're done
# Can't define multiple of the same attribute type (e.g. two {...})
break if attr_source[type]
attr_source[type], rest = Haml::Util.balance(rest, *chars)
end
attr_source
end
end
|
ruby
|
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[[ ]]],
}
attr_source = { static: static_attrs }
while rest
type, chars = attr_types[rest[0]]
break unless type # Not an attribute opening character, so we're done
# Can't define multiple of the same attribute type (e.g. two {...})
break if attr_source[type]
attr_source[type], rest = Haml::Util.balance(rest, *chars)
end
attr_source
end
end
|
[
"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[",
"[",
"]",
"]",
"]",
",",
"}",
"attr_source",
"=",
"{",
"static",
":",
"static_attrs",
"}",
"while",
"rest",
"type",
",",
"chars",
"=",
"attr_types",
"[",
"rest",
"[",
"0",
"]",
"]",
"break",
"unless",
"type",
"# Not an attribute opening character, so we're done",
"# Can't define multiple of the same attribute type (e.g. two {...})",
"break",
"if",
"attr_source",
"[",
"type",
"]",
"attr_source",
"[",
"type",
"]",
",",
"rest",
"=",
"Haml",
"::",
"Util",
".",
"balance",
"(",
"rest",
",",
"chars",
")",
"end",
"attr_source",
"end",
"end"
] |
Returns the source code for the static and dynamic attributes
of a tag.
@example For `%tag.class{ id: 'hello' }(lang=en)`, this returns:
{ :static => '.class', :hash => " id: 'hello' ", :html => "lang=en" }
@return [Hash]
|
[
"Returns",
"the",
"source",
"code",
"for",
"the",
"static",
"and",
"dynamic",
"attributes",
"of",
"a",
"tag",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/tree/tag_node.rb#L100-L125
|
11,595
|
sds/haml-lint
|
lib/haml_lint/linter/rubocop.rb
|
HamlLint.Linter::RuboCop.find_lints
|
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
end
|
ruby
|
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
end
|
[
"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",
"end"
] |
Executes RuboCop against the given Ruby code and records the offenses as
lints.
@param ruby [String] Ruby code
@param source_map [Hash] map of Ruby code line numbers to original line
numbers in the template
|
[
"Executes",
"RuboCop",
"against",
"the",
"given",
"Ruby",
"code",
"and",
"records",
"the",
"offenses",
"as",
"lints",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/rubocop.rb#L38-L51
|
11,596
|
sds/haml-lint
|
lib/haml_lint/linter/rubocop.rb
|
HamlLint.Linter::RuboCop.with_ruby_from_stdin
|
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
|
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
|
[
"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"
] |
Overrides the global stdin to allow RuboCop to read Ruby code from it.
@param ruby [String] the Ruby code to write to the overridden stdin
@param _block [Block] the block to perform with the overridden stdin
@return [void]
|
[
"Overrides",
"the",
"global",
"stdin",
"to",
"allow",
"RuboCop",
"to",
"read",
"Ruby",
"code",
"from",
"it",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/linter/rubocop.rb#L103-L112
|
11,597
|
sds/haml-lint
|
lib/haml_lint/utils.rb
|
HamlLint.Utils.get_abs_and_rel_path
|
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
|
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
|
[
"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"
] |
Returns an array of two items, the first being the absolute path, the second
the relative path.
The relative path is relative to the current working dir. The path passed can
be either relative or absolute.
@param path [String] Path to get absolute and relative path of
@return [Array<String>] Absolute and relative path
|
[
"Returns",
"an",
"array",
"of",
"two",
"items",
"the",
"first",
"being",
"the",
"absolute",
"path",
"the",
"second",
"the",
"relative",
"path",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/utils.rb#L37-L46
|
11,598
|
sds/haml-lint
|
lib/haml_lint/utils.rb
|
HamlLint.Utils.extract_interpolated_values
|
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 } ||
newline_positions.size) + 1
escape_count = (scan[2].size - 1) / 2
break unless escape_count.even?
dumped_interpolated_str = Haml::Util.balance(scan, '{', '}', 1)[0][0...-1]
# Hacky way to turn a dumped string back into a regular string
yield [eval('"' + dumped_interpolated_str + '"'), line] # rubocop:disable Eval
end
end
|
ruby
|
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 } ||
newline_positions.size) + 1
escape_count = (scan[2].size - 1) / 2
break unless escape_count.even?
dumped_interpolated_str = Haml::Util.balance(scan, '{', '}', 1)[0][0...-1]
# Hacky way to turn a dumped string back into a regular string
yield [eval('"' + dumped_interpolated_str + '"'), line] # rubocop:disable Eval
end
end
|
[
"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",
"}",
"||",
"newline_positions",
".",
"size",
")",
"+",
"1",
"escape_count",
"=",
"(",
"scan",
"[",
"2",
"]",
".",
"size",
"-",
"1",
")",
"/",
"2",
"break",
"unless",
"escape_count",
".",
"even?",
"dumped_interpolated_str",
"=",
"Haml",
"::",
"Util",
".",
"balance",
"(",
"scan",
",",
"'{'",
",",
"'}'",
",",
"1",
")",
"[",
"0",
"]",
"[",
"0",
"...",
"-",
"1",
"]",
"# Hacky way to turn a dumped string back into a regular string",
"yield",
"[",
"eval",
"(",
"'\"'",
"+",
"dumped_interpolated_str",
"+",
"'\"'",
")",
",",
"line",
"]",
"# rubocop:disable Eval",
"end",
"end"
] |
Yields interpolated values within a block of text.
@param text [String]
@yield Passes interpolated code and line number that code appears on in
the text.
@yieldparam interpolated_code [String] code that was interpolated
@yieldparam line [Integer] line number code appears on in text
|
[
"Yields",
"interpolated",
"values",
"within",
"a",
"block",
"of",
"text",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/utils.rb#L55-L71
|
11,599
|
sds/haml-lint
|
lib/haml_lint/utils.rb
|
HamlLint.Utils.for_consecutive_items
|
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 the chunk of consecutive items
yield items[current_index...(current_index + count)]
current_index += count # Skip this patch of consecutive items to find more
end
end
|
ruby
|
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 the chunk of consecutive items
yield items[current_index...(current_index + count)]
current_index += count # Skip this patch of consecutive items to find more
end
end
|
[
"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 the chunk of consecutive items",
"yield",
"items",
"[",
"current_index",
"...",
"(",
"current_index",
"+",
"count",
")",
"]",
"current_index",
"+=",
"count",
"# Skip this patch of consecutive items to find more",
"end",
"end"
] |
Find all consecutive items satisfying the given block of a minimum size,
yielding each group of consecutive items to the provided block.
@param items [Array]
@param satisfies [Proc] function that takes an item and returns true/false
@param min_consecutive [Fixnum] minimum number of consecutive items before
yielding the group
@yield Passes list of consecutive items all matching the criteria defined
by the `satisfies` {Proc} to the provided block
@yieldparam group [Array] List of consecutive items
@yieldreturn [Boolean] block should return whether item matches criteria
for inclusion
|
[
"Find",
"all",
"consecutive",
"items",
"satisfying",
"the",
"given",
"block",
"of",
"a",
"minimum",
"size",
"yielding",
"each",
"group",
"of",
"consecutive",
"items",
"to",
"the",
"provided",
"block",
"."
] |
024c773667e54cf88db938c2b368977005d70ee8
|
https://github.com/sds/haml-lint/blob/024c773667e54cf88db938c2b368977005d70ee8/lib/haml_lint/utils.rb#L108-L122
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.