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
|
|---|---|---|---|---|---|---|---|---|---|---|---|
18,400
|
Sutto/rocket_pants
|
lib/rocket_pants/controller/error_handling.rb
|
RocketPants.ErrorHandling.render_error
|
def render_error(exception)
logger.debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger
# When a normalised class is present, make sure we
# convert it to a useable error class.
normalised_class = exception.class.ancestors.detect do |klass|
klass < StandardError and error_mapping.has_key?(klass)
end
if normalised_class
mapped = error_mapping[normalised_class]
if mapped.respond_to?(:call)
exception = mapped.call(exception)
else
exception = mapped.new exception.message
end
end
self.status = lookup_error_status(exception)
render_json({
:error => lookup_error_name(exception).to_s,
:error_description => lookup_error_message(exception)
}.merge(lookup_error_metadata(exception)))
end
|
ruby
|
def render_error(exception)
logger.debug "Exception raised: #{exception.class.name}: #{exception.message}" if logger
# When a normalised class is present, make sure we
# convert it to a useable error class.
normalised_class = exception.class.ancestors.detect do |klass|
klass < StandardError and error_mapping.has_key?(klass)
end
if normalised_class
mapped = error_mapping[normalised_class]
if mapped.respond_to?(:call)
exception = mapped.call(exception)
else
exception = mapped.new exception.message
end
end
self.status = lookup_error_status(exception)
render_json({
:error => lookup_error_name(exception).to_s,
:error_description => lookup_error_message(exception)
}.merge(lookup_error_metadata(exception)))
end
|
[
"def",
"render_error",
"(",
"exception",
")",
"logger",
".",
"debug",
"\"Exception raised: #{exception.class.name}: #{exception.message}\"",
"if",
"logger",
"# When a normalised class is present, make sure we",
"# convert it to a useable error class.",
"normalised_class",
"=",
"exception",
".",
"class",
".",
"ancestors",
".",
"detect",
"do",
"|",
"klass",
"|",
"klass",
"<",
"StandardError",
"and",
"error_mapping",
".",
"has_key?",
"(",
"klass",
")",
"end",
"if",
"normalised_class",
"mapped",
"=",
"error_mapping",
"[",
"normalised_class",
"]",
"if",
"mapped",
".",
"respond_to?",
"(",
":call",
")",
"exception",
"=",
"mapped",
".",
"call",
"(",
"exception",
")",
"else",
"exception",
"=",
"mapped",
".",
"new",
"exception",
".",
"message",
"end",
"end",
"self",
".",
"status",
"=",
"lookup_error_status",
"(",
"exception",
")",
"render_json",
"(",
"{",
":error",
"=>",
"lookup_error_name",
"(",
"exception",
")",
".",
"to_s",
",",
":error_description",
"=>",
"lookup_error_message",
"(",
"exception",
")",
"}",
".",
"merge",
"(",
"lookup_error_metadata",
"(",
"exception",
")",
")",
")",
"end"
] |
Renders an exception as JSON using a nicer version of the error name and
error message, following the typically error standard as laid out in the JSON
api design.
@param [StandardError] exception the error to render a response for.
|
[
"Renders",
"an",
"exception",
"as",
"JSON",
"using",
"a",
"nicer",
"version",
"of",
"the",
"error",
"name",
"and",
"error",
"message",
"following",
"the",
"typically",
"error",
"standard",
"as",
"laid",
"out",
"in",
"the",
"JSON",
"api",
"design",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/error_handling.rb#L111-L131
|
18,401
|
Sutto/rocket_pants
|
lib/rocket_pants/client.rb
|
RocketPants.Client.transform_response
|
def transform_response(response, options = {})
# Now unpack the response into the data types.
inner = response.delete("response")
objects = unpack inner, options
# Unpack pagination as a special case.
if response.has_key?("pagination")
paginated_response objects, response
else
objects
end
end
|
ruby
|
def transform_response(response, options = {})
# Now unpack the response into the data types.
inner = response.delete("response")
objects = unpack inner, options
# Unpack pagination as a special case.
if response.has_key?("pagination")
paginated_response objects, response
else
objects
end
end
|
[
"def",
"transform_response",
"(",
"response",
",",
"options",
"=",
"{",
"}",
")",
"# Now unpack the response into the data types.",
"inner",
"=",
"response",
".",
"delete",
"(",
"\"response\"",
")",
"objects",
"=",
"unpack",
"inner",
",",
"options",
"# Unpack pagination as a special case.",
"if",
"response",
".",
"has_key?",
"(",
"\"pagination\"",
")",
"paginated_response",
"objects",
",",
"response",
"else",
"objects",
"end",
"end"
] |
Give a response hash from the api, will transform it into
the correct data type.
@param [Hash] response the incoming response
@param [hash] options any options to pass through for transformation
@return [Object] the transformed response.
|
[
"Give",
"a",
"response",
"hash",
"from",
"the",
"api",
"will",
"transform",
"it",
"into",
"the",
"correct",
"data",
"type",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L83-L93
|
18,402
|
Sutto/rocket_pants
|
lib/rocket_pants/client.rb
|
RocketPants.Client.paginated_response
|
def paginated_response(objects, container)
pagination = container.delete("pagination")
WillPaginate::Collection.create(pagination["current"], pagination["per_page"]) do |collection|
collection.replace objects
collection.total_entries = pagination["count"]
end
end
|
ruby
|
def paginated_response(objects, container)
pagination = container.delete("pagination")
WillPaginate::Collection.create(pagination["current"], pagination["per_page"]) do |collection|
collection.replace objects
collection.total_entries = pagination["count"]
end
end
|
[
"def",
"paginated_response",
"(",
"objects",
",",
"container",
")",
"pagination",
"=",
"container",
".",
"delete",
"(",
"\"pagination\"",
")",
"WillPaginate",
"::",
"Collection",
".",
"create",
"(",
"pagination",
"[",
"\"current\"",
"]",
",",
"pagination",
"[",
"\"per_page\"",
"]",
")",
"do",
"|",
"collection",
"|",
"collection",
".",
"replace",
"objects",
"collection",
".",
"total_entries",
"=",
"pagination",
"[",
"\"count\"",
"]",
"end",
"end"
] |
Returns an API response wrapped in a will_paginate collection
using the pagination key in the response container to set up
the current number of total entries and page details.
@param [Array<Object>] objects the actual response contents
@param [Hash{String => Object}] The response container
@option container [Hash] "pagination" the pagination data to use.
|
[
"Returns",
"an",
"API",
"response",
"wrapped",
"in",
"a",
"will_paginate",
"collection",
"using",
"the",
"pagination",
"key",
"in",
"the",
"response",
"container",
"to",
"set",
"up",
"the",
"current",
"number",
"of",
"total",
"entries",
"and",
"page",
"details",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L101-L107
|
18,403
|
Sutto/rocket_pants
|
lib/rocket_pants/client.rb
|
RocketPants.Client.unpack
|
def unpack(object, options = {})
transformer = options[:transformer] || options[:as]
transformer ? transformer.call(object) : object
end
|
ruby
|
def unpack(object, options = {})
transformer = options[:transformer] || options[:as]
transformer ? transformer.call(object) : object
end
|
[
"def",
"unpack",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"transformer",
"=",
"options",
"[",
":transformer",
"]",
"||",
"options",
"[",
":as",
"]",
"transformer",
"?",
"transformer",
".",
"call",
"(",
"object",
")",
":",
"object",
"end"
] |
Finds and uses the transformer for a given incoming object to
unpack it into a useful data type.
@param [Hash, Array<Hash>] object the response object to unpack
@param [Hash] options the unpacking options
@option options [Hash] :transformer,:as the transformer to use
@return The transformed data or the data itself when no transformer is specified.
|
[
"Finds",
"and",
"uses",
"the",
"transformer",
"for",
"a",
"given",
"incoming",
"object",
"to",
"unpack",
"it",
"into",
"a",
"useful",
"data",
"type",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/client.rb#L115-L118
|
18,404
|
Sutto/rocket_pants
|
lib/rocket_pants/controller/linking.rb
|
RocketPants.Linking.links
|
def links(links = {})
links.each_pair do |rel, uri|
link rel, uri if uri
end
end
|
ruby
|
def links(links = {})
links.each_pair do |rel, uri|
link rel, uri if uri
end
end
|
[
"def",
"links",
"(",
"links",
"=",
"{",
"}",
")",
"links",
".",
"each_pair",
"do",
"|",
"rel",
",",
"uri",
"|",
"link",
"rel",
",",
"uri",
"if",
"uri",
"end",
"end"
] |
Lets you add a series of links for the current resource.
@param [Hash{Symbol => String}] links a hash of links. Those with nil as the value are skipped.
|
[
"Lets",
"you",
"add",
"a",
"series",
"of",
"links",
"for",
"the",
"current",
"resource",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/linking.rb#L18-L22
|
18,405
|
Sutto/rocket_pants
|
lib/rocket_pants/controller/respondable.rb
|
RocketPants.Respondable.render_json
|
def render_json(json, options = {})
# Setup data from options
self.status = options[:status] if options[:status]
self.content_type = options[:content_type] if options[:content_type]
options = options.slice(*RENDERING_OPTIONS)
# Don't convert raw strings to JSON.
json = encode_to_json(json) unless json.respond_to?(:to_str)
# Encode the object to json.
self.status ||= :ok
self.content_type ||= Mime::JSON
self.response_body = json
headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
end
|
ruby
|
def render_json(json, options = {})
# Setup data from options
self.status = options[:status] if options[:status]
self.content_type = options[:content_type] if options[:content_type]
options = options.slice(*RENDERING_OPTIONS)
# Don't convert raw strings to JSON.
json = encode_to_json(json) unless json.respond_to?(:to_str)
# Encode the object to json.
self.status ||= :ok
self.content_type ||= Mime::JSON
self.response_body = json
headers['Content-Length'] = Rack::Utils.bytesize(json).to_s
end
|
[
"def",
"render_json",
"(",
"json",
",",
"options",
"=",
"{",
"}",
")",
"# Setup data from options",
"self",
".",
"status",
"=",
"options",
"[",
":status",
"]",
"if",
"options",
"[",
":status",
"]",
"self",
".",
"content_type",
"=",
"options",
"[",
":content_type",
"]",
"if",
"options",
"[",
":content_type",
"]",
"options",
"=",
"options",
".",
"slice",
"(",
"RENDERING_OPTIONS",
")",
"# Don't convert raw strings to JSON.",
"json",
"=",
"encode_to_json",
"(",
"json",
")",
"unless",
"json",
".",
"respond_to?",
"(",
":to_str",
")",
"# Encode the object to json.",
"self",
".",
"status",
"||=",
":ok",
"self",
".",
"content_type",
"||=",
"Mime",
"::",
"JSON",
"self",
".",
"response_body",
"=",
"json",
"headers",
"[",
"'Content-Length'",
"]",
"=",
"Rack",
"::",
"Utils",
".",
"bytesize",
"(",
"json",
")",
".",
"to_s",
"end"
] |
Given a json object or encoded json, will encode it
and set it to be the output of the given page.
|
[
"Given",
"a",
"json",
"object",
"or",
"encoded",
"json",
"will",
"encode",
"it",
"and",
"set",
"it",
"to",
"be",
"the",
"output",
"of",
"the",
"given",
"page",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L117-L129
|
18,406
|
Sutto/rocket_pants
|
lib/rocket_pants/controller/respondable.rb
|
RocketPants.Respondable.exposes
|
def exposes(object, options = {})
if Respondable.paginated?(object)
paginated object, options
elsif Respondable.collection?(object)
collection object, options
else
if Respondable.invalid?(object)
error! :invalid_resource, object.errors
else
resource object, options
end
end
end
|
ruby
|
def exposes(object, options = {})
if Respondable.paginated?(object)
paginated object, options
elsif Respondable.collection?(object)
collection object, options
else
if Respondable.invalid?(object)
error! :invalid_resource, object.errors
else
resource object, options
end
end
end
|
[
"def",
"exposes",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"if",
"Respondable",
".",
"paginated?",
"(",
"object",
")",
"paginated",
"object",
",",
"options",
"elsif",
"Respondable",
".",
"collection?",
"(",
"object",
")",
"collection",
"object",
",",
"options",
"else",
"if",
"Respondable",
".",
"invalid?",
"(",
"object",
")",
"error!",
":invalid_resource",
",",
"object",
".",
"errors",
"else",
"resource",
"object",
",",
"options",
"end",
"end",
"end"
] |
Exposes an object to the response - Essentiall, it tells the
controller that this is what we need to render.
|
[
"Exposes",
"an",
"object",
"to",
"the",
"response",
"-",
"Essentiall",
"it",
"tells",
"the",
"controller",
"that",
"this",
"is",
"what",
"we",
"need",
"to",
"render",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L163-L175
|
18,407
|
Sutto/rocket_pants
|
lib/rocket_pants/controller/respondable.rb
|
RocketPants.Respondable.metadata_for
|
def metadata_for(object, options, type, singular)
{}.tap do |metadata|
metadata[:count] = object.length unless singular
metadata[:pagination] = Respondable.extract_pagination(object) if type == :paginated
metadata.merge! options[:metadata] if options[:metadata]
end
end
|
ruby
|
def metadata_for(object, options, type, singular)
{}.tap do |metadata|
metadata[:count] = object.length unless singular
metadata[:pagination] = Respondable.extract_pagination(object) if type == :paginated
metadata.merge! options[:metadata] if options[:metadata]
end
end
|
[
"def",
"metadata_for",
"(",
"object",
",",
"options",
",",
"type",
",",
"singular",
")",
"{",
"}",
".",
"tap",
"do",
"|",
"metadata",
"|",
"metadata",
"[",
":count",
"]",
"=",
"object",
".",
"length",
"unless",
"singular",
"metadata",
"[",
":pagination",
"]",
"=",
"Respondable",
".",
"extract_pagination",
"(",
"object",
")",
"if",
"type",
"==",
":paginated",
"metadata",
".",
"merge!",
"options",
"[",
":metadata",
"]",
"if",
"options",
"[",
":metadata",
"]",
"end",
"end"
] |
Extracts the metadata for the current response, merging in options etc.
Implements a simple hook to allow adding extra metadata to your api.
@param [Object] object the data being exposed
@param [Hash{Symbol => Object}] options expose options optionally including new metadata.
@param [Symbol] type the type of the current object
@param [true,false] singular true iff the current object is a singular resource
|
[
"Extracts",
"the",
"metadata",
"for",
"the",
"current",
"response",
"merging",
"in",
"options",
"etc",
".",
"Implements",
"a",
"simple",
"hook",
"to",
"allow",
"adding",
"extra",
"metadata",
"to",
"your",
"api",
"."
] |
bddc27ada67a11ff34fa8065fe2b1b2627bd28ff
|
https://github.com/Sutto/rocket_pants/blob/bddc27ada67a11ff34fa8065fe2b1b2627bd28ff/lib/rocket_pants/controller/respondable.rb#L221-L227
|
18,408
|
petems/tugboat
|
lib/tugboat/config.rb
|
Tugboat.Configuration.create_config_file
|
def create_config_file(access_token, ssh_key_path, ssh_user, ssh_port, region, image, size, ssh_key, private_networking, backups_enabled, ip6, timeout)
# Default SSH Key path
ssh_key_path = File.join('~', DEFAULT_SSH_KEY_PATH) if ssh_key_path.empty?
ssh_user = 'root' if ssh_user.empty?
ssh_port = DEFAULT_SSH_PORT if ssh_port.empty?
region = DEFAULT_REGION if region.empty?
image = DEFAULT_IMAGE if image.empty?
size = DEFAULT_SIZE if size.empty?
default_ssh_key = DEFAULT_SSH_KEY if ssh_key.empty?
if private_networking.empty?
private_networking = DEFAULT_PRIVATE_NETWORKING
end
backups_enabled = DEFAULT_BACKUPS_ENABLED if backups_enabled.empty?
ip6 = DEFAULT_IP6 if ip6.empty?
timeout = DEFAULT_TIMEOUT if timeout.empty?
require 'yaml'
File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o600) do |file|
data = {
'authentication' => {
'access_token' => access_token
},
'connection' => {
'timeout' => timeout
},
'ssh' => {
'ssh_user' => ssh_user,
'ssh_key_path' => ssh_key_path,
'ssh_port' => ssh_port
},
'defaults' => {
'region' => region,
'image' => image,
'size' => size,
'ssh_key' => ssh_key,
'private_networking' => private_networking,
'backups_enabled' => backups_enabled,
'ip6' => ip6
}
}
file.write data.to_yaml
end
end
|
ruby
|
def create_config_file(access_token, ssh_key_path, ssh_user, ssh_port, region, image, size, ssh_key, private_networking, backups_enabled, ip6, timeout)
# Default SSH Key path
ssh_key_path = File.join('~', DEFAULT_SSH_KEY_PATH) if ssh_key_path.empty?
ssh_user = 'root' if ssh_user.empty?
ssh_port = DEFAULT_SSH_PORT if ssh_port.empty?
region = DEFAULT_REGION if region.empty?
image = DEFAULT_IMAGE if image.empty?
size = DEFAULT_SIZE if size.empty?
default_ssh_key = DEFAULT_SSH_KEY if ssh_key.empty?
if private_networking.empty?
private_networking = DEFAULT_PRIVATE_NETWORKING
end
backups_enabled = DEFAULT_BACKUPS_ENABLED if backups_enabled.empty?
ip6 = DEFAULT_IP6 if ip6.empty?
timeout = DEFAULT_TIMEOUT if timeout.empty?
require 'yaml'
File.open(@path, File::RDWR | File::TRUNC | File::CREAT, 0o600) do |file|
data = {
'authentication' => {
'access_token' => access_token
},
'connection' => {
'timeout' => timeout
},
'ssh' => {
'ssh_user' => ssh_user,
'ssh_key_path' => ssh_key_path,
'ssh_port' => ssh_port
},
'defaults' => {
'region' => region,
'image' => image,
'size' => size,
'ssh_key' => ssh_key,
'private_networking' => private_networking,
'backups_enabled' => backups_enabled,
'ip6' => ip6
}
}
file.write data.to_yaml
end
end
|
[
"def",
"create_config_file",
"(",
"access_token",
",",
"ssh_key_path",
",",
"ssh_user",
",",
"ssh_port",
",",
"region",
",",
"image",
",",
"size",
",",
"ssh_key",
",",
"private_networking",
",",
"backups_enabled",
",",
"ip6",
",",
"timeout",
")",
"# Default SSH Key path",
"ssh_key_path",
"=",
"File",
".",
"join",
"(",
"'~'",
",",
"DEFAULT_SSH_KEY_PATH",
")",
"if",
"ssh_key_path",
".",
"empty?",
"ssh_user",
"=",
"'root'",
"if",
"ssh_user",
".",
"empty?",
"ssh_port",
"=",
"DEFAULT_SSH_PORT",
"if",
"ssh_port",
".",
"empty?",
"region",
"=",
"DEFAULT_REGION",
"if",
"region",
".",
"empty?",
"image",
"=",
"DEFAULT_IMAGE",
"if",
"image",
".",
"empty?",
"size",
"=",
"DEFAULT_SIZE",
"if",
"size",
".",
"empty?",
"default_ssh_key",
"=",
"DEFAULT_SSH_KEY",
"if",
"ssh_key",
".",
"empty?",
"if",
"private_networking",
".",
"empty?",
"private_networking",
"=",
"DEFAULT_PRIVATE_NETWORKING",
"end",
"backups_enabled",
"=",
"DEFAULT_BACKUPS_ENABLED",
"if",
"backups_enabled",
".",
"empty?",
"ip6",
"=",
"DEFAULT_IP6",
"if",
"ip6",
".",
"empty?",
"timeout",
"=",
"DEFAULT_TIMEOUT",
"if",
"timeout",
".",
"empty?",
"require",
"'yaml'",
"File",
".",
"open",
"(",
"@path",
",",
"File",
"::",
"RDWR",
"|",
"File",
"::",
"TRUNC",
"|",
"File",
"::",
"CREAT",
",",
"0o600",
")",
"do",
"|",
"file",
"|",
"data",
"=",
"{",
"'authentication'",
"=>",
"{",
"'access_token'",
"=>",
"access_token",
"}",
",",
"'connection'",
"=>",
"{",
"'timeout'",
"=>",
"timeout",
"}",
",",
"'ssh'",
"=>",
"{",
"'ssh_user'",
"=>",
"ssh_user",
",",
"'ssh_key_path'",
"=>",
"ssh_key_path",
",",
"'ssh_port'",
"=>",
"ssh_port",
"}",
",",
"'defaults'",
"=>",
"{",
"'region'",
"=>",
"region",
",",
"'image'",
"=>",
"image",
",",
"'size'",
"=>",
"size",
",",
"'ssh_key'",
"=>",
"ssh_key",
",",
"'private_networking'",
"=>",
"private_networking",
",",
"'backups_enabled'",
"=>",
"backups_enabled",
",",
"'ip6'",
"=>",
"ip6",
"}",
"}",
"file",
".",
"write",
"data",
".",
"to_yaml",
"end",
"end"
] |
Writes a config file
|
[
"Writes",
"a",
"config",
"file"
] |
db1785c75f894022eb2ca3a7381f1d19cba4612f
|
https://github.com/petems/tugboat/blob/db1785c75f894022eb2ca3a7381f1d19cba4612f/lib/tugboat/config.rb#L114-L166
|
18,409
|
gocardless/creditsafe-ruby
|
lib/creditsafe/client.rb
|
Creditsafe.Client.handle_error
|
def handle_error(error)
case error
when Savon::SOAPFault
return UnknownApiError.new(error.message)
when Savon::HTTPError
if error.to_hash[:code] == 401
return AccountError.new("Unauthorized: invalid credentials")
end
return UnknownApiError.new(error.message)
when Excon::Errors::Error
return HttpError.new("Error making HTTP request: #{error.message}")
end
error
end
|
ruby
|
def handle_error(error)
case error
when Savon::SOAPFault
return UnknownApiError.new(error.message)
when Savon::HTTPError
if error.to_hash[:code] == 401
return AccountError.new("Unauthorized: invalid credentials")
end
return UnknownApiError.new(error.message)
when Excon::Errors::Error
return HttpError.new("Error making HTTP request: #{error.message}")
end
error
end
|
[
"def",
"handle_error",
"(",
"error",
")",
"case",
"error",
"when",
"Savon",
"::",
"SOAPFault",
"return",
"UnknownApiError",
".",
"new",
"(",
"error",
".",
"message",
")",
"when",
"Savon",
"::",
"HTTPError",
"if",
"error",
".",
"to_hash",
"[",
":code",
"]",
"==",
"401",
"return",
"AccountError",
".",
"new",
"(",
"\"Unauthorized: invalid credentials\"",
")",
"end",
"return",
"UnknownApiError",
".",
"new",
"(",
"error",
".",
"message",
")",
"when",
"Excon",
"::",
"Errors",
"::",
"Error",
"return",
"HttpError",
".",
"new",
"(",
"\"Error making HTTP request: #{error.message}\"",
")",
"end",
"error",
"end"
] |
There's a potential bug in the creditsafe API where they actually return
an HTTP 401 if you're unauthorized, hence the sad special case below
rubocop:disable Metrics/MethodLength
|
[
"There",
"s",
"a",
"potential",
"bug",
"in",
"the",
"creditsafe",
"API",
"where",
"they",
"actually",
"return",
"an",
"HTTP",
"401",
"if",
"you",
"re",
"unauthorized",
"hence",
"the",
"sad",
"special",
"case",
"below"
] |
4a03027a18fddca0905f65fedae3ed6eb1bc05aa
|
https://github.com/gocardless/creditsafe-ruby/blob/4a03027a18fddca0905f65fedae3ed6eb1bc05aa/lib/creditsafe/client.rb#L116-L130
|
18,410
|
CrowdFlower/ruby-crowdflower
|
lib/crowdflower/base.rb
|
CrowdFlower.Connection.method_missing
|
def method_missing(method_id, *args)
if [:get, :post, :put, :delete].include?(method_id)
path, options = *args
options ||= {}
options[:query] = (default_params.merge(options[:query] || {}))
options[:headers] = (self.class.default_options[:headers].merge(options[:headers] || {}))
CrowdFlower.request_hook.call(method_id, path, options) do
self.class.send(method_id, url(path), options)
end
else
super
end
end
|
ruby
|
def method_missing(method_id, *args)
if [:get, :post, :put, :delete].include?(method_id)
path, options = *args
options ||= {}
options[:query] = (default_params.merge(options[:query] || {}))
options[:headers] = (self.class.default_options[:headers].merge(options[:headers] || {}))
CrowdFlower.request_hook.call(method_id, path, options) do
self.class.send(method_id, url(path), options)
end
else
super
end
end
|
[
"def",
"method_missing",
"(",
"method_id",
",",
"*",
"args",
")",
"if",
"[",
":get",
",",
":post",
",",
":put",
",",
":delete",
"]",
".",
"include?",
"(",
"method_id",
")",
"path",
",",
"options",
"=",
"args",
"options",
"||=",
"{",
"}",
"options",
"[",
":query",
"]",
"=",
"(",
"default_params",
".",
"merge",
"(",
"options",
"[",
":query",
"]",
"||",
"{",
"}",
")",
")",
"options",
"[",
":headers",
"]",
"=",
"(",
"self",
".",
"class",
".",
"default_options",
"[",
":headers",
"]",
".",
"merge",
"(",
"options",
"[",
":headers",
"]",
"||",
"{",
"}",
")",
")",
"CrowdFlower",
".",
"request_hook",
".",
"call",
"(",
"method_id",
",",
"path",
",",
"options",
")",
"do",
"self",
".",
"class",
".",
"send",
"(",
"method_id",
",",
"url",
"(",
"path",
")",
",",
"options",
")",
"end",
"else",
"super",
"end",
"end"
] |
get, post, put and delete methods
|
[
"get",
"post",
"put",
"and",
"delete",
"methods"
] |
76e56343689cc2dff575bbe885e8269cdb236db0
|
https://github.com/CrowdFlower/ruby-crowdflower/blob/76e56343689cc2dff575bbe885e8269cdb236db0/lib/crowdflower/base.rb#L67-L80
|
18,411
|
CrowdFlower/ruby-crowdflower
|
lib/crowdflower/judgment.rb
|
CrowdFlower.Judgment.all
|
def all(page = 1, limit = 100, latest = true)
opts = connection.version == 2 ? {:unseen => latest} : {:latest => latest}
connection.get(resource_uri, {:query => {:limit => limit, :page => page}.merge(opts)})
end
|
ruby
|
def all(page = 1, limit = 100, latest = true)
opts = connection.version == 2 ? {:unseen => latest} : {:latest => latest}
connection.get(resource_uri, {:query => {:limit => limit, :page => page}.merge(opts)})
end
|
[
"def",
"all",
"(",
"page",
"=",
"1",
",",
"limit",
"=",
"100",
",",
"latest",
"=",
"true",
")",
"opts",
"=",
"connection",
".",
"version",
"==",
"2",
"?",
"{",
":unseen",
"=>",
"latest",
"}",
":",
"{",
":latest",
"=>",
"latest",
"}",
"connection",
".",
"get",
"(",
"resource_uri",
",",
"{",
":query",
"=>",
"{",
":limit",
"=>",
"limit",
",",
":page",
"=>",
"page",
"}",
".",
"merge",
"(",
"opts",
")",
"}",
")",
"end"
] |
Pull every judgment
|
[
"Pull",
"every",
"judgment"
] |
76e56343689cc2dff575bbe885e8269cdb236db0
|
https://github.com/CrowdFlower/ruby-crowdflower/blob/76e56343689cc2dff575bbe885e8269cdb236db0/lib/crowdflower/judgment.rb#L16-L19
|
18,412
|
samvera/solrizer
|
lib/solrizer/field_mapper.rb
|
Solrizer.FieldMapper.solr_names_and_values
|
def solr_names_and_values(field_name, field_value, index_types)
return {} if field_value.nil?
# Determine the set of index types
index_types = Array(index_types)
index_types.uniq!
index_types.dup.each do |index_type|
if index_type.to_s =~ /^not_(.*)/
index_types.delete index_type # not_foo
index_types.delete $1.to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.kind_of? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
results[name] = value
end
end
end
results
end
|
ruby
|
def solr_names_and_values(field_name, field_value, index_types)
return {} if field_value.nil?
# Determine the set of index types
index_types = Array(index_types)
index_types.uniq!
index_types.dup.each do |index_type|
if index_type.to_s =~ /^not_(.*)/
index_types.delete index_type # not_foo
index_types.delete $1.to_sym # foo
end
end
# Map names and values
results = {}
# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.
field_value = [field_value] if field_value.kind_of? Time
index_types.each do |index_type|
Array(field_value).each do |single_value|
# Get mapping for field
descriptor = indexer(index_type)
data_type = extract_type(single_value)
name, converter = descriptor.name_and_converter(field_name, type: data_type)
next unless name
# Is there a custom converter?
# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.
value = if converter
if converter.arity == 1
converter.call(single_value)
else
converter.call(single_value, field_name)
end
elsif data_type == :boolean
single_value
else
single_value.to_s
end
# Add mapped name & value, unless it's a duplicate
if descriptor.evaluate_suffix(data_type).multivalued?
values = (results[name] ||= [])
values << value unless value.nil? || values.include?(value)
else
Solrizer.logger.warn "Setting #{name} to `#{value}', but it already had `#{results[name]}'" if results[name] && Solrizer.logger
results[name] = value
end
end
end
results
end
|
[
"def",
"solr_names_and_values",
"(",
"field_name",
",",
"field_value",
",",
"index_types",
")",
"return",
"{",
"}",
"if",
"field_value",
".",
"nil?",
"# Determine the set of index types",
"index_types",
"=",
"Array",
"(",
"index_types",
")",
"index_types",
".",
"uniq!",
"index_types",
".",
"dup",
".",
"each",
"do",
"|",
"index_type",
"|",
"if",
"index_type",
".",
"to_s",
"=~",
"/",
"/",
"index_types",
".",
"delete",
"index_type",
"# not_foo",
"index_types",
".",
"delete",
"$1",
".",
"to_sym",
"# foo",
"end",
"end",
"# Map names and values",
"results",
"=",
"{",
"}",
"# Time seems to extend enumerable, so wrap it so we don't interate over each of its elements.",
"field_value",
"=",
"[",
"field_value",
"]",
"if",
"field_value",
".",
"kind_of?",
"Time",
"index_types",
".",
"each",
"do",
"|",
"index_type",
"|",
"Array",
"(",
"field_value",
")",
".",
"each",
"do",
"|",
"single_value",
"|",
"# Get mapping for field",
"descriptor",
"=",
"indexer",
"(",
"index_type",
")",
"data_type",
"=",
"extract_type",
"(",
"single_value",
")",
"name",
",",
"converter",
"=",
"descriptor",
".",
"name_and_converter",
"(",
"field_name",
",",
"type",
":",
"data_type",
")",
"next",
"unless",
"name",
"# Is there a custom converter?",
"# TODO instead of a custom converter, look for input data type and output data type. Create a few methods that can do that cast.",
"value",
"=",
"if",
"converter",
"if",
"converter",
".",
"arity",
"==",
"1",
"converter",
".",
"call",
"(",
"single_value",
")",
"else",
"converter",
".",
"call",
"(",
"single_value",
",",
"field_name",
")",
"end",
"elsif",
"data_type",
"==",
":boolean",
"single_value",
"else",
"single_value",
".",
"to_s",
"end",
"# Add mapped name & value, unless it's a duplicate",
"if",
"descriptor",
".",
"evaluate_suffix",
"(",
"data_type",
")",
".",
"multivalued?",
"values",
"=",
"(",
"results",
"[",
"name",
"]",
"||=",
"[",
"]",
")",
"values",
"<<",
"value",
"unless",
"value",
".",
"nil?",
"||",
"values",
".",
"include?",
"(",
"value",
")",
"else",
"Solrizer",
".",
"logger",
".",
"warn",
"\"Setting #{name} to `#{value}', but it already had `#{results[name]}'\"",
"if",
"results",
"[",
"name",
"]",
"&&",
"Solrizer",
".",
"logger",
"results",
"[",
"name",
"]",
"=",
"value",
"end",
"end",
"end",
"results",
"end"
] |
Given a field name-value pair, a data type, and an array of index types, returns a hash of
mapped names and values. The values in the hash are _arrays_, and may contain multiple values.
|
[
"Given",
"a",
"field",
"name",
"-",
"value",
"pair",
"a",
"data",
"type",
"and",
"an",
"array",
"of",
"index",
"types",
"returns",
"a",
"hash",
"of",
"mapped",
"names",
"and",
"values",
".",
"The",
"values",
"in",
"the",
"hash",
"are",
"_arrays_",
"and",
"may",
"contain",
"multiple",
"values",
"."
] |
6a53933cdc977a507342bbdde68a2165e3fd1263
|
https://github.com/samvera/solrizer/blob/6a53933cdc977a507342bbdde68a2165e3fd1263/lib/solrizer/field_mapper.rb#L180-L235
|
18,413
|
anlek/mongify
|
lib/mongify/configuration.rb
|
Mongify.Configuration.mongodb_connection
|
def mongodb_connection(options={}, &block)
return @mongodb_conncetion if @mongodb_connection and !block_given?
options.stringify_keys!
options['adapter'] ||= 'mongodb'
@mongodb_connection = no_sql_connection(options, &block)
end
|
ruby
|
def mongodb_connection(options={}, &block)
return @mongodb_conncetion if @mongodb_connection and !block_given?
options.stringify_keys!
options['adapter'] ||= 'mongodb'
@mongodb_connection = no_sql_connection(options, &block)
end
|
[
"def",
"mongodb_connection",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"return",
"@mongodb_conncetion",
"if",
"@mongodb_connection",
"and",
"!",
"block_given?",
"options",
".",
"stringify_keys!",
"options",
"[",
"'adapter'",
"]",
"||=",
"'mongodb'",
"@mongodb_connection",
"=",
"no_sql_connection",
"(",
"options",
",",
"block",
")",
"end"
] |
self
Returns a no_sql_connection which is bound to a mongodb adapter
or builds a new no_sql_connection if block is given
|
[
"self",
"Returns",
"a",
"no_sql_connection",
"which",
"is",
"bound",
"to",
"a",
"mongodb",
"adapter",
"or",
"builds",
"a",
"new",
"no_sql_connection",
"if",
"block",
"is",
"given"
] |
6c592e864bac04338fdc3d89b3413351d87505c2
|
https://github.com/anlek/mongify/blob/6c592e864bac04338fdc3d89b3413351d87505c2/lib/mongify/configuration.rb#L22-L27
|
18,414
|
anlek/mongify
|
lib/mongify/progressbar.rb
|
Mongify.ProgressBar.show
|
def show
return unless @out
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
}
line = sprintf(@format, *arguments)
width = get_width
if line.length == width - 1
@out.print(line + eol)
@out.flush
elsif line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
if @terminal_width == 0 then @out.print(line + eol) else show end
else # line.length < width - 1
@terminal_width += width - line.length + 1
show
end
@previous_time = Time.now
end
|
ruby
|
def show
return unless @out
arguments = @format_arguments.map {|method|
method = sprintf("fmt_%s", method)
send(method)
}
line = sprintf(@format, *arguments)
width = get_width
if line.length == width - 1
@out.print(line + eol)
@out.flush
elsif line.length >= width
@terminal_width = [@terminal_width - (line.length - width + 1), 0].max
if @terminal_width == 0 then @out.print(line + eol) else show end
else # line.length < width - 1
@terminal_width += width - line.length + 1
show
end
@previous_time = Time.now
end
|
[
"def",
"show",
"return",
"unless",
"@out",
"arguments",
"=",
"@format_arguments",
".",
"map",
"{",
"|",
"method",
"|",
"method",
"=",
"sprintf",
"(",
"\"fmt_%s\"",
",",
"method",
")",
"send",
"(",
"method",
")",
"}",
"line",
"=",
"sprintf",
"(",
"@format",
",",
"arguments",
")",
"width",
"=",
"get_width",
"if",
"line",
".",
"length",
"==",
"width",
"-",
"1",
"@out",
".",
"print",
"(",
"line",
"+",
"eol",
")",
"@out",
".",
"flush",
"elsif",
"line",
".",
"length",
">=",
"width",
"@terminal_width",
"=",
"[",
"@terminal_width",
"-",
"(",
"line",
".",
"length",
"-",
"width",
"+",
"1",
")",
",",
"0",
"]",
".",
"max",
"if",
"@terminal_width",
"==",
"0",
"then",
"@out",
".",
"print",
"(",
"line",
"+",
"eol",
")",
"else",
"show",
"end",
"else",
"# line.length < width - 1",
"@terminal_width",
"+=",
"width",
"-",
"line",
".",
"length",
"+",
"1",
"show",
"end",
"@previous_time",
"=",
"Time",
".",
"now",
"end"
] |
Draws the bar
|
[
"Draws",
"the",
"bar"
] |
6c592e864bac04338fdc3d89b3413351d87505c2
|
https://github.com/anlek/mongify/blob/6c592e864bac04338fdc3d89b3413351d87505c2/lib/mongify/progressbar.rb#L158-L178
|
18,415
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.call
|
def call(env)
return render(500) do |xml|
xml.h2("#{@key} env is not initialized")
end unless env[@key]
request = ::Rack::Request.new(env)
if action = dispatch_action(request)
send(action, request)
else
@app.call(env)
end
end
|
ruby
|
def call(env)
return render(500) do |xml|
xml.h2("#{@key} env is not initialized")
end unless env[@key]
request = ::Rack::Request.new(env)
if action = dispatch_action(request)
send(action, request)
else
@app.call(env)
end
end
|
[
"def",
"call",
"(",
"env",
")",
"return",
"render",
"(",
"500",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"(",
"\"#{@key} env is not initialized\"",
")",
"end",
"unless",
"env",
"[",
"@key",
"]",
"request",
"=",
"::",
"Rack",
"::",
"Request",
".",
"new",
"(",
"env",
")",
"if",
"action",
"=",
"dispatch_action",
"(",
"request",
")",
"send",
"(",
"action",
",",
"request",
")",
"else",
"@app",
".",
"call",
"(",
"env",
")",
"end",
"end"
] |
Initialize RackSessionAccess middleware
@param app a rack application
@param options
Options:
* :key - rack session key
|
[
"Initialize",
"RackSessionAccess",
"middleware"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L23-L35
|
18,416
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.show
|
def show(request)
# force load session because it can be lazy loaded
request.env[@key].delete(:rack_session_access_force_load_session)
# session hash object
session_hash = request.env[@key].to_hash
case File.extname(request.path)
when ".raw"
render do |xml|
xml.h2 "Raw rack session data"
xml.pre RackSessionAccess.encode(session_hash)
end
else
render do |xml|
xml.h2 "Rack session data"
xml.ul do |ul|
session_hash.each do |k,v|
ul.li("#{k.inspect} : #{v.inspect}")
end
end
xml.p do |p|
p.a("Edit", :href => action_path(:edit))
end
end
end
end
|
ruby
|
def show(request)
# force load session because it can be lazy loaded
request.env[@key].delete(:rack_session_access_force_load_session)
# session hash object
session_hash = request.env[@key].to_hash
case File.extname(request.path)
when ".raw"
render do |xml|
xml.h2 "Raw rack session data"
xml.pre RackSessionAccess.encode(session_hash)
end
else
render do |xml|
xml.h2 "Rack session data"
xml.ul do |ul|
session_hash.each do |k,v|
ul.li("#{k.inspect} : #{v.inspect}")
end
end
xml.p do |p|
p.a("Edit", :href => action_path(:edit))
end
end
end
end
|
[
"def",
"show",
"(",
"request",
")",
"# force load session because it can be lazy loaded",
"request",
".",
"env",
"[",
"@key",
"]",
".",
"delete",
"(",
":rack_session_access_force_load_session",
")",
"# session hash object",
"session_hash",
"=",
"request",
".",
"env",
"[",
"@key",
"]",
".",
"to_hash",
"case",
"File",
".",
"extname",
"(",
"request",
".",
"path",
")",
"when",
"\".raw\"",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Raw rack session data\"",
"xml",
".",
"pre",
"RackSessionAccess",
".",
"encode",
"(",
"session_hash",
")",
"end",
"else",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Rack session data\"",
"xml",
".",
"ul",
"do",
"|",
"ul",
"|",
"session_hash",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"ul",
".",
"li",
"(",
"\"#{k.inspect} : #{v.inspect}\"",
")",
"end",
"end",
"xml",
".",
"p",
"do",
"|",
"p",
"|",
"p",
".",
"a",
"(",
"\"Edit\"",
",",
":href",
"=>",
"action_path",
"(",
":edit",
")",
")",
"end",
"end",
"end",
"end"
] |
List session data
|
[
"List",
"session",
"data"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L40-L66
|
18,417
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.edit
|
def edit(request)
render do |xml|
xml.h2 "Update rack session"
xml.p "Put marshalized and encoded with base64 ruby hash into the form"
xml.form({
:action => action_path(:update),
:method => 'post',
:enctype => 'application/x-www-form-urlencoded'
}) do |form|
form.input(:type => 'hidden', :name =>'_method', :value => 'put')
form.textarea(:cols => 40, :rows => 10, :name => 'data') {}
form.p do |p|
p.input(:type => 'submit', :value => "Update")
end
end
end
end
|
ruby
|
def edit(request)
render do |xml|
xml.h2 "Update rack session"
xml.p "Put marshalized and encoded with base64 ruby hash into the form"
xml.form({
:action => action_path(:update),
:method => 'post',
:enctype => 'application/x-www-form-urlencoded'
}) do |form|
form.input(:type => 'hidden', :name =>'_method', :value => 'put')
form.textarea(:cols => 40, :rows => 10, :name => 'data') {}
form.p do |p|
p.input(:type => 'submit', :value => "Update")
end
end
end
end
|
[
"def",
"edit",
"(",
"request",
")",
"render",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"\"Update rack session\"",
"xml",
".",
"p",
"\"Put marshalized and encoded with base64 ruby hash into the form\"",
"xml",
".",
"form",
"(",
"{",
":action",
"=>",
"action_path",
"(",
":update",
")",
",",
":method",
"=>",
"'post'",
",",
":enctype",
"=>",
"'application/x-www-form-urlencoded'",
"}",
")",
"do",
"|",
"form",
"|",
"form",
".",
"input",
"(",
":type",
"=>",
"'hidden'",
",",
":name",
"=>",
"'_method'",
",",
":value",
"=>",
"'put'",
")",
"form",
".",
"textarea",
"(",
":cols",
"=>",
"40",
",",
":rows",
"=>",
"10",
",",
":name",
"=>",
"'data'",
")",
"{",
"}",
"form",
".",
"p",
"do",
"|",
"p",
"|",
"p",
".",
"input",
"(",
":type",
"=>",
"'submit'",
",",
":value",
"=>",
"\"Update\"",
")",
"end",
"end",
"end",
"end"
] |
Render form for submit new session data
|
[
"Render",
"form",
"for",
"submit",
"new",
"session",
"data"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L69-L85
|
18,418
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.update
|
def update(request)
begin
data = request.params['data']
hash = RackSessionAccess.decode(data)
hash.each { |k, v| request.env[@key][k] = v }
rescue => e
return render(400) do |xml|
xml.h2("Bad data #{data.inspect}: #{e.message} ")
end
end
redirect_to action_path(:show)
end
|
ruby
|
def update(request)
begin
data = request.params['data']
hash = RackSessionAccess.decode(data)
hash.each { |k, v| request.env[@key][k] = v }
rescue => e
return render(400) do |xml|
xml.h2("Bad data #{data.inspect}: #{e.message} ")
end
end
redirect_to action_path(:show)
end
|
[
"def",
"update",
"(",
"request",
")",
"begin",
"data",
"=",
"request",
".",
"params",
"[",
"'data'",
"]",
"hash",
"=",
"RackSessionAccess",
".",
"decode",
"(",
"data",
")",
"hash",
".",
"each",
"{",
"|",
"k",
",",
"v",
"|",
"request",
".",
"env",
"[",
"@key",
"]",
"[",
"k",
"]",
"=",
"v",
"}",
"rescue",
"=>",
"e",
"return",
"render",
"(",
"400",
")",
"do",
"|",
"xml",
"|",
"xml",
".",
"h2",
"(",
"\"Bad data #{data.inspect}: #{e.message} \"",
")",
"end",
"end",
"redirect_to",
"action_path",
"(",
":show",
")",
"end"
] |
Update session data
|
[
"Update",
"session",
"data"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L88-L100
|
18,419
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.dispatch_action
|
def dispatch_action(request)
method = request_method(request)
path = request.path.sub(/\.\w+$/, '')
route = @routing.detect { |r| r[0] == method && r[1] == path }
route[2] if route
end
|
ruby
|
def dispatch_action(request)
method = request_method(request)
path = request.path.sub(/\.\w+$/, '')
route = @routing.detect { |r| r[0] == method && r[1] == path }
route[2] if route
end
|
[
"def",
"dispatch_action",
"(",
"request",
")",
"method",
"=",
"request_method",
"(",
"request",
")",
"path",
"=",
"request",
".",
"path",
".",
"sub",
"(",
"/",
"\\.",
"\\w",
"/",
",",
"''",
")",
"route",
"=",
"@routing",
".",
"detect",
"{",
"|",
"r",
"|",
"r",
"[",
"0",
"]",
"==",
"method",
"&&",
"r",
"[",
"1",
"]",
"==",
"path",
"}",
"route",
"[",
"2",
"]",
"if",
"route",
"end"
] |
Dispatch action from request
|
[
"Dispatch",
"action",
"from",
"request"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L105-L110
|
18,420
|
railsware/rack_session_access
|
lib/rack_session_access/middleware.rb
|
RackSessionAccess.Middleware.request_method
|
def request_method(request)
return request.request_method if request.request_method != 'POST'
return request.params['_method'].upcase if request.params['_method']
request.request_method
end
|
ruby
|
def request_method(request)
return request.request_method if request.request_method != 'POST'
return request.params['_method'].upcase if request.params['_method']
request.request_method
end
|
[
"def",
"request_method",
"(",
"request",
")",
"return",
"request",
".",
"request_method",
"if",
"request",
".",
"request_method",
"!=",
"'POST'",
"return",
"request",
".",
"params",
"[",
"'_method'",
"]",
".",
"upcase",
"if",
"request",
".",
"params",
"[",
"'_method'",
"]",
"request",
".",
"request_method",
"end"
] |
Return HTTP method, detect emulated method with _method param
|
[
"Return",
"HTTP",
"method",
"detect",
"emulated",
"method",
"with",
"_method",
"param"
] |
aa462368296f4ba9ced66360eb1de39acd3610c9
|
https://github.com/railsware/rack_session_access/blob/aa462368296f4ba9ced66360eb1de39acd3610c9/lib/rack_session_access/middleware.rb#L113-L117
|
18,421
|
bdmac/strong_password
|
lib/strong_password/qwerty_adjuster.rb
|
StrongPassword.QwertyAdjuster.adjusted_entropy
|
def adjusted_entropy(entropy_threshhold: 0)
revpassword = base_password.reverse
min_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min
QWERTY_STRINGS.each do |qwertystr|
qpassword = mask_qwerty_strings(base_password, qwertystr)
qrevpassword = mask_qwerty_strings(revpassword, qwertystr)
if qpassword != base_password
numbits = EntropyCalculator.calculate(qpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
if qrevpassword != revpassword
numbits = EntropyCalculator.calculate(qrevpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
end
min_entropy
end
|
ruby
|
def adjusted_entropy(entropy_threshhold: 0)
revpassword = base_password.reverse
min_entropy = [EntropyCalculator.calculate(base_password), EntropyCalculator.calculate(revpassword)].min
QWERTY_STRINGS.each do |qwertystr|
qpassword = mask_qwerty_strings(base_password, qwertystr)
qrevpassword = mask_qwerty_strings(revpassword, qwertystr)
if qpassword != base_password
numbits = EntropyCalculator.calculate(qpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
if qrevpassword != revpassword
numbits = EntropyCalculator.calculate(qrevpassword)
min_entropy = [min_entropy, numbits].min
return min_entropy if min_entropy < entropy_threshhold
end
end
min_entropy
end
|
[
"def",
"adjusted_entropy",
"(",
"entropy_threshhold",
":",
"0",
")",
"revpassword",
"=",
"base_password",
".",
"reverse",
"min_entropy",
"=",
"[",
"EntropyCalculator",
".",
"calculate",
"(",
"base_password",
")",
",",
"EntropyCalculator",
".",
"calculate",
"(",
"revpassword",
")",
"]",
".",
"min",
"QWERTY_STRINGS",
".",
"each",
"do",
"|",
"qwertystr",
"|",
"qpassword",
"=",
"mask_qwerty_strings",
"(",
"base_password",
",",
"qwertystr",
")",
"qrevpassword",
"=",
"mask_qwerty_strings",
"(",
"revpassword",
",",
"qwertystr",
")",
"if",
"qpassword",
"!=",
"base_password",
"numbits",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"qpassword",
")",
"min_entropy",
"=",
"[",
"min_entropy",
",",
"numbits",
"]",
".",
"min",
"return",
"min_entropy",
"if",
"min_entropy",
"<",
"entropy_threshhold",
"end",
"if",
"qrevpassword",
"!=",
"revpassword",
"numbits",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"qrevpassword",
")",
"min_entropy",
"=",
"[",
"min_entropy",
",",
"numbits",
"]",
".",
"min",
"return",
"min_entropy",
"if",
"min_entropy",
"<",
"entropy_threshhold",
"end",
"end",
"min_entropy",
"end"
] |
Returns the minimum entropy for the password's qwerty locality
adjustments. If a threshhold is specified we will bail
early to avoid unnecessary processing.
|
[
"Returns",
"the",
"minimum",
"entropy",
"for",
"the",
"password",
"s",
"qwerty",
"locality",
"adjustments",
".",
"If",
"a",
"threshhold",
"is",
"specified",
"we",
"will",
"bail",
"early",
"to",
"avoid",
"unnecessary",
"processing",
"."
] |
b7f87281c7e2755a2df63bce5a8336755b3954e2
|
https://github.com/bdmac/strong_password/blob/b7f87281c7e2755a2df63bce5a8336755b3954e2/lib/strong_password/qwerty_adjuster.rb#L37-L55
|
18,422
|
bdmac/strong_password
|
lib/strong_password/dictionary_adjuster.rb
|
StrongPassword.DictionaryAdjuster.adjusted_entropy
|
def adjusted_entropy(min_word_length: 4, extra_dictionary_words: [], entropy_threshhold: -1)
dictionary_words = Regexp.union( ( extra_dictionary_words + COMMON_PASSWORDS ).compact.reject{ |i| i.length < min_word_length } )
min_entropy = EntropyCalculator.calculate(base_password)
# Process the passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end
|
ruby
|
def adjusted_entropy(min_word_length: 4, extra_dictionary_words: [], entropy_threshhold: -1)
dictionary_words = Regexp.union( ( extra_dictionary_words + COMMON_PASSWORDS ).compact.reject{ |i| i.length < min_word_length } )
min_entropy = EntropyCalculator.calculate(base_password)
# Process the passwords, while looking for possible matching words in the dictionary.
PasswordVariants.all_variants(base_password).inject( min_entropy ) do |min_entropy, variant|
[ min_entropy, EntropyCalculator.calculate( variant.sub( dictionary_words, '*' ) ) ].min
end
end
|
[
"def",
"adjusted_entropy",
"(",
"min_word_length",
":",
"4",
",",
"extra_dictionary_words",
":",
"[",
"]",
",",
"entropy_threshhold",
":",
"-",
"1",
")",
"dictionary_words",
"=",
"Regexp",
".",
"union",
"(",
"(",
"extra_dictionary_words",
"+",
"COMMON_PASSWORDS",
")",
".",
"compact",
".",
"reject",
"{",
"|",
"i",
"|",
"i",
".",
"length",
"<",
"min_word_length",
"}",
")",
"min_entropy",
"=",
"EntropyCalculator",
".",
"calculate",
"(",
"base_password",
")",
"# Process the passwords, while looking for possible matching words in the dictionary.",
"PasswordVariants",
".",
"all_variants",
"(",
"base_password",
")",
".",
"inject",
"(",
"min_entropy",
")",
"do",
"|",
"min_entropy",
",",
"variant",
"|",
"[",
"min_entropy",
",",
"EntropyCalculator",
".",
"calculate",
"(",
"variant",
".",
"sub",
"(",
"dictionary_words",
",",
"'*'",
")",
")",
"]",
".",
"min",
"end",
"end"
] |
Returns the minimum entropy for the passwords dictionary adjustments.
If a threshhold is specified we will bail early to avoid unnecessary
processing.
Note that we only check for the first matching word up to the threshhold if set.
Subsequent matching words are not deductd.
|
[
"Returns",
"the",
"minimum",
"entropy",
"for",
"the",
"passwords",
"dictionary",
"adjustments",
".",
"If",
"a",
"threshhold",
"is",
"specified",
"we",
"will",
"bail",
"early",
"to",
"avoid",
"unnecessary",
"processing",
".",
"Note",
"that",
"we",
"only",
"check",
"for",
"the",
"first",
"matching",
"word",
"up",
"to",
"the",
"threshhold",
"if",
"set",
".",
"Subsequent",
"matching",
"words",
"are",
"not",
"deductd",
"."
] |
b7f87281c7e2755a2df63bce5a8336755b3954e2
|
https://github.com/bdmac/strong_password/blob/b7f87281c7e2755a2df63bce5a8336755b3954e2/lib/strong_password/dictionary_adjuster.rb#L991-L998
|
18,423
|
dkubb/adamantium
|
lib/adamantium/module_methods.rb
|
Adamantium.ModuleMethods.memoize
|
def memoize(*methods)
options = methods.last.kind_of?(Hash) ? methods.pop : {}
method_freezer = Freezer.parse(options) || freezer
methods.each { |method| memoize_method(method, method_freezer) }
self
end
|
ruby
|
def memoize(*methods)
options = methods.last.kind_of?(Hash) ? methods.pop : {}
method_freezer = Freezer.parse(options) || freezer
methods.each { |method| memoize_method(method, method_freezer) }
self
end
|
[
"def",
"memoize",
"(",
"*",
"methods",
")",
"options",
"=",
"methods",
".",
"last",
".",
"kind_of?",
"(",
"Hash",
")",
"?",
"methods",
".",
"pop",
":",
"{",
"}",
"method_freezer",
"=",
"Freezer",
".",
"parse",
"(",
"options",
")",
"||",
"freezer",
"methods",
".",
"each",
"{",
"|",
"method",
"|",
"memoize_method",
"(",
"method",
",",
"method_freezer",
")",
"}",
"self",
"end"
] |
Memoize a list of methods
@example
memoize :hash
@param [Array<#to_s>] methods
a list of methods to memoize
@return [self]
@api public
|
[
"Memoize",
"a",
"list",
"of",
"methods"
] |
bf38d4ad8a4307ab7f0593758b87f62b91e1df69
|
https://github.com/dkubb/adamantium/blob/bf38d4ad8a4307ab7f0593758b87f62b91e1df69/lib/adamantium/module_methods.rb#L28-L33
|
18,424
|
dkubb/adamantium
|
lib/adamantium/module_methods.rb
|
Adamantium.ModuleMethods.memoize_method
|
def memoize_method(method_name, freezer)
memoized_methods[method_name] = Memoizable::MethodBuilder
.new(self, method_name, freezer).call
end
|
ruby
|
def memoize_method(method_name, freezer)
memoized_methods[method_name] = Memoizable::MethodBuilder
.new(self, method_name, freezer).call
end
|
[
"def",
"memoize_method",
"(",
"method_name",
",",
"freezer",
")",
"memoized_methods",
"[",
"method_name",
"]",
"=",
"Memoizable",
"::",
"MethodBuilder",
".",
"new",
"(",
"self",
",",
"method_name",
",",
"freezer",
")",
".",
"call",
"end"
] |
Memoize the named method
@param [Symbol] method_name
a method name to memoize
@param [#call] freezer
a callable object to freeze the value
@return [undefined]
@api private
|
[
"Memoize",
"the",
"named",
"method"
] |
bf38d4ad8a4307ab7f0593758b87f62b91e1df69
|
https://github.com/dkubb/adamantium/blob/bf38d4ad8a4307ab7f0593758b87f62b91e1df69/lib/adamantium/module_methods.rb#L60-L63
|
18,425
|
propublica/timeline-setter
|
lib/timeline_setter/timeline.rb
|
TimelineSetter.Timeline.timeline_min
|
def timeline_min
@js = ""
@css = Kompress::CSS.new(File.open("#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css").read).css
libs = Dir.glob("#{TimelineSetter::ROOT}/public/javascripts/vendor/**").select {|q| q =~ /min/ }
libs.each { |lib| @js << File.open(lib,'r').read }
@min_html = Kompress::HTML.new(timeline_markup).html
@js << File.open("#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js", 'r').read
@timeline = tmpl("timeline-min.erb")
end
|
ruby
|
def timeline_min
@js = ""
@css = Kompress::CSS.new(File.open("#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css").read).css
libs = Dir.glob("#{TimelineSetter::ROOT}/public/javascripts/vendor/**").select {|q| q =~ /min/ }
libs.each { |lib| @js << File.open(lib,'r').read }
@min_html = Kompress::HTML.new(timeline_markup).html
@js << File.open("#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js", 'r').read
@timeline = tmpl("timeline-min.erb")
end
|
[
"def",
"timeline_min",
"@js",
"=",
"\"\"",
"@css",
"=",
"Kompress",
"::",
"CSS",
".",
"new",
"(",
"File",
".",
"open",
"(",
"\"#{TimelineSetter::ROOT}/public/stylesheets/timeline-setter.css\"",
")",
".",
"read",
")",
".",
"css",
"libs",
"=",
"Dir",
".",
"glob",
"(",
"\"#{TimelineSetter::ROOT}/public/javascripts/vendor/**\"",
")",
".",
"select",
"{",
"|",
"q",
"|",
"q",
"=~",
"/",
"/",
"}",
"libs",
".",
"each",
"{",
"|",
"lib",
"|",
"@js",
"<<",
"File",
".",
"open",
"(",
"lib",
",",
"'r'",
")",
".",
"read",
"}",
"@min_html",
"=",
"Kompress",
"::",
"HTML",
".",
"new",
"(",
"timeline_markup",
")",
".",
"html",
"@js",
"<<",
"File",
".",
"open",
"(",
"\"#{TimelineSetter::ROOT}/public/javascripts/timeline-setter.min.js\"",
",",
"'r'",
")",
".",
"read",
"@timeline",
"=",
"tmpl",
"(",
"\"timeline-min.erb\"",
")",
"end"
] |
Create a minified one-page version of a timeline by minifying CSS and JS and embedding all assets
into our ERB template.
|
[
"Create",
"a",
"minified",
"one",
"-",
"page",
"version",
"of",
"a",
"timeline",
"by",
"minifying",
"CSS",
"and",
"JS",
"and",
"embedding",
"all",
"assets",
"into",
"our",
"ERB",
"template",
"."
] |
a6229c8942a2eddfab9b957cee02f33176f00ab9
|
https://github.com/propublica/timeline-setter/blob/a6229c8942a2eddfab9b957cee02f33176f00ab9/lib/timeline_setter/timeline.rb#L38-L46
|
18,426
|
eapache/starscope
|
lib/starscope/db.rb
|
Starscope.DB.parse_db
|
def parse_db(stream)
case stream.gets.to_i
when DB_FORMAT
@meta = Oj.load(stream.gets)
@tables = Oj.load(stream.gets)
return true
when 3..4
# Old format, so read the directories segment then rebuild
add_paths(Oj.load(stream.gets))
return false
when 0..2
# Old format (pre-json), so read the directories segment then rebuild
len = stream.gets.to_i
add_paths(Marshal.load(stream.read(len)))
return false
else
raise UnknownDBFormatError
end
rescue Oj::ParseError
stream.rewind
raise unless stream.gets.to_i == DB_FORMAT
# try reading as formated json, which is much slower, but it is sometimes
# useful to be able to directly read your db
objects = []
Oj.load(stream) { |obj| objects << obj }
@meta, @tables = objects
return true
end
|
ruby
|
def parse_db(stream)
case stream.gets.to_i
when DB_FORMAT
@meta = Oj.load(stream.gets)
@tables = Oj.load(stream.gets)
return true
when 3..4
# Old format, so read the directories segment then rebuild
add_paths(Oj.load(stream.gets))
return false
when 0..2
# Old format (pre-json), so read the directories segment then rebuild
len = stream.gets.to_i
add_paths(Marshal.load(stream.read(len)))
return false
else
raise UnknownDBFormatError
end
rescue Oj::ParseError
stream.rewind
raise unless stream.gets.to_i == DB_FORMAT
# try reading as formated json, which is much slower, but it is sometimes
# useful to be able to directly read your db
objects = []
Oj.load(stream) { |obj| objects << obj }
@meta, @tables = objects
return true
end
|
[
"def",
"parse_db",
"(",
"stream",
")",
"case",
"stream",
".",
"gets",
".",
"to_i",
"when",
"DB_FORMAT",
"@meta",
"=",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
"@tables",
"=",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
"return",
"true",
"when",
"3",
"..",
"4",
"# Old format, so read the directories segment then rebuild",
"add_paths",
"(",
"Oj",
".",
"load",
"(",
"stream",
".",
"gets",
")",
")",
"return",
"false",
"when",
"0",
"..",
"2",
"# Old format (pre-json), so read the directories segment then rebuild",
"len",
"=",
"stream",
".",
"gets",
".",
"to_i",
"add_paths",
"(",
"Marshal",
".",
"load",
"(",
"stream",
".",
"read",
"(",
"len",
")",
")",
")",
"return",
"false",
"else",
"raise",
"UnknownDBFormatError",
"end",
"rescue",
"Oj",
"::",
"ParseError",
"stream",
".",
"rewind",
"raise",
"unless",
"stream",
".",
"gets",
".",
"to_i",
"==",
"DB_FORMAT",
"# try reading as formated json, which is much slower, but it is sometimes",
"# useful to be able to directly read your db",
"objects",
"=",
"[",
"]",
"Oj",
".",
"load",
"(",
"stream",
")",
"{",
"|",
"obj",
"|",
"objects",
"<<",
"obj",
"}",
"@meta",
",",
"@tables",
"=",
"objects",
"return",
"true",
"end"
] |
returns true iff the database is in the most recent format
|
[
"returns",
"true",
"iff",
"the",
"database",
"is",
"in",
"the",
"most",
"recent",
"format"
] |
8637f52bca46a5d5843789b7effd142a4586185f
|
https://github.com/eapache/starscope/blob/8637f52bca46a5d5843789b7effd142a4586185f/lib/starscope/db.rb#L164-L191
|
18,427
|
jellymann/mittsu
|
lib/mittsu/extras/geometries/polyhedron_geometry.rb
|
Mittsu.PolyhedronGeometry.prepare
|
def prepare(vector)
vertex = vector.normalize.clone
vertex.index = @vertices.push(vertex).length - 1
# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
u = azimuth(vector) / 2.0 / Math::PI + 0.5
v = inclination(vector) / Math::PI + 0.5
vertex.uv = Vector2.new(u, 1.0 - v)
vertex
end
|
ruby
|
def prepare(vector)
vertex = vector.normalize.clone
vertex.index = @vertices.push(vertex).length - 1
# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
u = azimuth(vector) / 2.0 / Math::PI + 0.5
v = inclination(vector) / Math::PI + 0.5
vertex.uv = Vector2.new(u, 1.0 - v)
vertex
end
|
[
"def",
"prepare",
"(",
"vector",
")",
"vertex",
"=",
"vector",
".",
"normalize",
".",
"clone",
"vertex",
".",
"index",
"=",
"@vertices",
".",
"push",
"(",
"vertex",
")",
".",
"length",
"-",
"1",
"# Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.",
"u",
"=",
"azimuth",
"(",
"vector",
")",
"/",
"2.0",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
"v",
"=",
"inclination",
"(",
"vector",
")",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
"vertex",
".",
"uv",
"=",
"Vector2",
".",
"new",
"(",
"u",
",",
"1.0",
"-",
"v",
")",
"vertex",
"end"
] |
Project vector onto sphere's surface
|
[
"Project",
"vector",
"onto",
"sphere",
"s",
"surface"
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L76-L86
|
18,428
|
jellymann/mittsu
|
lib/mittsu/extras/geometries/polyhedron_geometry.rb
|
Mittsu.PolyhedronGeometry.make
|
def make(v1, v2, v3)
face = Face3.new(v1.index, v2.index, v3.index, [v1.clone, v2.clone, v3.clone])
@faces << face
@centroid.copy(v1).add(v2).add(v3).divide_scalar(3)
azi = azimuth(@centroid)
@face_vertex_uvs[0] << [
correct_uv(v1.uv, v1, azi),
correct_uv(v2.uv, v2, azi),
correct_uv(v3.uv, v3, azi)
]
end
|
ruby
|
def make(v1, v2, v3)
face = Face3.new(v1.index, v2.index, v3.index, [v1.clone, v2.clone, v3.clone])
@faces << face
@centroid.copy(v1).add(v2).add(v3).divide_scalar(3)
azi = azimuth(@centroid)
@face_vertex_uvs[0] << [
correct_uv(v1.uv, v1, azi),
correct_uv(v2.uv, v2, azi),
correct_uv(v3.uv, v3, azi)
]
end
|
[
"def",
"make",
"(",
"v1",
",",
"v2",
",",
"v3",
")",
"face",
"=",
"Face3",
".",
"new",
"(",
"v1",
".",
"index",
",",
"v2",
".",
"index",
",",
"v3",
".",
"index",
",",
"[",
"v1",
".",
"clone",
",",
"v2",
".",
"clone",
",",
"v3",
".",
"clone",
"]",
")",
"@faces",
"<<",
"face",
"@centroid",
".",
"copy",
"(",
"v1",
")",
".",
"add",
"(",
"v2",
")",
".",
"add",
"(",
"v3",
")",
".",
"divide_scalar",
"(",
"3",
")",
"azi",
"=",
"azimuth",
"(",
"@centroid",
")",
"@face_vertex_uvs",
"[",
"0",
"]",
"<<",
"[",
"correct_uv",
"(",
"v1",
".",
"uv",
",",
"v1",
",",
"azi",
")",
",",
"correct_uv",
"(",
"v2",
".",
"uv",
",",
"v2",
",",
"azi",
")",
",",
"correct_uv",
"(",
"v3",
".",
"uv",
",",
"v3",
",",
"azi",
")",
"]",
"end"
] |
Approximate a curved face with recursively sub-divided triangles.
|
[
"Approximate",
"a",
"curved",
"face",
"with",
"recursively",
"sub",
"-",
"divided",
"triangles",
"."
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L89-L102
|
18,429
|
jellymann/mittsu
|
lib/mittsu/extras/geometries/polyhedron_geometry.rb
|
Mittsu.PolyhedronGeometry.subdivide
|
def subdivide(face, detail)
cols = 2.0 ** detail
a = prepare(@vertices[face.a])
b = prepare(@vertices[face.b])
c = prepare(@vertices[face.c])
v = []
# Construct all of the vertices for this subdivision.
for i in 0..cols do
v[i] = []
aj = prepare(a.clone.lerp(c, i.to_f / cols.to_f))
bj = prepare(b.clone.lerp(c, i.to_f / cols.to_f))
rows = cols - i
for j in 0..rows do
v[i][j] = if j.zero? && i == cols
aj
else
prepare(aj.clone.lerp(bj, j.to_f / rows.to_f))
end
end
end
# Construct all of the faces
for i in 0...cols do
for j in (0...(2 * (cols - i) - 1)) do
k = j/2
if j.even?
make(
v[i][k + 1],
v[i + 1][k],
v[i][k]
)
else
make(
v[i][k + 1],
v[i + 1][k + 1],
v[i + 1][k]
)
end
end
end
end
|
ruby
|
def subdivide(face, detail)
cols = 2.0 ** detail
a = prepare(@vertices[face.a])
b = prepare(@vertices[face.b])
c = prepare(@vertices[face.c])
v = []
# Construct all of the vertices for this subdivision.
for i in 0..cols do
v[i] = []
aj = prepare(a.clone.lerp(c, i.to_f / cols.to_f))
bj = prepare(b.clone.lerp(c, i.to_f / cols.to_f))
rows = cols - i
for j in 0..rows do
v[i][j] = if j.zero? && i == cols
aj
else
prepare(aj.clone.lerp(bj, j.to_f / rows.to_f))
end
end
end
# Construct all of the faces
for i in 0...cols do
for j in (0...(2 * (cols - i) - 1)) do
k = j/2
if j.even?
make(
v[i][k + 1],
v[i + 1][k],
v[i][k]
)
else
make(
v[i][k + 1],
v[i + 1][k + 1],
v[i + 1][k]
)
end
end
end
end
|
[
"def",
"subdivide",
"(",
"face",
",",
"detail",
")",
"cols",
"=",
"2.0",
"**",
"detail",
"a",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"a",
"]",
")",
"b",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"b",
"]",
")",
"c",
"=",
"prepare",
"(",
"@vertices",
"[",
"face",
".",
"c",
"]",
")",
"v",
"=",
"[",
"]",
"# Construct all of the vertices for this subdivision.",
"for",
"i",
"in",
"0",
"..",
"cols",
"do",
"v",
"[",
"i",
"]",
"=",
"[",
"]",
"aj",
"=",
"prepare",
"(",
"a",
".",
"clone",
".",
"lerp",
"(",
"c",
",",
"i",
".",
"to_f",
"/",
"cols",
".",
"to_f",
")",
")",
"bj",
"=",
"prepare",
"(",
"b",
".",
"clone",
".",
"lerp",
"(",
"c",
",",
"i",
".",
"to_f",
"/",
"cols",
".",
"to_f",
")",
")",
"rows",
"=",
"cols",
"-",
"i",
"for",
"j",
"in",
"0",
"..",
"rows",
"do",
"v",
"[",
"i",
"]",
"[",
"j",
"]",
"=",
"if",
"j",
".",
"zero?",
"&&",
"i",
"==",
"cols",
"aj",
"else",
"prepare",
"(",
"aj",
".",
"clone",
".",
"lerp",
"(",
"bj",
",",
"j",
".",
"to_f",
"/",
"rows",
".",
"to_f",
")",
")",
"end",
"end",
"end",
"# Construct all of the faces",
"for",
"i",
"in",
"0",
"...",
"cols",
"do",
"for",
"j",
"in",
"(",
"0",
"...",
"(",
"2",
"*",
"(",
"cols",
"-",
"i",
")",
"-",
"1",
")",
")",
"do",
"k",
"=",
"j",
"/",
"2",
"if",
"j",
".",
"even?",
"make",
"(",
"v",
"[",
"i",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"]",
",",
"v",
"[",
"i",
"]",
"[",
"k",
"]",
")",
"else",
"make",
"(",
"v",
"[",
"i",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"+",
"1",
"]",
",",
"v",
"[",
"i",
"+",
"1",
"]",
"[",
"k",
"]",
")",
"end",
"end",
"end",
"end"
] |
Analytically subdivide a face to the required detail level.
|
[
"Analytically",
"subdivide",
"a",
"face",
"to",
"the",
"required",
"detail",
"level",
"."
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L105-L149
|
18,430
|
jellymann/mittsu
|
lib/mittsu/extras/geometries/polyhedron_geometry.rb
|
Mittsu.PolyhedronGeometry.inclination
|
def inclination(vector)
Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z))
end
|
ruby
|
def inclination(vector)
Math.atan2(-vector.y, Math.sqrt(vector.x * vector.x + vector.z * vector.z))
end
|
[
"def",
"inclination",
"(",
"vector",
")",
"Math",
".",
"atan2",
"(",
"-",
"vector",
".",
"y",
",",
"Math",
".",
"sqrt",
"(",
"vector",
".",
"x",
"*",
"vector",
".",
"x",
"+",
"vector",
".",
"z",
"*",
"vector",
".",
"z",
")",
")",
"end"
] |
Angle above the XZ plane.
|
[
"Angle",
"above",
"the",
"XZ",
"plane",
"."
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L157-L159
|
18,431
|
jellymann/mittsu
|
lib/mittsu/extras/geometries/polyhedron_geometry.rb
|
Mittsu.PolyhedronGeometry.correct_uv
|
def correct_uv(uv, vector, azimuth)
return Vector2.new(uv.x - 1.0, uv.y) if azimuth < 0
return Vector2.new(azimuth / 2.0 / Math::PI + 0.5, uv.y) if vector.x.zero? && vector.z.zero?
uv.clone
end
|
ruby
|
def correct_uv(uv, vector, azimuth)
return Vector2.new(uv.x - 1.0, uv.y) if azimuth < 0
return Vector2.new(azimuth / 2.0 / Math::PI + 0.5, uv.y) if vector.x.zero? && vector.z.zero?
uv.clone
end
|
[
"def",
"correct_uv",
"(",
"uv",
",",
"vector",
",",
"azimuth",
")",
"return",
"Vector2",
".",
"new",
"(",
"uv",
".",
"x",
"-",
"1.0",
",",
"uv",
".",
"y",
")",
"if",
"azimuth",
"<",
"0",
"return",
"Vector2",
".",
"new",
"(",
"azimuth",
"/",
"2.0",
"/",
"Math",
"::",
"PI",
"+",
"0.5",
",",
"uv",
".",
"y",
")",
"if",
"vector",
".",
"x",
".",
"zero?",
"&&",
"vector",
".",
"z",
".",
"zero?",
"uv",
".",
"clone",
"end"
] |
Texture fixing helper. Spheres have some odd behaviours.
|
[
"Texture",
"fixing",
"helper",
".",
"Spheres",
"have",
"some",
"odd",
"behaviours",
"."
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/extras/geometries/polyhedron_geometry.rb#L162-L166
|
18,432
|
jellymann/mittsu
|
lib/mittsu/renderers/opengl/textures/texture.rb
|
Mittsu.Texture.filter_fallback
|
def filter_fallback(filter)
if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter
GL_NEAREST
end
GL_LINEAR
end
|
ruby
|
def filter_fallback(filter)
if filter == NearestFilter || filter == NearestMipMapNearestFilter || f == NearestMipMapLinearFilter
GL_NEAREST
end
GL_LINEAR
end
|
[
"def",
"filter_fallback",
"(",
"filter",
")",
"if",
"filter",
"==",
"NearestFilter",
"||",
"filter",
"==",
"NearestMipMapNearestFilter",
"||",
"f",
"==",
"NearestMipMapLinearFilter",
"GL_NEAREST",
"end",
"GL_LINEAR",
"end"
] |
Fallback filters for non-power-of-2 textures
|
[
"Fallback",
"filters",
"for",
"non",
"-",
"power",
"-",
"of",
"-",
"2",
"textures"
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/textures/texture.rb#L79-L85
|
18,433
|
jellymann/mittsu
|
lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb
|
Mittsu.ShadowMapPlugin.update_virtual_light
|
def update_virtual_light(light, cascade)
virtual_light = light.shadow_cascade_array[cascade]
virtual_light.position.copy(light.position)
virtual_light.target.position.copy(light.target.position)
virtual_light.look_at(virtual_light.target)
virtual_light.shadow_camera_visible = light.shadow_camera_visible
virtual_light.shadow_darkness = light.shadow_darkness
virtual_light.shadow_bias = light.shadow_cascade_bias[cascade]
near_z = light.shadow_cascade_near_z[cascade]
far_z = light.shadow_cascade_far_z[cascade]
points_frustum = virtual_light.points_frustum
points_frustum[0].z = near_z
points_frustum[1].z = near_z
points_frustum[2].z = near_z
points_frustum[3].z = near_z
points_frustum[4].z = far_z
points_frustum[5].z = far_z
points_frustum[6].z = far_z
points_frustum[7].z = far_z
end
|
ruby
|
def update_virtual_light(light, cascade)
virtual_light = light.shadow_cascade_array[cascade]
virtual_light.position.copy(light.position)
virtual_light.target.position.copy(light.target.position)
virtual_light.look_at(virtual_light.target)
virtual_light.shadow_camera_visible = light.shadow_camera_visible
virtual_light.shadow_darkness = light.shadow_darkness
virtual_light.shadow_bias = light.shadow_cascade_bias[cascade]
near_z = light.shadow_cascade_near_z[cascade]
far_z = light.shadow_cascade_far_z[cascade]
points_frustum = virtual_light.points_frustum
points_frustum[0].z = near_z
points_frustum[1].z = near_z
points_frustum[2].z = near_z
points_frustum[3].z = near_z
points_frustum[4].z = far_z
points_frustum[5].z = far_z
points_frustum[6].z = far_z
points_frustum[7].z = far_z
end
|
[
"def",
"update_virtual_light",
"(",
"light",
",",
"cascade",
")",
"virtual_light",
"=",
"light",
".",
"shadow_cascade_array",
"[",
"cascade",
"]",
"virtual_light",
".",
"position",
".",
"copy",
"(",
"light",
".",
"position",
")",
"virtual_light",
".",
"target",
".",
"position",
".",
"copy",
"(",
"light",
".",
"target",
".",
"position",
")",
"virtual_light",
".",
"look_at",
"(",
"virtual_light",
".",
"target",
")",
"virtual_light",
".",
"shadow_camera_visible",
"=",
"light",
".",
"shadow_camera_visible",
"virtual_light",
".",
"shadow_darkness",
"=",
"light",
".",
"shadow_darkness",
"virtual_light",
".",
"shadow_bias",
"=",
"light",
".",
"shadow_cascade_bias",
"[",
"cascade",
"]",
"near_z",
"=",
"light",
".",
"shadow_cascade_near_z",
"[",
"cascade",
"]",
"far_z",
"=",
"light",
".",
"shadow_cascade_far_z",
"[",
"cascade",
"]",
"points_frustum",
"=",
"virtual_light",
".",
"points_frustum",
"points_frustum",
"[",
"0",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"1",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"2",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"3",
"]",
".",
"z",
"=",
"near_z",
"points_frustum",
"[",
"4",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"5",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"6",
"]",
".",
"z",
"=",
"far_z",
"points_frustum",
"[",
"7",
"]",
".",
"z",
"=",
"far_z",
"end"
] |
synchronize virtual light with the original light
|
[
"synchronize",
"virtual",
"light",
"with",
"the",
"original",
"light"
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L338-L364
|
18,434
|
jellymann/mittsu
|
lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb
|
Mittsu.ShadowMapPlugin.update_shadow_camera
|
def update_shadow_camera(camera, light)
shadow_camera = light.shadow_camera
points_frustum = light.pointa_frustum
points_world = light.points_world
@min.set(Float::INFINITY, Float::INFINITY, Float::INFINITY)
@max.set(-Float::INFINITY, -Float::INFINITY, -Float::INFINITY)
8.times do |i|
p = points_world[i]
p.copy(points_frustum[i])
p.unproject(camera)
p.apply_matrix4(shadow_camera.matrix_world_inverse)
@min.x = p.x if (p.x < @min.x)
@max.x = p.x if (p.x > @max.x)
@min.y = p.y if (p.y < @min.y)
@max.y = p.y if (p.y > @max.y)
@min.z = p.z if (p.z < @min.z)
@max.z = p.z if (p.z > @max.z)
end
shadow_camera.left = @min.x
shadow_camera.right = @max.x
shadow_camera.top = @max.y
shadow_camera.bottom = @min.y
# can't really fit near/far
# shadow_camera.near = @min.x
# shadow_camera.far = @max.z
shadow_camera.update_projection_matrix
end
|
ruby
|
def update_shadow_camera(camera, light)
shadow_camera = light.shadow_camera
points_frustum = light.pointa_frustum
points_world = light.points_world
@min.set(Float::INFINITY, Float::INFINITY, Float::INFINITY)
@max.set(-Float::INFINITY, -Float::INFINITY, -Float::INFINITY)
8.times do |i|
p = points_world[i]
p.copy(points_frustum[i])
p.unproject(camera)
p.apply_matrix4(shadow_camera.matrix_world_inverse)
@min.x = p.x if (p.x < @min.x)
@max.x = p.x if (p.x > @max.x)
@min.y = p.y if (p.y < @min.y)
@max.y = p.y if (p.y > @max.y)
@min.z = p.z if (p.z < @min.z)
@max.z = p.z if (p.z > @max.z)
end
shadow_camera.left = @min.x
shadow_camera.right = @max.x
shadow_camera.top = @max.y
shadow_camera.bottom = @min.y
# can't really fit near/far
# shadow_camera.near = @min.x
# shadow_camera.far = @max.z
shadow_camera.update_projection_matrix
end
|
[
"def",
"update_shadow_camera",
"(",
"camera",
",",
"light",
")",
"shadow_camera",
"=",
"light",
".",
"shadow_camera",
"points_frustum",
"=",
"light",
".",
"pointa_frustum",
"points_world",
"=",
"light",
".",
"points_world",
"@min",
".",
"set",
"(",
"Float",
"::",
"INFINITY",
",",
"Float",
"::",
"INFINITY",
",",
"Float",
"::",
"INFINITY",
")",
"@max",
".",
"set",
"(",
"-",
"Float",
"::",
"INFINITY",
",",
"-",
"Float",
"::",
"INFINITY",
",",
"-",
"Float",
"::",
"INFINITY",
")",
"8",
".",
"times",
"do",
"|",
"i",
"|",
"p",
"=",
"points_world",
"[",
"i",
"]",
"p",
".",
"copy",
"(",
"points_frustum",
"[",
"i",
"]",
")",
"p",
".",
"unproject",
"(",
"camera",
")",
"p",
".",
"apply_matrix4",
"(",
"shadow_camera",
".",
"matrix_world_inverse",
")",
"@min",
".",
"x",
"=",
"p",
".",
"x",
"if",
"(",
"p",
".",
"x",
"<",
"@min",
".",
"x",
")",
"@max",
".",
"x",
"=",
"p",
".",
"x",
"if",
"(",
"p",
".",
"x",
">",
"@max",
".",
"x",
")",
"@min",
".",
"y",
"=",
"p",
".",
"y",
"if",
"(",
"p",
".",
"y",
"<",
"@min",
".",
"y",
")",
"@max",
".",
"y",
"=",
"p",
".",
"y",
"if",
"(",
"p",
".",
"y",
">",
"@max",
".",
"y",
")",
"@min",
".",
"z",
"=",
"p",
".",
"z",
"if",
"(",
"p",
".",
"z",
"<",
"@min",
".",
"z",
")",
"@max",
".",
"z",
"=",
"p",
".",
"z",
"if",
"(",
"p",
".",
"z",
">",
"@max",
".",
"z",
")",
"end",
"shadow_camera",
".",
"left",
"=",
"@min",
".",
"x",
"shadow_camera",
".",
"right",
"=",
"@max",
".",
"x",
"shadow_camera",
".",
"top",
"=",
"@max",
".",
"y",
"shadow_camera",
".",
"bottom",
"=",
"@min",
".",
"y",
"# can't really fit near/far",
"# shadow_camera.near = @min.x",
"# shadow_camera.far = @max.z",
"shadow_camera",
".",
"update_projection_matrix",
"end"
] |
fit shadow camera's ortho frustum to camera frustum
|
[
"fit",
"shadow",
"camera",
"s",
"ortho",
"frustum",
"to",
"camera",
"frustum"
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L368-L404
|
18,435
|
jellymann/mittsu
|
lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb
|
Mittsu.ShadowMapPlugin.get_object_material
|
def get_object_material(object)
if object.material.is_a?(MeshFaceMaterial)
object.material.materials[0]
else
object.material
end
end
|
ruby
|
def get_object_material(object)
if object.material.is_a?(MeshFaceMaterial)
object.material.materials[0]
else
object.material
end
end
|
[
"def",
"get_object_material",
"(",
"object",
")",
"if",
"object",
".",
"material",
".",
"is_a?",
"(",
"MeshFaceMaterial",
")",
"object",
".",
"material",
".",
"materials",
"[",
"0",
"]",
"else",
"object",
".",
"material",
"end",
"end"
] |
For the moment just ignore objects that have multiple materials with different animation methods
Only the frst material will be taken into account for deciding which depth material to use for shadow maps
|
[
"For",
"the",
"moment",
"just",
"ignore",
"objects",
"that",
"have",
"multiple",
"materials",
"with",
"different",
"animation",
"methods",
"Only",
"the",
"frst",
"material",
"will",
"be",
"taken",
"into",
"account",
"for",
"deciding",
"which",
"depth",
"material",
"to",
"use",
"for",
"shadow",
"maps"
] |
955bde855c727d775b80f2c88457cb4b58c8c8f8
|
https://github.com/jellymann/mittsu/blob/955bde855c727d775b80f2c88457cb4b58c8c8f8/lib/mittsu/renderers/opengl/plugins/shadow_map_plugin.rb#L409-L415
|
18,436
|
reinteractive/wallaby
|
lib/helpers/wallaby/resources_helper.rb
|
Wallaby.ResourcesHelper.show_title
|
def show_title(decorated)
raise ::ArgumentError unless decorated.is_a? ResourceDecorator
[
to_model_label(decorated.model_class), decorated.to_label
].compact.join ': '
end
|
ruby
|
def show_title(decorated)
raise ::ArgumentError unless decorated.is_a? ResourceDecorator
[
to_model_label(decorated.model_class), decorated.to_label
].compact.join ': '
end
|
[
"def",
"show_title",
"(",
"decorated",
")",
"raise",
"::",
"ArgumentError",
"unless",
"decorated",
".",
"is_a?",
"ResourceDecorator",
"[",
"to_model_label",
"(",
"decorated",
".",
"model_class",
")",
",",
"decorated",
".",
"to_label",
"]",
".",
"compact",
".",
"join",
"': '",
"end"
] |
Title for show page of given resource
@param decorated [Wallaby::ResourceDecorator]
@return [String]
|
[
"Title",
"for",
"show",
"page",
"of",
"given",
"resource"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/resources_helper.rb#L31-L36
|
18,437
|
reinteractive/wallaby
|
lib/helpers/wallaby/secure_helper.rb
|
Wallaby.SecureHelper.user_portrait
|
def user_portrait(user = current_user)
email_method = security.email_method || :email
email = ModuleUtils.try_to user, email_method
if email.present?
https = "http#{request.ssl? ? 's' : EMPTY_STRING}"
email_md5 = ::Digest::MD5.hexdigest email.downcase
image_source = "#{https}://www.gravatar.com/avatar/#{email_md5}"
image_tag image_source, class: 'user'
else
fa_icon 'user'
end
end
|
ruby
|
def user_portrait(user = current_user)
email_method = security.email_method || :email
email = ModuleUtils.try_to user, email_method
if email.present?
https = "http#{request.ssl? ? 's' : EMPTY_STRING}"
email_md5 = ::Digest::MD5.hexdigest email.downcase
image_source = "#{https}://www.gravatar.com/avatar/#{email_md5}"
image_tag image_source, class: 'user'
else
fa_icon 'user'
end
end
|
[
"def",
"user_portrait",
"(",
"user",
"=",
"current_user",
")",
"email_method",
"=",
"security",
".",
"email_method",
"||",
":email",
"email",
"=",
"ModuleUtils",
".",
"try_to",
"user",
",",
"email_method",
"if",
"email",
".",
"present?",
"https",
"=",
"\"http#{request.ssl? ? 's' : EMPTY_STRING}\"",
"email_md5",
"=",
"::",
"Digest",
"::",
"MD5",
".",
"hexdigest",
"email",
".",
"downcase",
"image_source",
"=",
"\"#{https}://www.gravatar.com/avatar/#{email_md5}\"",
"image_tag",
"image_source",
",",
"class",
":",
"'user'",
"else",
"fa_icon",
"'user'",
"end",
"end"
] |
Image portrait for given user.
- if email is present, a gravatar image tag will be returned
- otherwise, an user icon will be returned
@param user [Object]
@return [String] IMG or I element
|
[
"Image",
"portrait",
"for",
"given",
"user",
".",
"-",
"if",
"email",
"is",
"present",
"a",
"gravatar",
"image",
"tag",
"will",
"be",
"returned",
"-",
"otherwise",
"an",
"user",
"icon",
"will",
"be",
"returned"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L9-L20
|
18,438
|
reinteractive/wallaby
|
lib/helpers/wallaby/secure_helper.rb
|
Wallaby.SecureHelper.logout_path
|
def logout_path(user = current_user, app = main_app)
path = security.logout_path
path ||=
if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
"destroy_#{scope}_session_path"
end
ModuleUtils.try_to app, path
end
|
ruby
|
def logout_path(user = current_user, app = main_app)
path = security.logout_path
path ||=
if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
"destroy_#{scope}_session_path"
end
ModuleUtils.try_to app, path
end
|
[
"def",
"logout_path",
"(",
"user",
"=",
"current_user",
",",
"app",
"=",
"main_app",
")",
"path",
"=",
"security",
".",
"logout_path",
"path",
"||=",
"if",
"defined?",
"::",
"Devise",
"scope",
"=",
"::",
"Devise",
"::",
"Mapping",
".",
"find_scope!",
"user",
"\"destroy_#{scope}_session_path\"",
"end",
"ModuleUtils",
".",
"try_to",
"app",
",",
"path",
"end"
] |
Logout path for given user
@see Wallaby::Configuration::Security#logout_path
@param user [Object]
@param app [Object]
@return [String] URL to log out
|
[
"Logout",
"path",
"for",
"given",
"user"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L27-L35
|
18,439
|
reinteractive/wallaby
|
lib/helpers/wallaby/secure_helper.rb
|
Wallaby.SecureHelper.logout_method
|
def logout_method(user = current_user)
http_method = security.logout_method
http_method || if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
mapping = ::Devise.mappings[scope]
mapping.sign_out_via
end
end
|
ruby
|
def logout_method(user = current_user)
http_method = security.logout_method
http_method || if defined? ::Devise
scope = ::Devise::Mapping.find_scope! user
mapping = ::Devise.mappings[scope]
mapping.sign_out_via
end
end
|
[
"def",
"logout_method",
"(",
"user",
"=",
"current_user",
")",
"http_method",
"=",
"security",
".",
"logout_method",
"http_method",
"||",
"if",
"defined?",
"::",
"Devise",
"scope",
"=",
"::",
"Devise",
"::",
"Mapping",
".",
"find_scope!",
"user",
"mapping",
"=",
"::",
"Devise",
".",
"mappings",
"[",
"scope",
"]",
"mapping",
".",
"sign_out_via",
"end",
"end"
] |
Logout method for given user
@see Wallaby::Configuration::Security#logout_method
@param user [Object]
@return [String, Symbol] http method to log out
|
[
"Logout",
"method",
"for",
"given",
"user"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/secure_helper.rb#L41-L48
|
18,440
|
reinteractive/wallaby
|
lib/routes/wallaby/resources_router.rb
|
Wallaby.ResourcesRouter.find_controller_by
|
def find_controller_by(params)
model_class = find_model_class_by params
Map.controller_map(model_class, params[:resources_controller]) || default_controller(params)
end
|
ruby
|
def find_controller_by(params)
model_class = find_model_class_by params
Map.controller_map(model_class, params[:resources_controller]) || default_controller(params)
end
|
[
"def",
"find_controller_by",
"(",
"params",
")",
"model_class",
"=",
"find_model_class_by",
"params",
"Map",
".",
"controller_map",
"(",
"model_class",
",",
"params",
"[",
":resources_controller",
"]",
")",
"||",
"default_controller",
"(",
"params",
")",
"end"
] |
Find controller class
@param params [Hash]
@return [Class] controller class
|
[
"Find",
"controller",
"class"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L29-L32
|
18,441
|
reinteractive/wallaby
|
lib/routes/wallaby/resources_router.rb
|
Wallaby.ResourcesRouter.find_model_class_by
|
def find_model_class_by(params)
model_class = Map.model_class_map params[:resources]
return model_class unless MODEL_ACTIONS.include? params[:action].to_sym
raise ModelNotFound, params[:resources] unless model_class
unless Map.mode_map[model_class]
raise UnprocessableEntity, I18n.t('errors.unprocessable_entity.model', model: model_class)
end
model_class
end
|
ruby
|
def find_model_class_by(params)
model_class = Map.model_class_map params[:resources]
return model_class unless MODEL_ACTIONS.include? params[:action].to_sym
raise ModelNotFound, params[:resources] unless model_class
unless Map.mode_map[model_class]
raise UnprocessableEntity, I18n.t('errors.unprocessable_entity.model', model: model_class)
end
model_class
end
|
[
"def",
"find_model_class_by",
"(",
"params",
")",
"model_class",
"=",
"Map",
".",
"model_class_map",
"params",
"[",
":resources",
"]",
"return",
"model_class",
"unless",
"MODEL_ACTIONS",
".",
"include?",
"params",
"[",
":action",
"]",
".",
"to_sym",
"raise",
"ModelNotFound",
",",
"params",
"[",
":resources",
"]",
"unless",
"model_class",
"unless",
"Map",
".",
"mode_map",
"[",
"model_class",
"]",
"raise",
"UnprocessableEntity",
",",
"I18n",
".",
"t",
"(",
"'errors.unprocessable_entity.model'",
",",
"model",
":",
"model_class",
")",
"end",
"model_class",
"end"
] |
Find out the model class
@param params [Hash]
@return [Class]
@raise [Wallaby::ModelNotFound] when model class is not found
@raise [Wallaby::UnprocessableEntity] when there is no corresponding mode found for model class
|
[
"Find",
"out",
"the",
"model",
"class"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L49-L57
|
18,442
|
reinteractive/wallaby
|
lib/routes/wallaby/resources_router.rb
|
Wallaby.ResourcesRouter.set_message_for
|
def set_message_for(exception, env)
session = env[ActionDispatch::Request::Session::ENV_SESSION_KEY] || {}
env[ActionDispatch::Flash::KEY] ||= ActionDispatch::Flash::FlashHash.from_session_value session['flash']
flash = env[ActionDispatch::Flash::KEY]
flash[:alert] = exception.message
end
|
ruby
|
def set_message_for(exception, env)
session = env[ActionDispatch::Request::Session::ENV_SESSION_KEY] || {}
env[ActionDispatch::Flash::KEY] ||= ActionDispatch::Flash::FlashHash.from_session_value session['flash']
flash = env[ActionDispatch::Flash::KEY]
flash[:alert] = exception.message
end
|
[
"def",
"set_message_for",
"(",
"exception",
",",
"env",
")",
"session",
"=",
"env",
"[",
"ActionDispatch",
"::",
"Request",
"::",
"Session",
"::",
"ENV_SESSION_KEY",
"]",
"||",
"{",
"}",
"env",
"[",
"ActionDispatch",
"::",
"Flash",
"::",
"KEY",
"]",
"||=",
"ActionDispatch",
"::",
"Flash",
"::",
"FlashHash",
".",
"from_session_value",
"session",
"[",
"'flash'",
"]",
"flash",
"=",
"env",
"[",
"ActionDispatch",
"::",
"Flash",
"::",
"KEY",
"]",
"flash",
"[",
":alert",
"]",
"=",
"exception",
".",
"message",
"end"
] |
Set flash error message
@param exception [Exception]
@param env [Hash] @see http://www.rubydoc.info/github/rack/rack/master/file/SPEC
|
[
"Set",
"flash",
"error",
"message"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/routes/wallaby/resources_router.rb#L62-L67
|
18,443
|
reinteractive/wallaby
|
lib/interfaces/wallaby/model_decorator.rb
|
Wallaby.ModelDecorator.validate_presence_of
|
def validate_presence_of(field_name, type)
type || raise(::ArgumentError, I18n.t('errors.invalid.type_required', field_name: field_name))
end
|
ruby
|
def validate_presence_of(field_name, type)
type || raise(::ArgumentError, I18n.t('errors.invalid.type_required', field_name: field_name))
end
|
[
"def",
"validate_presence_of",
"(",
"field_name",
",",
"type",
")",
"type",
"||",
"raise",
"(",
"::",
"ArgumentError",
",",
"I18n",
".",
"t",
"(",
"'errors.invalid.type_required'",
",",
"field_name",
":",
"field_name",
")",
")",
"end"
] |
Validate presence of a type for given field name
@param type [String, Symbol, nil]
@return [String, Symbol] type
@raise [ArgumentError] when type is nil
|
[
"Validate",
"presence",
"of",
"a",
"type",
"for",
"given",
"field",
"name"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/interfaces/wallaby/model_decorator.rb#L158-L160
|
18,444
|
reinteractive/wallaby
|
lib/helpers/wallaby/styling_helper.rb
|
Wallaby.StylingHelper.itooltip
|
def itooltip(title, icon_suffix = 'info-circle', html_options = {})
html_options[:title] = title
(html_options[:data] ||= {}).merge! toggle: 'tooltip', placement: 'top'
fa_icon icon_suffix, html_options
end
|
ruby
|
def itooltip(title, icon_suffix = 'info-circle', html_options = {})
html_options[:title] = title
(html_options[:data] ||= {}).merge! toggle: 'tooltip', placement: 'top'
fa_icon icon_suffix, html_options
end
|
[
"def",
"itooltip",
"(",
"title",
",",
"icon_suffix",
"=",
"'info-circle'",
",",
"html_options",
"=",
"{",
"}",
")",
"html_options",
"[",
":title",
"]",
"=",
"title",
"(",
"html_options",
"[",
":data",
"]",
"||=",
"{",
"}",
")",
".",
"merge!",
"toggle",
":",
"'tooltip'",
",",
"placement",
":",
"'top'",
"fa_icon",
"icon_suffix",
",",
"html_options",
"end"
] |
Build up tooltip
@param title [String]
@param icon_suffix [String]
@param html_options [Hash]
@return [String] tooltip HTML
|
[
"Build",
"up",
"tooltip"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/styling_helper.rb#L31-L36
|
18,445
|
reinteractive/wallaby
|
lib/helpers/wallaby/styling_helper.rb
|
Wallaby.StylingHelper.imodal
|
def imodal(title, body, html_options = {})
label ||= html_options.delete(:label) \
|| html_options.delete(:icon) || fa_icon('clone')
content_tag :span, class: 'modaler' do
concat link_to(label, '#', data: { target: '#imodal', toggle: 'modal' })
concat content_tag(:span, title, class: 'modaler__title')
concat content_tag(:span, body, class: 'modaler__body')
end
end
|
ruby
|
def imodal(title, body, html_options = {})
label ||= html_options.delete(:label) \
|| html_options.delete(:icon) || fa_icon('clone')
content_tag :span, class: 'modaler' do
concat link_to(label, '#', data: { target: '#imodal', toggle: 'modal' })
concat content_tag(:span, title, class: 'modaler__title')
concat content_tag(:span, body, class: 'modaler__body')
end
end
|
[
"def",
"imodal",
"(",
"title",
",",
"body",
",",
"html_options",
"=",
"{",
"}",
")",
"label",
"||=",
"html_options",
".",
"delete",
"(",
":label",
")",
"||",
"html_options",
".",
"delete",
"(",
":icon",
")",
"||",
"fa_icon",
"(",
"'clone'",
")",
"content_tag",
":span",
",",
"class",
":",
"'modaler'",
"do",
"concat",
"link_to",
"(",
"label",
",",
"'#'",
",",
"data",
":",
"{",
"target",
":",
"'#imodal'",
",",
"toggle",
":",
"'modal'",
"}",
")",
"concat",
"content_tag",
"(",
":span",
",",
"title",
",",
"class",
":",
"'modaler__title'",
")",
"concat",
"content_tag",
"(",
":span",
",",
"body",
",",
"class",
":",
"'modaler__body'",
")",
"end",
"end"
] |
Build up modal
@param title [String]
@param body [String]
@param html_options [Hash]
@return [String] modal HTML
|
[
"Build",
"up",
"modal"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/styling_helper.rb#L43-L51
|
18,446
|
reinteractive/wallaby
|
lib/forms/wallaby/form_builder.rb
|
Wallaby.FormBuilder.error_messages
|
def error_messages(field_name)
errors = Array object.errors[field_name]
return if errors.blank?
content_tag :ul, class: 'errors' do
errors.each do |message|
concat content_tag :li, content_tag(:small, raw(message))
end
end
end
|
ruby
|
def error_messages(field_name)
errors = Array object.errors[field_name]
return if errors.blank?
content_tag :ul, class: 'errors' do
errors.each do |message|
concat content_tag :li, content_tag(:small, raw(message))
end
end
end
|
[
"def",
"error_messages",
"(",
"field_name",
")",
"errors",
"=",
"Array",
"object",
".",
"errors",
"[",
"field_name",
"]",
"return",
"if",
"errors",
".",
"blank?",
"content_tag",
":ul",
",",
"class",
":",
"'errors'",
"do",
"errors",
".",
"each",
"do",
"|",
"message",
"|",
"concat",
"content_tag",
":li",
",",
"content_tag",
"(",
":small",
",",
"raw",
"(",
"message",
")",
")",
"end",
"end",
"end"
] |
Build up the HTML for displaying error messages
@param field_name [String/Symbol]
@return [String] HTML
|
[
"Build",
"up",
"the",
"HTML",
"for",
"displaying",
"error",
"messages"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L14-L23
|
18,447
|
reinteractive/wallaby
|
lib/forms/wallaby/form_builder.rb
|
Wallaby.FormBuilder.label
|
def label(method, text = nil, options = {}, &block)
text = instance_exec(&text) if text.is_a?(Proc)
super
end
|
ruby
|
def label(method, text = nil, options = {}, &block)
text = instance_exec(&text) if text.is_a?(Proc)
super
end
|
[
"def",
"label",
"(",
"method",
",",
"text",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"text",
"=",
"instance_exec",
"(",
"text",
")",
"if",
"text",
".",
"is_a?",
"(",
"Proc",
")",
"super",
"end"
] |
Extend label to accept proc type `text` argument
@see ActionView::Helpers::FormBuilder#label
|
[
"Extend",
"label",
"to",
"accept",
"proc",
"type",
"text",
"argument"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L27-L30
|
18,448
|
reinteractive/wallaby
|
lib/forms/wallaby/form_builder.rb
|
Wallaby.FormBuilder.select
|
def select(method, choices = nil, options = {}, html_options = {}, &block)
choices = instance_exec(&choices) if choices.is_a?(Proc)
super
end
|
ruby
|
def select(method, choices = nil, options = {}, html_options = {}, &block)
choices = instance_exec(&choices) if choices.is_a?(Proc)
super
end
|
[
"def",
"select",
"(",
"method",
",",
"choices",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"html_options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"choices",
"=",
"instance_exec",
"(",
"choices",
")",
"if",
"choices",
".",
"is_a?",
"(",
"Proc",
")",
"super",
"end"
] |
Extend select to accept proc type `choices` argument
@see ActionView::Helpers::FormBuilder#select
|
[
"Extend",
"select",
"to",
"accept",
"proc",
"type",
"choices",
"argument"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L34-L37
|
18,449
|
reinteractive/wallaby
|
lib/forms/wallaby/form_builder.rb
|
Wallaby.FormBuilder.method_missing
|
def method_missing(method, *args, &block)
return super unless @template.respond_to? method
# Delegate the method so that we don't come in here the next time
# when same method is called
self.class.delegate method, to: :@template
@template.public_send method, *args, &block
end
|
ruby
|
def method_missing(method, *args, &block)
return super unless @template.respond_to? method
# Delegate the method so that we don't come in here the next time
# when same method is called
self.class.delegate method, to: :@template
@template.public_send method, *args, &block
end
|
[
"def",
"method_missing",
"(",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"return",
"super",
"unless",
"@template",
".",
"respond_to?",
"method",
"# Delegate the method so that we don't come in here the next time",
"# when same method is called",
"self",
".",
"class",
".",
"delegate",
"method",
",",
"to",
":",
":@template",
"@template",
".",
"public_send",
"method",
",",
"args",
",",
"block",
"end"
] |
Delegate missing method to `@template`
|
[
"Delegate",
"missing",
"method",
"to"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/forms/wallaby/form_builder.rb#L42-L48
|
18,450
|
reinteractive/wallaby
|
lib/helpers/wallaby/form_helper.rb
|
Wallaby.FormHelper.remote_url
|
def remote_url(url, model_class, wildcard = 'QUERY')
url || index_path(model_class, url_params: { q: wildcard, per: pagination.page_size })
end
|
ruby
|
def remote_url(url, model_class, wildcard = 'QUERY')
url || index_path(model_class, url_params: { q: wildcard, per: pagination.page_size })
end
|
[
"def",
"remote_url",
"(",
"url",
",",
"model_class",
",",
"wildcard",
"=",
"'QUERY'",
")",
"url",
"||",
"index_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"q",
":",
"wildcard",
",",
"per",
":",
"pagination",
".",
"page_size",
"}",
")",
"end"
] |
To generate remote URL for auto select plugin.
@see https://github.com/reinteractive/wallaby/blob/master/app/assets/javascripts/wallaby/auto_select.js
auto_select.js
@param url [String, nil]
if URL is nil, it will fall back to default remote URL
@param model_class [Class]
@param wildcard [String] wildcard that auto_select uses to replace with
the typed keyword
@return [String] URL for autocomplete
|
[
"To",
"generate",
"remote",
"URL",
"for",
"auto",
"select",
"plugin",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/form_helper.rb#L19-L21
|
18,451
|
reinteractive/wallaby
|
lib/helpers/wallaby/index_helper.rb
|
Wallaby.IndexHelper.filter_link
|
def filter_link(model_class, filter_name, filters: {}, url_params: {})
is_all = filter_name == :all
config = filters[filter_name] || {}
label = is_all ? all_label : filter_label(filter_name, filters)
url_params =
if config[:default] then index_params.except(:filter).merge(url_params)
else index_params.merge(filter: filter_name).merge(url_params)
end
index_link(model_class, url_params: url_params) { label }
end
|
ruby
|
def filter_link(model_class, filter_name, filters: {}, url_params: {})
is_all = filter_name == :all
config = filters[filter_name] || {}
label = is_all ? all_label : filter_label(filter_name, filters)
url_params =
if config[:default] then index_params.except(:filter).merge(url_params)
else index_params.merge(filter: filter_name).merge(url_params)
end
index_link(model_class, url_params: url_params) { label }
end
|
[
"def",
"filter_link",
"(",
"model_class",
",",
"filter_name",
",",
"filters",
":",
"{",
"}",
",",
"url_params",
":",
"{",
"}",
")",
"is_all",
"=",
"filter_name",
"==",
":all",
"config",
"=",
"filters",
"[",
"filter_name",
"]",
"||",
"{",
"}",
"label",
"=",
"is_all",
"?",
"all_label",
":",
"filter_label",
"(",
"filter_name",
",",
"filters",
")",
"url_params",
"=",
"if",
"config",
"[",
":default",
"]",
"then",
"index_params",
".",
"except",
"(",
":filter",
")",
".",
"merge",
"(",
"url_params",
")",
"else",
"index_params",
".",
"merge",
"(",
"filter",
":",
"filter_name",
")",
".",
"merge",
"(",
"url_params",
")",
"end",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"url_params",
")",
"{",
"label",
"}",
"end"
] |
Link for a given model class and filter name
@param model_class [Class]
@param filter_name [String, Symbol]
@param filters [Hash]
@param url_params [Hash, ActionController::Parameters]
@return [String] HTML anchor link
|
[
"Link",
"for",
"a",
"given",
"model",
"class",
"and",
"filter",
"name"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/index_helper.rb#L54-L63
|
18,452
|
reinteractive/wallaby
|
lib/helpers/wallaby/index_helper.rb
|
Wallaby.IndexHelper.export_link
|
def export_link(model_class, url_params: {})
url_params = index_params.except(:page, :per).merge(format: 'csv').merge(url_params)
index_link(model_class, url_params: url_params) { t 'links.export', ext: 'CSV' }
end
|
ruby
|
def export_link(model_class, url_params: {})
url_params = index_params.except(:page, :per).merge(format: 'csv').merge(url_params)
index_link(model_class, url_params: url_params) { t 'links.export', ext: 'CSV' }
end
|
[
"def",
"export_link",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"url_params",
"=",
"index_params",
".",
"except",
"(",
":page",
",",
":per",
")",
".",
"merge",
"(",
"format",
":",
"'csv'",
")",
".",
"merge",
"(",
"url_params",
")",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"url_params",
")",
"{",
"t",
"'links.export'",
",",
"ext",
":",
"'CSV'",
"}",
"end"
] |
Export link for a given model_class.
It accepts extra url params
@param model_class [Class]
@param url_params [Hash, ActionController::Parameters] extra URL params
@return [String] HTML anchor link
|
[
"Export",
"link",
"for",
"a",
"given",
"model_class",
".",
"It",
"accepts",
"extra",
"url",
"params"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/index_helper.rb#L70-L73
|
18,453
|
reinteractive/wallaby
|
lib/helpers/wallaby/base_helper.rb
|
Wallaby.BaseHelper.model_classes
|
def model_classes(classes = Map.model_classes)
nested_hash = classes.each_with_object({}) do |klass, hash|
hash[klass] = Node.new(klass)
end
nested_hash.each do |klass, node|
node.parent = parent = nested_hash[klass.superclass]
parent.children << node if parent
end
nested_hash.values.select { |v| v.parent.nil? }
end
|
ruby
|
def model_classes(classes = Map.model_classes)
nested_hash = classes.each_with_object({}) do |klass, hash|
hash[klass] = Node.new(klass)
end
nested_hash.each do |klass, node|
node.parent = parent = nested_hash[klass.superclass]
parent.children << node if parent
end
nested_hash.values.select { |v| v.parent.nil? }
end
|
[
"def",
"model_classes",
"(",
"classes",
"=",
"Map",
".",
"model_classes",
")",
"nested_hash",
"=",
"classes",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"klass",
",",
"hash",
"|",
"hash",
"[",
"klass",
"]",
"=",
"Node",
".",
"new",
"(",
"klass",
")",
"end",
"nested_hash",
".",
"each",
"do",
"|",
"klass",
",",
"node",
"|",
"node",
".",
"parent",
"=",
"parent",
"=",
"nested_hash",
"[",
"klass",
".",
"superclass",
"]",
"parent",
".",
"children",
"<<",
"node",
"if",
"parent",
"end",
"nested_hash",
".",
"values",
".",
"select",
"{",
"|",
"v",
"|",
"v",
".",
"parent",
".",
"nil?",
"}",
"end"
] |
Turn a list of classes into tree structure by inheritance.
@param classes [Array<Class>]
a list of all the classes that wallaby supports
@return [Array<Wallaby::Node>] a tree structure of given classes
|
[
"Turn",
"a",
"list",
"of",
"classes",
"into",
"tree",
"structure",
"by",
"inheritance",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/base_helper.rb#L36-L45
|
18,454
|
reinteractive/wallaby
|
lib/helpers/wallaby/base_helper.rb
|
Wallaby.BaseHelper.model_tree
|
def model_tree(array, base_class = nil)
return EMPTY_STRING.html_safe if array.blank?
options = { html_options: { class: 'dropdown-item' } }
content_tag :ul, class: 'dropdown-menu', 'aria-labelledby': base_class do
array.sort_by(&:name).each do |node|
content = index_link(node.klass, options).try :<<, model_tree(node.children)
concat content_tag(:li, content)
end
end
end
|
ruby
|
def model_tree(array, base_class = nil)
return EMPTY_STRING.html_safe if array.blank?
options = { html_options: { class: 'dropdown-item' } }
content_tag :ul, class: 'dropdown-menu', 'aria-labelledby': base_class do
array.sort_by(&:name).each do |node|
content = index_link(node.klass, options).try :<<, model_tree(node.children)
concat content_tag(:li, content)
end
end
end
|
[
"def",
"model_tree",
"(",
"array",
",",
"base_class",
"=",
"nil",
")",
"return",
"EMPTY_STRING",
".",
"html_safe",
"if",
"array",
".",
"blank?",
"options",
"=",
"{",
"html_options",
":",
"{",
"class",
":",
"'dropdown-item'",
"}",
"}",
"content_tag",
":ul",
",",
"class",
":",
"'dropdown-menu'",
",",
"'aria-labelledby'",
":",
"base_class",
"do",
"array",
".",
"sort_by",
"(",
":name",
")",
".",
"each",
"do",
"|",
"node",
"|",
"content",
"=",
"index_link",
"(",
"node",
".",
"klass",
",",
"options",
")",
".",
"try",
":<<",
",",
"model_tree",
"(",
"node",
".",
"children",
")",
"concat",
"content_tag",
"(",
":li",
",",
"content",
")",
"end",
"end",
"end"
] |
Turn the tree of classes into a nested `ul` list.
@param array [Array<Wallaby::Node>] root classes
@return [String] HTML for the whole tree
|
[
"Turn",
"the",
"tree",
"of",
"classes",
"into",
"a",
"nested",
"ul",
"list",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/base_helper.rb#L50-L59
|
18,455
|
reinteractive/wallaby
|
lib/authorizers/wallaby/model_authorizer.rb
|
Wallaby.ModelAuthorizer.init_provider
|
def init_provider(context)
providers = Map.authorizer_provider_map model_class
provider_class = providers[self.class.provider_name]
provider_class ||= providers.values.find { |klass| klass.available? context }
provider_class.new context
end
|
ruby
|
def init_provider(context)
providers = Map.authorizer_provider_map model_class
provider_class = providers[self.class.provider_name]
provider_class ||= providers.values.find { |klass| klass.available? context }
provider_class.new context
end
|
[
"def",
"init_provider",
"(",
"context",
")",
"providers",
"=",
"Map",
".",
"authorizer_provider_map",
"model_class",
"provider_class",
"=",
"providers",
"[",
"self",
".",
"class",
".",
"provider_name",
"]",
"provider_class",
"||=",
"providers",
".",
"values",
".",
"find",
"{",
"|",
"klass",
"|",
"klass",
".",
"available?",
"context",
"}",
"provider_class",
".",
"new",
"context",
"end"
] |
Go through provider list and detect which provider is used.
@param context [ActionController::Base]
@return [Wallaby::Authorizer]
|
[
"Go",
"through",
"provider",
"list",
"and",
"detect",
"which",
"provider",
"is",
"used",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/model_authorizer.rb#L69-L74
|
18,456
|
reinteractive/wallaby
|
app/controllers/wallaby/application_controller.rb
|
Wallaby.ApplicationController.error_rendering
|
def error_rendering(exception, symbol)
Rails.logger.error exception
@exception = exception
@symbol = symbol
@code = Rack::Utils::SYMBOL_TO_STATUS_CODE[symbol].to_i
respond_with @exception, status: @code, template: ERROR_PATH, prefixes: _prefixes
end
|
ruby
|
def error_rendering(exception, symbol)
Rails.logger.error exception
@exception = exception
@symbol = symbol
@code = Rack::Utils::SYMBOL_TO_STATUS_CODE[symbol].to_i
respond_with @exception, status: @code, template: ERROR_PATH, prefixes: _prefixes
end
|
[
"def",
"error_rendering",
"(",
"exception",
",",
"symbol",
")",
"Rails",
".",
"logger",
".",
"error",
"exception",
"@exception",
"=",
"exception",
"@symbol",
"=",
"symbol",
"@code",
"=",
"Rack",
"::",
"Utils",
"::",
"SYMBOL_TO_STATUS_CODE",
"[",
"symbol",
"]",
".",
"to_i",
"respond_with",
"@exception",
",",
"status",
":",
"@code",
",",
"template",
":",
"ERROR_PATH",
",",
"prefixes",
":",
"_prefixes",
"end"
] |
Capture exceptions and display the error using error template.
@param exception [Exception]
@param symbol [Symbol] http status symbol
|
[
"Capture",
"exceptions",
"and",
"display",
"the",
"error",
"using",
"error",
"template",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/app/controllers/wallaby/application_controller.rb#L73-L80
|
18,457
|
reinteractive/wallaby
|
lib/concerns/wallaby/authorizable.rb
|
Wallaby.Authorizable.authorized?
|
def authorized?(action, subject)
return false unless subject
klass = subject.is_a?(Class) ? subject : subject.class
authorizer_of(klass).authorized? action, subject
end
|
ruby
|
def authorized?(action, subject)
return false unless subject
klass = subject.is_a?(Class) ? subject : subject.class
authorizer_of(klass).authorized? action, subject
end
|
[
"def",
"authorized?",
"(",
"action",
",",
"subject",
")",
"return",
"false",
"unless",
"subject",
"klass",
"=",
"subject",
".",
"is_a?",
"(",
"Class",
")",
"?",
"subject",
":",
"subject",
".",
"class",
"authorizer_of",
"(",
"klass",
")",
".",
"authorized?",
"action",
",",
"subject",
"end"
] |
Check if user is allowed to perform action on given subject
@param action [Symbol, String]
@param subject [Object, Class]
@return [true] if allowed
@return [false] if not allowed
@since 5.2.0
|
[
"Check",
"if",
"user",
"is",
"allowed",
"to",
"perform",
"action",
"on",
"given",
"subject"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/authorizable.rb#L67-L71
|
18,458
|
reinteractive/wallaby
|
lib/concerns/wallaby/shared_helpers.rb
|
Wallaby.SharedHelpers.controller_to_get
|
def controller_to_get(attribute_name, class_attribute_name = nil)
class_attribute_name ||= attribute_name
return ModuleUtils.try_to self.class, class_attribute_name if is_a? ::ActionController::Base # controller?
ModuleUtils.try_to controller, attribute_name # view?
end
|
ruby
|
def controller_to_get(attribute_name, class_attribute_name = nil)
class_attribute_name ||= attribute_name
return ModuleUtils.try_to self.class, class_attribute_name if is_a? ::ActionController::Base # controller?
ModuleUtils.try_to controller, attribute_name # view?
end
|
[
"def",
"controller_to_get",
"(",
"attribute_name",
",",
"class_attribute_name",
"=",
"nil",
")",
"class_attribute_name",
"||=",
"attribute_name",
"return",
"ModuleUtils",
".",
"try_to",
"self",
".",
"class",
",",
"class_attribute_name",
"if",
"is_a?",
"::",
"ActionController",
"::",
"Base",
"# controller?",
"ModuleUtils",
".",
"try_to",
"controller",
",",
"attribute_name",
"# view?",
"end"
] |
Fetch value for given attribute.
If it's used in controller, it will fetch it from class attribute.
If it's used in view, it will fetch it from controller.
@param attribute_name [String, Symbol] instance attribute name
@param class_attribute_name [String, Symbol] class attribute name
@return [Object] the value
|
[
"Fetch",
"value",
"for",
"given",
"attribute",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/shared_helpers.rb#L13-L17
|
18,459
|
reinteractive/wallaby
|
lib/renderers/wallaby/custom_lookup_context.rb
|
Wallaby.CustomLookupContext.find_template
|
def find_template(name, prefixes = [], partial = false, keys = [], options = {})
prefixes = [] if partial && name.include?(SLASH) # reset the prefixes if `/` is detected
key = [name, prefixes, partial, keys, options].map(&:inspect).join(SLASH)
cached_lookup[key] ||= super
end
|
ruby
|
def find_template(name, prefixes = [], partial = false, keys = [], options = {})
prefixes = [] if partial && name.include?(SLASH) # reset the prefixes if `/` is detected
key = [name, prefixes, partial, keys, options].map(&:inspect).join(SLASH)
cached_lookup[key] ||= super
end
|
[
"def",
"find_template",
"(",
"name",
",",
"prefixes",
"=",
"[",
"]",
",",
"partial",
"=",
"false",
",",
"keys",
"=",
"[",
"]",
",",
"options",
"=",
"{",
"}",
")",
"prefixes",
"=",
"[",
"]",
"if",
"partial",
"&&",
"name",
".",
"include?",
"(",
"SLASH",
")",
"# reset the prefixes if `/` is detected",
"key",
"=",
"[",
"name",
",",
"prefixes",
",",
"partial",
",",
"keys",
",",
"options",
"]",
".",
"map",
"(",
":inspect",
")",
".",
"join",
"(",
"SLASH",
")",
"cached_lookup",
"[",
"key",
"]",
"||=",
"super",
"end"
] |
It overrides the oirgin method to call the origin `find_template` and cache the result during a request.
@param name [String]
@param prefixes [Array<String>]
@param partial [Boolean]
@param keys [Array<String>] keys of local variables
@param options [Hash]
|
[
"It",
"overrides",
"the",
"oirgin",
"method",
"to",
"call",
"the",
"origin",
"find_template",
"and",
"cache",
"the",
"result",
"during",
"a",
"request",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_lookup_context.rb#L16-L20
|
18,460
|
reinteractive/wallaby
|
lib/authorizers/wallaby/pundit_authorization_provider.rb
|
Wallaby.PunditAuthorizationProvider.authorize
|
def authorize(action, subject)
context.send(:authorize, subject, normalize(action)) && subject
rescue ::Pundit::NotAuthorizedError
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end
|
ruby
|
def authorize(action, subject)
context.send(:authorize, subject, normalize(action)) && subject
rescue ::Pundit::NotAuthorizedError
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end
|
[
"def",
"authorize",
"(",
"action",
",",
"subject",
")",
"context",
".",
"send",
"(",
":authorize",
",",
"subject",
",",
"normalize",
"(",
"action",
")",
")",
"&&",
"subject",
"rescue",
"::",
"Pundit",
"::",
"NotAuthorizedError",
"Rails",
".",
"logger",
".",
"info",
"I18n",
".",
"t",
"(",
"'errors.unauthorized'",
",",
"user",
":",
"user",
",",
"action",
":",
"action",
",",
"subject",
":",
"subject",
")",
"raise",
"Forbidden",
"end"
] |
Check user's permission for an action on given subject.
This method will be used in controller.
@param action [Symbol, String]
@param subject [Object, Class]
@raise [Wallaby::Forbidden] when user is not authorized to perform the action.
|
[
"Check",
"user",
"s",
"permission",
"for",
"an",
"action",
"on",
"given",
"subject",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L18-L23
|
18,461
|
reinteractive/wallaby
|
lib/authorizers/wallaby/pundit_authorization_provider.rb
|
Wallaby.PunditAuthorizationProvider.authorized?
|
def authorized?(action, subject)
policy = context.send :policy, subject
ModuleUtils.try_to policy, normalize(action)
end
|
ruby
|
def authorized?(action, subject)
policy = context.send :policy, subject
ModuleUtils.try_to policy, normalize(action)
end
|
[
"def",
"authorized?",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"ModuleUtils",
".",
"try_to",
"policy",
",",
"normalize",
"(",
"action",
")",
"end"
] |
Check and see if user is allowed to perform an action on given subject
@param action [Symbol, String]
@param subject [Object, Class]
@return [Boolean]
|
[
"Check",
"and",
"see",
"if",
"user",
"is",
"allowed",
"to",
"perform",
"an",
"action",
"on",
"given",
"subject"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L29-L32
|
18,462
|
reinteractive/wallaby
|
lib/authorizers/wallaby/pundit_authorization_provider.rb
|
Wallaby.PunditAuthorizationProvider.attributes_for
|
def attributes_for(action, subject)
policy = context.send :policy, subject
value = ModuleUtils.try_to(policy, "attributes_for_#{action}") || ModuleUtils.try_to(policy, 'attributes_for')
Rails.logger.warn I18n.t('error.pundit.not_found.attributes_for', subject: subject) unless value
value || {}
end
|
ruby
|
def attributes_for(action, subject)
policy = context.send :policy, subject
value = ModuleUtils.try_to(policy, "attributes_for_#{action}") || ModuleUtils.try_to(policy, 'attributes_for')
Rails.logger.warn I18n.t('error.pundit.not_found.attributes_for', subject: subject) unless value
value || {}
end
|
[
"def",
"attributes_for",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"value",
"=",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"\"attributes_for_#{action}\"",
")",
"||",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"'attributes_for'",
")",
"Rails",
".",
"logger",
".",
"warn",
"I18n",
".",
"t",
"(",
"'error.pundit.not_found.attributes_for'",
",",
"subject",
":",
"subject",
")",
"unless",
"value",
"value",
"||",
"{",
"}",
"end"
] |
Restrict user to assign certain values.
It will do a lookup in policy's methods and pick the first available method:
- attributes\_for\_#\{ action \}
- attributes\_for
@param action [Symbol, String]
@param subject [Object]
@return [Hash] field value paired hash that user's allowed to assign
|
[
"Restrict",
"user",
"to",
"assign",
"certain",
"values",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L43-L48
|
18,463
|
reinteractive/wallaby
|
lib/authorizers/wallaby/pundit_authorization_provider.rb
|
Wallaby.PunditAuthorizationProvider.permit_params
|
def permit_params(action, subject)
policy = context.send :policy, subject
# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258
ModuleUtils.try_to(policy, "permitted_attributes_for_#{action}") \
|| ModuleUtils.try_to(policy, 'permitted_attributes')
end
|
ruby
|
def permit_params(action, subject)
policy = context.send :policy, subject
# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258
ModuleUtils.try_to(policy, "permitted_attributes_for_#{action}") \
|| ModuleUtils.try_to(policy, 'permitted_attributes')
end
|
[
"def",
"permit_params",
"(",
"action",
",",
"subject",
")",
"policy",
"=",
"context",
".",
"send",
":policy",
",",
"subject",
"# @see https://github.com/varvet/pundit/blob/master/lib/pundit.rb#L258",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"\"permitted_attributes_for_#{action}\"",
")",
"||",
"ModuleUtils",
".",
"try_to",
"(",
"policy",
",",
"'permitted_attributes'",
")",
"end"
] |
Restrict user for mass assignment.
It will do a lookup in policy's methods and pick the first available method:
- permitted\_attributes\_for\_#\{ action \}
- permitted\_attributes
@param action [Symbol, String]
@param subject [Object]
@return [Array] field list that user's allowed to change.
|
[
"Restrict",
"user",
"for",
"mass",
"assignment",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/pundit_authorization_provider.rb#L59-L64
|
18,464
|
reinteractive/wallaby
|
lib/concerns/wallaby/defaultable.rb
|
Wallaby.Defaultable.set_defaults_for
|
def set_defaults_for(action, options)
case action.try(:to_sym)
when :create, :update then assign_create_and_update_defaults_with options
when :destroy then assign_destroy_defaults_with options
end
options
end
|
ruby
|
def set_defaults_for(action, options)
case action.try(:to_sym)
when :create, :update then assign_create_and_update_defaults_with options
when :destroy then assign_destroy_defaults_with options
end
options
end
|
[
"def",
"set_defaults_for",
"(",
"action",
",",
"options",
")",
"case",
"action",
".",
"try",
"(",
":to_sym",
")",
"when",
":create",
",",
":update",
"then",
"assign_create_and_update_defaults_with",
"options",
"when",
":destroy",
"then",
"assign_destroy_defaults_with",
"options",
"end",
"options",
"end"
] |
Set default options for create action
@param options [Hash]
@return [Hash] updated options with default values
|
[
"Set",
"default",
"options",
"for",
"create",
"action"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/concerns/wallaby/defaultable.rb#L9-L15
|
18,465
|
reinteractive/wallaby
|
lib/authorizers/wallaby/cancancan_authorization_provider.rb
|
Wallaby.CancancanAuthorizationProvider.authorize
|
def authorize(action, subject)
current_ability.authorize! action, subject
rescue ::CanCan::AccessDenied
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end
|
ruby
|
def authorize(action, subject)
current_ability.authorize! action, subject
rescue ::CanCan::AccessDenied
Rails.logger.info I18n.t('errors.unauthorized', user: user, action: action, subject: subject)
raise Forbidden
end
|
[
"def",
"authorize",
"(",
"action",
",",
"subject",
")",
"current_ability",
".",
"authorize!",
"action",
",",
"subject",
"rescue",
"::",
"CanCan",
"::",
"AccessDenied",
"Rails",
".",
"logger",
".",
"info",
"I18n",
".",
"t",
"(",
"'errors.unauthorized'",
",",
"user",
":",
"user",
",",
"action",
":",
"action",
",",
"subject",
":",
"subject",
")",
"raise",
"Forbidden",
"end"
] |
Check user's permission for an action on given subject.
This method will be used in controller.
@param action [Symbol, String]
@param subject [Object, Class]
@raise [Wallaby::Forbidden] when user is not authorized to perform the action.
|
[
"Check",
"user",
"s",
"permission",
"for",
"an",
"action",
"on",
"given",
"subject",
".",
"This",
"method",
"will",
"be",
"used",
"in",
"controller",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/authorizers/wallaby/cancancan_authorization_provider.rb#L19-L24
|
18,466
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.index_link
|
def index_link(model_class, url_params: {}, html_options: {}, &block)
return if unauthorized? :index, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { to_model_label model_class }
)
path = index_path model_class, url_params: url_params
link_to path, html_options, &block
end
|
ruby
|
def index_link(model_class, url_params: {}, html_options: {}, &block)
return if unauthorized? :index, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { to_model_label model_class }
)
path = index_path model_class, url_params: url_params
link_to path, html_options, &block
end
|
[
"def",
"index_link",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":index",
",",
"model_class",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"block",
":",
"->",
"{",
"to_model_label",
"model_class",
"}",
")",
"path",
"=",
"index_path",
"model_class",
",",
"url_params",
":",
"url_params",
"link_to",
"path",
",",
"html_options",
",",
"block",
"end"
] |
Return link to index page by a given model class
If user's not authorized, nil will be returned
@param model_class [Class]
@param url_params [ActionController::Parameters, Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element
|
[
"Return",
"link",
"to",
"index",
"page",
"by",
"a",
"given",
"model",
"class"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L17-L26
|
18,467
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.new_link
|
def new_link(model_class, html_options: {}, &block)
return if unauthorized? :new, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__create',
block: -> { t 'links.new', model: to_model_label(model_class) }
)
link_to new_path(model_class), html_options, &block
end
|
ruby
|
def new_link(model_class, html_options: {}, &block)
return if unauthorized? :new, model_class
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__create',
block: -> { t 'links.new', model: to_model_label(model_class) }
)
link_to new_path(model_class), html_options, &block
end
|
[
"def",
"new_link",
"(",
"model_class",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":new",
",",
"model_class",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__create'",
",",
"block",
":",
"->",
"{",
"t",
"'links.new'",
",",
"model",
":",
"to_model_label",
"(",
"model_class",
")",
"}",
")",
"link_to",
"new_path",
"(",
"model_class",
")",
",",
"html_options",
",",
"block",
"end"
] |
Return link to create page by a given model class
If user's not authorized, nil will be returned
@param model_class [Class]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element
|
[
"Return",
"link",
"to",
"create",
"page",
"by",
"a",
"given",
"model",
"class"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L34-L43
|
18,468
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.show_link
|
def show_link(resource, options: {}, html_options: {}, &block)
# NOTE: to_s is a must
# if a block is returning integer (e.g. `{ 1 }`)
# `link_to` will render blank text note inside hyper link
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { decorate(resource).to_label.to_s }
)
default = options[:readonly] && block.call || nil
return default if unauthorized? :show, extract(resource)
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
ruby
|
def show_link(resource, options: {}, html_options: {}, &block)
# NOTE: to_s is a must
# if a block is returning integer (e.g. `{ 1 }`)
# `link_to` will render blank text note inside hyper link
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
block: -> { decorate(resource).to_label.to_s }
)
default = options[:readonly] && block.call || nil
return default if unauthorized? :show, extract(resource)
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
[
"def",
"show_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"# NOTE: to_s is a must",
"# if a block is returning integer (e.g. `{ 1 }`)",
"# `link_to` will render blank text note inside hyper link",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"block",
":",
"->",
"{",
"decorate",
"(",
"resource",
")",
".",
"to_label",
".",
"to_s",
"}",
")",
"default",
"=",
"options",
"[",
":readonly",
"]",
"&&",
"block",
".",
"call",
"||",
"nil",
"return",
"default",
"if",
"unauthorized?",
":show",
",",
"extract",
"(",
"resource",
")",
"link_to",
"show_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] |
Return link to show page by a given model class
If user's not authorized, resource label will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param options [Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String] anchor element / text
|
[
"Return",
"link",
"to",
"show",
"page",
"by",
"a",
"given",
"model",
"class",
"If",
"user",
"s",
"not",
"authorized",
"resource",
"label",
"will",
"be",
"returned"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L51-L63
|
18,469
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.edit_link
|
def edit_link(resource, options: {}, html_options: {}, &block)
default = options[:readonly] && decorate(resource).to_label || nil
return default if unauthorized? :edit, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__update',
block: -> { "#{t 'links.edit'} #{decorate(resource).to_label}" }
)
link_to edit_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
ruby
|
def edit_link(resource, options: {}, html_options: {}, &block)
default = options[:readonly] && decorate(resource).to_label || nil
return default if unauthorized? :edit, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__update',
block: -> { "#{t 'links.edit'} #{decorate(resource).to_label}" }
)
link_to edit_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
[
"def",
"edit_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"default",
"=",
"options",
"[",
":readonly",
"]",
"&&",
"decorate",
"(",
"resource",
")",
".",
"to_label",
"||",
"nil",
"return",
"default",
"if",
"unauthorized?",
":edit",
",",
"extract",
"(",
"resource",
")",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__update'",
",",
"block",
":",
"->",
"{",
"\"#{t 'links.edit'} #{decorate(resource).to_label}\"",
"}",
")",
"link_to",
"edit_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] |
Return link to edit page by a given model class
If user's not authorized, resource label will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param options [Hash]
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String] anchor element / text
|
[
"Return",
"link",
"to",
"edit",
"page",
"by",
"a",
"given",
"model",
"class",
"If",
"user",
"s",
"not",
"authorized",
"resource",
"label",
"will",
"be",
"returned"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L71-L82
|
18,470
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.delete_link
|
def delete_link(resource, options: {}, html_options: {}, &block)
return if unauthorized? :destroy, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__destroy',
block: -> { t 'links.delete' }
)
html_options[:method] ||= :delete
html_options[:data] ||= {}
html_options[:data][:confirm] ||= t 'links.confirm.delete'
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
ruby
|
def delete_link(resource, options: {}, html_options: {}, &block)
return if unauthorized? :destroy, extract(resource)
html_options, block = LinkOptionsNormalizer.normalize(
html_options, block,
class: 'resource__destroy',
block: -> { t 'links.delete' }
)
html_options[:method] ||= :delete
html_options[:data] ||= {}
html_options[:data][:confirm] ||= t 'links.confirm.delete'
link_to show_path(resource, HashUtils.slice!(options, :is_resource, :url_params)), html_options, &block
end
|
[
"def",
"delete_link",
"(",
"resource",
",",
"options",
":",
"{",
"}",
",",
"html_options",
":",
"{",
"}",
",",
"&",
"block",
")",
"return",
"if",
"unauthorized?",
":destroy",
",",
"extract",
"(",
"resource",
")",
"html_options",
",",
"block",
"=",
"LinkOptionsNormalizer",
".",
"normalize",
"(",
"html_options",
",",
"block",
",",
"class",
":",
"'resource__destroy'",
",",
"block",
":",
"->",
"{",
"t",
"'links.delete'",
"}",
")",
"html_options",
"[",
":method",
"]",
"||=",
":delete",
"html_options",
"[",
":data",
"]",
"||=",
"{",
"}",
"html_options",
"[",
":data",
"]",
"[",
":confirm",
"]",
"||=",
"t",
"'links.confirm.delete'",
"link_to",
"show_path",
"(",
"resource",
",",
"HashUtils",
".",
"slice!",
"(",
"options",
",",
":is_resource",
",",
":url_params",
")",
")",
",",
"html_options",
",",
"block",
"end"
] |
Return link to delete action by a given model class
If user's not authorized, nil will be returned
@param resource [Object, Wallaby::ResourceDecorator] model class
@param html_options [Hash] (@see ActionView::Helpers::UrlHelper#link_to)
@return [String, nil] anchor element
|
[
"Return",
"link",
"to",
"delete",
"action",
"by",
"a",
"given",
"model",
"class"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L90-L104
|
18,471
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.index_path
|
def index_path(model_class, url_params: {})
if url_params.is_a?(::ActionController::Parameters) \
&& !url_params.permitted?
url_params = {}
end
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :index
)
end
|
ruby
|
def index_path(model_class, url_params: {})
if url_params.is_a?(::ActionController::Parameters) \
&& !url_params.permitted?
url_params = {}
end
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :index
)
end
|
[
"def",
"index_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"if",
"url_params",
".",
"is_a?",
"(",
"::",
"ActionController",
"::",
"Parameters",
")",
"&&",
"!",
"url_params",
".",
"permitted?",
"url_params",
"=",
"{",
"}",
"end",
"url_for",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"to_resources_name",
"(",
"model_class",
")",
",",
"action",
":",
":index",
")",
"end"
] |
Url for index page
@param model_class [Class]
@param url_params [ActionController::Parameters, Hash]
@return [String]
|
[
"Url",
"for",
"index",
"page"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L118-L128
|
18,472
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.new_path
|
def new_path(model_class, url_params: {})
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :new
)
end
|
ruby
|
def new_path(model_class, url_params: {})
url_for url_params.to_h.reverse_merge(
resources: to_resources_name(model_class),
action: :new
)
end
|
[
"def",
"new_path",
"(",
"model_class",
",",
"url_params",
":",
"{",
"}",
")",
"url_for",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"to_resources_name",
"(",
"model_class",
")",
",",
"action",
":",
":new",
")",
"end"
] |
Url for new resource form page
@param model_class [Class]
@return [String]
|
[
"Url",
"for",
"new",
"resource",
"form",
"page"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L133-L138
|
18,473
|
reinteractive/wallaby
|
lib/helpers/wallaby/links_helper.rb
|
Wallaby.LinksHelper.edit_path
|
def edit_path(resource, is_resource: false, url_params: {})
decorated = decorate resource
return unless is_resource || decorated.primary_key_value
url_for(
url_params.to_h.reverse_merge(
resources: decorated.resources_name,
action: :edit,
id: decorated.primary_key_value
).delete_if { |_, v| v.blank? }
)
end
|
ruby
|
def edit_path(resource, is_resource: false, url_params: {})
decorated = decorate resource
return unless is_resource || decorated.primary_key_value
url_for(
url_params.to_h.reverse_merge(
resources: decorated.resources_name,
action: :edit,
id: decorated.primary_key_value
).delete_if { |_, v| v.blank? }
)
end
|
[
"def",
"edit_path",
"(",
"resource",
",",
"is_resource",
":",
"false",
",",
"url_params",
":",
"{",
"}",
")",
"decorated",
"=",
"decorate",
"resource",
"return",
"unless",
"is_resource",
"||",
"decorated",
".",
"primary_key_value",
"url_for",
"(",
"url_params",
".",
"to_h",
".",
"reverse_merge",
"(",
"resources",
":",
"decorated",
".",
"resources_name",
",",
"action",
":",
":edit",
",",
"id",
":",
"decorated",
".",
"primary_key_value",
")",
".",
"delete_if",
"{",
"|",
"_",
",",
"v",
"|",
"v",
".",
"blank?",
"}",
")",
"end"
] |
Url for edit form page of given resource
@param resource [Object]
@param is_resource [Boolean]
@return [String]
|
[
"Url",
"for",
"edit",
"form",
"page",
"of",
"given",
"resource"
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/helpers/wallaby/links_helper.rb#L161-L173
|
18,474
|
reinteractive/wallaby
|
lib/renderers/wallaby/custom_partial_renderer.rb
|
Wallaby.CustomPartialRenderer.render
|
def render(context, options, block)
super
rescue CellHandling => e
CellUtils.render context, e.message, options[:locals], &block
end
|
ruby
|
def render(context, options, block)
super
rescue CellHandling => e
CellUtils.render context, e.message, options[:locals], &block
end
|
[
"def",
"render",
"(",
"context",
",",
"options",
",",
"block",
")",
"super",
"rescue",
"CellHandling",
"=>",
"e",
"CellUtils",
".",
"render",
"context",
",",
"e",
".",
"message",
",",
"options",
"[",
":locals",
"]",
",",
"block",
"end"
] |
When a type partial is found, it works as usual.
But when a cell is found, there is an exception {Wallaby::CellHandling} raised. This error will be captured,
and the cell will be rendered.
@param context [ActionView::Context]
@param options [Hash]
@param block [Proc]
@return [String] HTML output
|
[
"When",
"a",
"type",
"partial",
"is",
"found",
"it",
"works",
"as",
"usual",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_partial_renderer.rb#L12-L16
|
18,475
|
reinteractive/wallaby
|
lib/renderers/wallaby/custom_partial_renderer.rb
|
Wallaby.CustomPartialRenderer.find_partial
|
def find_partial(*)
super.tap do |partial|
raise CellHandling, partial.inspect if CellUtils.cell? partial.inspect
end
end
|
ruby
|
def find_partial(*)
super.tap do |partial|
raise CellHandling, partial.inspect if CellUtils.cell? partial.inspect
end
end
|
[
"def",
"find_partial",
"(",
"*",
")",
"super",
".",
"tap",
"do",
"|",
"partial",
"|",
"raise",
"CellHandling",
",",
"partial",
".",
"inspect",
"if",
"CellUtils",
".",
"cell?",
"partial",
".",
"inspect",
"end",
"end"
] |
Override origin method to stop rendering when a cell is found.
@return [ActionView::Template] partial template
@raise [Wallaby:::CellHandling] when a cell is found
|
[
"Override",
"origin",
"method",
"to",
"stop",
"rendering",
"when",
"a",
"cell",
"is",
"found",
"."
] |
85b86e5e661d68a62aa8ae25d39c4f545c5ac36e
|
https://github.com/reinteractive/wallaby/blob/85b86e5e661d68a62aa8ae25d39c4f545c5ac36e/lib/renderers/wallaby/custom_partial_renderer.rb#L21-L25
|
18,476
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.filter_types
|
def filter_types
types = []
wrap_with_rewind(@filtered_data) do
scanline_positions.each do |pos|
@filtered_data.pos = pos
byte = @filtered_data.read 1
types << byte.unpack('C').first
end
end
types
end
|
ruby
|
def filter_types
types = []
wrap_with_rewind(@filtered_data) do
scanline_positions.each do |pos|
@filtered_data.pos = pos
byte = @filtered_data.read 1
types << byte.unpack('C').first
end
end
types
end
|
[
"def",
"filter_types",
"types",
"=",
"[",
"]",
"wrap_with_rewind",
"(",
"@filtered_data",
")",
"do",
"scanline_positions",
".",
"each",
"do",
"|",
"pos",
"|",
"@filtered_data",
".",
"pos",
"=",
"pos",
"byte",
"=",
"@filtered_data",
".",
"read",
"1",
"types",
"<<",
"byte",
".",
"unpack",
"(",
"'C'",
")",
".",
"first",
"end",
"end",
"types",
"end"
] |
Returns an array of each scanline's filter type value.
|
[
"Returns",
"an",
"array",
"of",
"each",
"scanline",
"s",
"filter",
"type",
"value",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L104-L114
|
18,477
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.compress
|
def compress(
level = Zlib::DEFAULT_COMPRESSION,
window_bits = Zlib::MAX_WBITS,
mem_level = Zlib::DEF_MEM_LEVEL,
strategy = Zlib::DEFAULT_STRATEGY
)
wrap_with_rewind(@compressed_data, @filtered_data) do
z = Zlib::Deflate.new level, window_bits, mem_level, strategy
until @filtered_data.eof? do
buffer_size = 2 ** 16
flush = Zlib::NO_FLUSH
flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size
@compressed_data << z.deflate(@filtered_data.read(buffer_size), flush)
end
z.finish
z.close
truncate_io @compressed_data
end
@is_compressed_data_modified = false
self
end
|
ruby
|
def compress(
level = Zlib::DEFAULT_COMPRESSION,
window_bits = Zlib::MAX_WBITS,
mem_level = Zlib::DEF_MEM_LEVEL,
strategy = Zlib::DEFAULT_STRATEGY
)
wrap_with_rewind(@compressed_data, @filtered_data) do
z = Zlib::Deflate.new level, window_bits, mem_level, strategy
until @filtered_data.eof? do
buffer_size = 2 ** 16
flush = Zlib::NO_FLUSH
flush = Zlib::FINISH if @filtered_data.size - @filtered_data.pos < buffer_size
@compressed_data << z.deflate(@filtered_data.read(buffer_size), flush)
end
z.finish
z.close
truncate_io @compressed_data
end
@is_compressed_data_modified = false
self
end
|
[
"def",
"compress",
"(",
"level",
"=",
"Zlib",
"::",
"DEFAULT_COMPRESSION",
",",
"window_bits",
"=",
"Zlib",
"::",
"MAX_WBITS",
",",
"mem_level",
"=",
"Zlib",
"::",
"DEF_MEM_LEVEL",
",",
"strategy",
"=",
"Zlib",
"::",
"DEFAULT_STRATEGY",
")",
"wrap_with_rewind",
"(",
"@compressed_data",
",",
"@filtered_data",
")",
"do",
"z",
"=",
"Zlib",
"::",
"Deflate",
".",
"new",
"level",
",",
"window_bits",
",",
"mem_level",
",",
"strategy",
"until",
"@filtered_data",
".",
"eof?",
"do",
"buffer_size",
"=",
"2",
"**",
"16",
"flush",
"=",
"Zlib",
"::",
"NO_FLUSH",
"flush",
"=",
"Zlib",
"::",
"FINISH",
"if",
"@filtered_data",
".",
"size",
"-",
"@filtered_data",
".",
"pos",
"<",
"buffer_size",
"@compressed_data",
"<<",
"z",
".",
"deflate",
"(",
"@filtered_data",
".",
"read",
"(",
"buffer_size",
")",
",",
"flush",
")",
"end",
"z",
".",
"finish",
"z",
".",
"close",
"truncate_io",
"@compressed_data",
"end",
"@is_compressed_data_modified",
"=",
"false",
"self",
"end"
] |
Re-compress the filtered data.
All arguments are for Zlib. See the document of Zlib::Deflate.new for more detail.
|
[
"Re",
"-",
"compress",
"the",
"filtered",
"data",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L264-L284
|
18,478
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.each_scanline
|
def each_scanline # :yield: scanline
return enum_for :each_scanline unless block_given?
prev_filters = self.filter_types
is_refilter_needed = false
filter_codecs = []
wrap_with_rewind(@filtered_data) do
at = 0
scanline_positions.push(@filtered_data.size).inject do |pos, delimit|
scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at
yield scanline
if fabricate_scanline(scanline, prev_filters, filter_codecs)
is_refilter_needed = true
end
at += 1
delimit
end
end
apply_filters(prev_filters, filter_codecs) if is_refilter_needed
compress
self
end
|
ruby
|
def each_scanline # :yield: scanline
return enum_for :each_scanline unless block_given?
prev_filters = self.filter_types
is_refilter_needed = false
filter_codecs = []
wrap_with_rewind(@filtered_data) do
at = 0
scanline_positions.push(@filtered_data.size).inject do |pos, delimit|
scanline = Scanline.new @filtered_data, pos, (delimit - pos - 1), at
yield scanline
if fabricate_scanline(scanline, prev_filters, filter_codecs)
is_refilter_needed = true
end
at += 1
delimit
end
end
apply_filters(prev_filters, filter_codecs) if is_refilter_needed
compress
self
end
|
[
"def",
"each_scanline",
"# :yield: scanline",
"return",
"enum_for",
":each_scanline",
"unless",
"block_given?",
"prev_filters",
"=",
"self",
".",
"filter_types",
"is_refilter_needed",
"=",
"false",
"filter_codecs",
"=",
"[",
"]",
"wrap_with_rewind",
"(",
"@filtered_data",
")",
"do",
"at",
"=",
"0",
"scanline_positions",
".",
"push",
"(",
"@filtered_data",
".",
"size",
")",
".",
"inject",
"do",
"|",
"pos",
",",
"delimit",
"|",
"scanline",
"=",
"Scanline",
".",
"new",
"@filtered_data",
",",
"pos",
",",
"(",
"delimit",
"-",
"pos",
"-",
"1",
")",
",",
"at",
"yield",
"scanline",
"if",
"fabricate_scanline",
"(",
"scanline",
",",
"prev_filters",
",",
"filter_codecs",
")",
"is_refilter_needed",
"=",
"true",
"end",
"at",
"+=",
"1",
"delimit",
"end",
"end",
"apply_filters",
"(",
"prev_filters",
",",
"filter_codecs",
")",
"if",
"is_refilter_needed",
"compress",
"self",
"end"
] |
Process each scanline.
It takes a block with a parameter. The parameter must be an instance of
PNGlitch::Scanline and it provides ways to edit the filter type and the data
of the scanlines. Normally it iterates the number of the PNG image height.
Here is some examples:
pnglitch.each_scanline do |line|
line.gsub!(/\w/, '0') # replace all alphabetical chars in data
end
pnglicth.each_scanline do |line|
line.change_filter 3 # change all filter to 3, data will get re-filtering (it won't be a glitch)
end
pnglicth.each_scanline do |line|
line.graft 3 # change all filter to 3 and data remains (it will be a glitch)
end
See PNGlitch::Scanline for more details.
This method is safer than +glitch+ but will be a little bit slow.
-----
Please note that +each_scanline+ will apply the filters *after* the loop. It means
a following example doesn't work as expected.
pnglicth.each_scanline do |line|
line.change_filter 3
line.gsub! /\d/, 'x' # wants to glitch after changing filters.
end
To glitch after applying the new filter types, it should be called separately like:
pnglicth.each_scanline do |line|
line.change_filter 3
end
pnglicth.each_scanline do |line|
line.gsub! /\d/, 'x'
end
|
[
"Process",
"each",
"scanline",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L330-L350
|
18,479
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.width=
|
def width= w
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data << [w].pack('N')
@head_data.pos -= 4
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
break
end
end
@head_data.rewind
w
end
|
ruby
|
def width= w
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data << [w].pack('N')
@head_data.pos -= 4
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
break
end
end
@head_data.rewind
w
end
|
[
"def",
"width",
"=",
"w",
"@head_data",
".",
"pos",
"=",
"8",
"while",
"bytes",
"=",
"@head_data",
".",
"read",
"(",
"8",
")",
"length",
",",
"type",
"=",
"bytes",
".",
"unpack",
"'Na*'",
"if",
"type",
"==",
"'IHDR'",
"@head_data",
"<<",
"[",
"w",
"]",
".",
"pack",
"(",
"'N'",
")",
"@head_data",
".",
"pos",
"-=",
"4",
"data",
"=",
"@head_data",
".",
"read",
"length",
"@head_data",
"<<",
"[",
"Zlib",
".",
"crc32",
"(",
"data",
",",
"Zlib",
".",
"crc32",
"(",
"type",
")",
")",
"]",
".",
"pack",
"(",
"'N'",
")",
"break",
"end",
"end",
"@head_data",
".",
"rewind",
"w",
"end"
] |
Rewrites the width value.
|
[
"Rewrites",
"the",
"width",
"value",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L418-L432
|
18,480
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.height=
|
def height= h
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data.pos += 4
@head_data << [h].pack('N')
@head_data.pos -= 8
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
@head_data.rewind
break
end
end
@head_data.rewind
h
end
|
ruby
|
def height= h
@head_data.pos = 8
while bytes = @head_data.read(8)
length, type = bytes.unpack 'Na*'
if type == 'IHDR'
@head_data.pos += 4
@head_data << [h].pack('N')
@head_data.pos -= 8
data = @head_data.read length
@head_data << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
@head_data.rewind
break
end
end
@head_data.rewind
h
end
|
[
"def",
"height",
"=",
"h",
"@head_data",
".",
"pos",
"=",
"8",
"while",
"bytes",
"=",
"@head_data",
".",
"read",
"(",
"8",
")",
"length",
",",
"type",
"=",
"bytes",
".",
"unpack",
"'Na*'",
"if",
"type",
"==",
"'IHDR'",
"@head_data",
".",
"pos",
"+=",
"4",
"@head_data",
"<<",
"[",
"h",
"]",
".",
"pack",
"(",
"'N'",
")",
"@head_data",
".",
"pos",
"-=",
"8",
"data",
"=",
"@head_data",
".",
"read",
"length",
"@head_data",
"<<",
"[",
"Zlib",
".",
"crc32",
"(",
"data",
",",
"Zlib",
".",
"crc32",
"(",
"type",
")",
")",
"]",
".",
"pack",
"(",
"'N'",
")",
"@head_data",
".",
"rewind",
"break",
"end",
"end",
"@head_data",
".",
"rewind",
"h",
"end"
] |
Rewrites the height value.
|
[
"Rewrites",
"the",
"height",
"value",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L437-L453
|
18,481
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.save
|
def save file
wrap_with_rewind(@head_data, @tail_data, @compressed_data) do
open(file, 'wb') do |io|
io << @head_data.read
chunk_size = @idat_chunk_size || @compressed_data.size
type = 'IDAT'
until @compressed_data.eof? do
data = @compressed_data.read(chunk_size)
io << [data.size].pack('N')
io << type
io << data
io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
end
io << @tail_data.read
end
end
self
end
|
ruby
|
def save file
wrap_with_rewind(@head_data, @tail_data, @compressed_data) do
open(file, 'wb') do |io|
io << @head_data.read
chunk_size = @idat_chunk_size || @compressed_data.size
type = 'IDAT'
until @compressed_data.eof? do
data = @compressed_data.read(chunk_size)
io << [data.size].pack('N')
io << type
io << data
io << [Zlib.crc32(data, Zlib.crc32(type))].pack('N')
end
io << @tail_data.read
end
end
self
end
|
[
"def",
"save",
"file",
"wrap_with_rewind",
"(",
"@head_data",
",",
"@tail_data",
",",
"@compressed_data",
")",
"do",
"open",
"(",
"file",
",",
"'wb'",
")",
"do",
"|",
"io",
"|",
"io",
"<<",
"@head_data",
".",
"read",
"chunk_size",
"=",
"@idat_chunk_size",
"||",
"@compressed_data",
".",
"size",
"type",
"=",
"'IDAT'",
"until",
"@compressed_data",
".",
"eof?",
"do",
"data",
"=",
"@compressed_data",
".",
"read",
"(",
"chunk_size",
")",
"io",
"<<",
"[",
"data",
".",
"size",
"]",
".",
"pack",
"(",
"'N'",
")",
"io",
"<<",
"type",
"io",
"<<",
"data",
"io",
"<<",
"[",
"Zlib",
".",
"crc32",
"(",
"data",
",",
"Zlib",
".",
"crc32",
"(",
"type",
")",
")",
"]",
".",
"pack",
"(",
"'N'",
")",
"end",
"io",
"<<",
"@tail_data",
".",
"read",
"end",
"end",
"self",
"end"
] |
Save to the +file+.
|
[
"Save",
"to",
"the",
"+",
"file",
"+",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L458-L475
|
18,482
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.wrap_with_rewind
|
def wrap_with_rewind *io, &block
io.each do |i|
i.rewind
end
yield
io.each do |i|
i.rewind
end
end
|
ruby
|
def wrap_with_rewind *io, &block
io.each do |i|
i.rewind
end
yield
io.each do |i|
i.rewind
end
end
|
[
"def",
"wrap_with_rewind",
"*",
"io",
",",
"&",
"block",
"io",
".",
"each",
"do",
"|",
"i",
"|",
"i",
".",
"rewind",
"end",
"yield",
"io",
".",
"each",
"do",
"|",
"i",
"|",
"i",
".",
"rewind",
"end",
"end"
] |
Rewinds given IOs before and after the block.
|
[
"Rewinds",
"given",
"IOs",
"before",
"and",
"after",
"the",
"block",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L488-L496
|
18,483
|
ucnv/pnglitch
|
lib/pnglitch/base.rb
|
PNGlitch.Base.scanline_positions
|
def scanline_positions
scanline_pos = [0]
amount = @filtered_data.size
@interlace_pass_count = []
if self.interlaced?
# Adam7
# Pass 1
v = 1 + (@width / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 2
v = 1 + ((@width - 4) / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 3
v = 1 + (@width / 4.0).ceil * @sample_size
((@height - 4) / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 4
v = 1 + ((@width - 2) / 4.0).ceil * @sample_size
(@height / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 5
v = 1 + (@width / 2.0).ceil * @sample_size
((@height - 2) / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 6
v = 1 + ((@width - 1) / 2.0).ceil * @sample_size
(@height / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 7
v = 1 + @width * @sample_size
((@height - 1) / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
scanline_pos.pop # no need to keep last position
end
loop do
v = scanline_pos.last + (1 + @width * @sample_size)
break if v >= amount
scanline_pos << v
end
scanline_pos
end
|
ruby
|
def scanline_positions
scanline_pos = [0]
amount = @filtered_data.size
@interlace_pass_count = []
if self.interlaced?
# Adam7
# Pass 1
v = 1 + (@width / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 2
v = 1 + ((@width - 4) / 8.0).ceil * @sample_size
(@height / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 3
v = 1 + (@width / 4.0).ceil * @sample_size
((@height - 4) / 8.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 4
v = 1 + ((@width - 2) / 4.0).ceil * @sample_size
(@height / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 5
v = 1 + (@width / 2.0).ceil * @sample_size
((@height - 2) / 4.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 6
v = 1 + ((@width - 1) / 2.0).ceil * @sample_size
(@height / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
@interlace_pass_count << scanline_pos.size
# Pass 7
v = 1 + @width * @sample_size
((@height - 1) / 2.0).ceil.times do
scanline_pos << scanline_pos.last + v
end
scanline_pos.pop # no need to keep last position
end
loop do
v = scanline_pos.last + (1 + @width * @sample_size)
break if v >= amount
scanline_pos << v
end
scanline_pos
end
|
[
"def",
"scanline_positions",
"scanline_pos",
"=",
"[",
"0",
"]",
"amount",
"=",
"@filtered_data",
".",
"size",
"@interlace_pass_count",
"=",
"[",
"]",
"if",
"self",
".",
"interlaced?",
"# Adam7",
"# Pass 1",
"v",
"=",
"1",
"+",
"(",
"@width",
"/",
"8.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"@height",
"/",
"8.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 2",
"v",
"=",
"1",
"+",
"(",
"(",
"@width",
"-",
"4",
")",
"/",
"8.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"@height",
"/",
"8.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 3",
"v",
"=",
"1",
"+",
"(",
"@width",
"/",
"4.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"(",
"@height",
"-",
"4",
")",
"/",
"8.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 4",
"v",
"=",
"1",
"+",
"(",
"(",
"@width",
"-",
"2",
")",
"/",
"4.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"@height",
"/",
"4.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 5",
"v",
"=",
"1",
"+",
"(",
"@width",
"/",
"2.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"(",
"@height",
"-",
"2",
")",
"/",
"4.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 6",
"v",
"=",
"1",
"+",
"(",
"(",
"@width",
"-",
"1",
")",
"/",
"2.0",
")",
".",
"ceil",
"*",
"@sample_size",
"(",
"@height",
"/",
"2.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"@interlace_pass_count",
"<<",
"scanline_pos",
".",
"size",
"# Pass 7",
"v",
"=",
"1",
"+",
"@width",
"*",
"@sample_size",
"(",
"(",
"@height",
"-",
"1",
")",
"/",
"2.0",
")",
".",
"ceil",
".",
"times",
"do",
"scanline_pos",
"<<",
"scanline_pos",
".",
"last",
"+",
"v",
"end",
"scanline_pos",
".",
"pop",
"# no need to keep last position",
"end",
"loop",
"do",
"v",
"=",
"scanline_pos",
".",
"last",
"+",
"(",
"1",
"+",
"@width",
"*",
"@sample_size",
")",
"break",
"if",
"v",
">=",
"amount",
"scanline_pos",
"<<",
"v",
"end",
"scanline_pos",
"end"
] |
Calculate positions of scanlines
|
[
"Calculate",
"positions",
"of",
"scanlines"
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/base.rb#L499-L554
|
18,484
|
ucnv/pnglitch
|
lib/pnglitch/scanline.rb
|
PNGlitch.Scanline.register_filter_encoder
|
def register_filter_encoder encoder = nil, &block
if !encoder.nil? && encoder.is_a?(Proc)
@filter_codec[:encoder] = encoder
elsif block_given?
@filter_codec[:encoder] = block
end
save
end
|
ruby
|
def register_filter_encoder encoder = nil, &block
if !encoder.nil? && encoder.is_a?(Proc)
@filter_codec[:encoder] = encoder
elsif block_given?
@filter_codec[:encoder] = block
end
save
end
|
[
"def",
"register_filter_encoder",
"encoder",
"=",
"nil",
",",
"&",
"block",
"if",
"!",
"encoder",
".",
"nil?",
"&&",
"encoder",
".",
"is_a?",
"(",
"Proc",
")",
"@filter_codec",
"[",
":encoder",
"]",
"=",
"encoder",
"elsif",
"block_given?",
"@filter_codec",
"[",
":encoder",
"]",
"=",
"block",
"end",
"save",
"end"
] |
Registers a custom filter function to encode data.
With this operation, it will be able to change filter encoding behavior despite
the specified filter type value. It takes a Proc object or a block.
|
[
"Registers",
"a",
"custom",
"filter",
"function",
"to",
"encode",
"data",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L97-L104
|
18,485
|
ucnv/pnglitch
|
lib/pnglitch/scanline.rb
|
PNGlitch.Scanline.register_filter_decoder
|
def register_filter_decoder decoder = nil, &block
if !decoder.nil? && decoder.is_a?(Proc)
@filter_codec[:decoder] = decoder
elsif block_given?
@filter_codec[:decoder] = block
end
save
end
|
ruby
|
def register_filter_decoder decoder = nil, &block
if !decoder.nil? && decoder.is_a?(Proc)
@filter_codec[:decoder] = decoder
elsif block_given?
@filter_codec[:decoder] = block
end
save
end
|
[
"def",
"register_filter_decoder",
"decoder",
"=",
"nil",
",",
"&",
"block",
"if",
"!",
"decoder",
".",
"nil?",
"&&",
"decoder",
".",
"is_a?",
"(",
"Proc",
")",
"@filter_codec",
"[",
":decoder",
"]",
"=",
"decoder",
"elsif",
"block_given?",
"@filter_codec",
"[",
":decoder",
"]",
"=",
"block",
"end",
"save",
"end"
] |
Registers a custom filter function to decode data.
With this operation, it will be able to change filter decoding behavior despite
the specified filter type value. It takes a Proc object or a block.
|
[
"Registers",
"a",
"custom",
"filter",
"function",
"to",
"decode",
"data",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L112-L119
|
18,486
|
ucnv/pnglitch
|
lib/pnglitch/scanline.rb
|
PNGlitch.Scanline.save
|
def save
pos = @io.pos
@io.pos = @start_at
@io << [Filter.guess(@filter_type)].pack('C')
@io << self.data.slice(0, @data_size).ljust(@data_size, "\0")
@io.pos = pos
@callback.call(self) unless @callback.nil?
self
end
|
ruby
|
def save
pos = @io.pos
@io.pos = @start_at
@io << [Filter.guess(@filter_type)].pack('C')
@io << self.data.slice(0, @data_size).ljust(@data_size, "\0")
@io.pos = pos
@callback.call(self) unless @callback.nil?
self
end
|
[
"def",
"save",
"pos",
"=",
"@io",
".",
"pos",
"@io",
".",
"pos",
"=",
"@start_at",
"@io",
"<<",
"[",
"Filter",
".",
"guess",
"(",
"@filter_type",
")",
"]",
".",
"pack",
"(",
"'C'",
")",
"@io",
"<<",
"self",
".",
"data",
".",
"slice",
"(",
"0",
",",
"@data_size",
")",
".",
"ljust",
"(",
"@data_size",
",",
"\"\\0\"",
")",
"@io",
".",
"pos",
"=",
"pos",
"@callback",
".",
"call",
"(",
"self",
")",
"unless",
"@callback",
".",
"nil?",
"self",
"end"
] |
Save the changes.
|
[
"Save",
"the",
"changes",
"."
] |
ea4d0801b81343fae9b3e711c022e24b667d5a2a
|
https://github.com/ucnv/pnglitch/blob/ea4d0801b81343fae9b3e711c022e24b667d5a2a/lib/pnglitch/scanline.rb#L124-L132
|
18,487
|
piotrmurach/benchmark-perf
|
lib/benchmark/perf.rb
|
Benchmark.Perf.variance
|
def variance(measurements)
return 0 if measurements.empty?
avg = average(measurements)
total = measurements.reduce(0) do |sum, x|
sum + (x - avg)**2
end
total.to_f / measurements.size
end
|
ruby
|
def variance(measurements)
return 0 if measurements.empty?
avg = average(measurements)
total = measurements.reduce(0) do |sum, x|
sum + (x - avg)**2
end
total.to_f / measurements.size
end
|
[
"def",
"variance",
"(",
"measurements",
")",
"return",
"0",
"if",
"measurements",
".",
"empty?",
"avg",
"=",
"average",
"(",
"measurements",
")",
"total",
"=",
"measurements",
".",
"reduce",
"(",
"0",
")",
"do",
"|",
"sum",
",",
"x",
"|",
"sum",
"+",
"(",
"x",
"-",
"avg",
")",
"**",
"2",
"end",
"total",
".",
"to_f",
"/",
"measurements",
".",
"size",
"end"
] |
Calculate variance of measurements
@param [Array[Float]] measurements
@return [Float]
@api public
|
[
"Calculate",
"variance",
"of",
"measurements"
] |
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
|
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L33-L41
|
18,488
|
piotrmurach/benchmark-perf
|
lib/benchmark/perf.rb
|
Benchmark.Perf.assert_perform_under
|
def assert_perform_under(threshold, options = {}, &work)
actual, _ = ExecutionTime.run(options, &work)
actual <= threshold
end
|
ruby
|
def assert_perform_under(threshold, options = {}, &work)
actual, _ = ExecutionTime.run(options, &work)
actual <= threshold
end
|
[
"def",
"assert_perform_under",
"(",
"threshold",
",",
"options",
"=",
"{",
"}",
",",
"&",
"work",
")",
"actual",
",",
"_",
"=",
"ExecutionTime",
".",
"run",
"(",
"options",
",",
"work",
")",
"actual",
"<=",
"threshold",
"end"
] |
Run given work and gather time statistics
@param [Float] threshold
@return [Boolean]
@api public
|
[
"Run",
"given",
"work",
"and",
"gather",
"time",
"statistics"
] |
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
|
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L63-L66
|
18,489
|
piotrmurach/benchmark-perf
|
lib/benchmark/perf.rb
|
Benchmark.Perf.assert_perform_ips
|
def assert_perform_ips(iterations, options = {}, &work)
mean, stddev, _ = Iteration.run(options, &work)
iterations <= (mean + 3 * stddev)
end
|
ruby
|
def assert_perform_ips(iterations, options = {}, &work)
mean, stddev, _ = Iteration.run(options, &work)
iterations <= (mean + 3 * stddev)
end
|
[
"def",
"assert_perform_ips",
"(",
"iterations",
",",
"options",
"=",
"{",
"}",
",",
"&",
"work",
")",
"mean",
",",
"stddev",
",",
"_",
"=",
"Iteration",
".",
"run",
"(",
"options",
",",
"work",
")",
"iterations",
"<=",
"(",
"mean",
"+",
"3",
"*",
"stddev",
")",
"end"
] |
Assert work is performed within expected iterations per second
@param [Integer] iterations
@return [Boolean]
@api public
|
[
"Assert",
"work",
"is",
"performed",
"within",
"expected",
"iterations",
"per",
"second"
] |
ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e
|
https://github.com/piotrmurach/benchmark-perf/blob/ed17c0a5f10d4fc25e443cc2b4151c54c8c4480e/lib/benchmark/perf.rb#L76-L79
|
18,490
|
zenhob/hcl
|
lib/hcl/app.rb
|
HCl.App.run
|
def run
request_config if @options[:reauth]
if @options[:changelog]
system %[ more "#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}" ]
exit
end
begin
if @command
if command? @command
result = send @command, *@args
if not result.nil?
if result.respond_to? :join, include_all=false
puts result.join(', ')
elsif result.respond_to? :to_s, include_all=false
puts result
end
end
else
puts start(@command, *@args)
end
else
puts show
end
rescue CommandError => e
$stderr.puts e
exit 1
rescue RuntimeError => e
$stderr.puts "Error: #{e}"
exit 1
rescue Faraday::Error => e
$stderr.puts "Connection failed. (#{e.message})"
exit 1
rescue HarvestMiddleware::ThrottleFailure => e
$stderr.puts "Too many requests, retrying in #{e.retry_after+5} seconds..."
sleep e.retry_after+5
run
rescue HarvestMiddleware::AuthFailure => e
$stderr.puts "Unable to authenticate: #{e}"
request_config
run
rescue HarvestMiddleware::Failure => e
$stderr.puts "API failure: #{e}"
exit 1
end
end
|
ruby
|
def run
request_config if @options[:reauth]
if @options[:changelog]
system %[ more "#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}" ]
exit
end
begin
if @command
if command? @command
result = send @command, *@args
if not result.nil?
if result.respond_to? :join, include_all=false
puts result.join(', ')
elsif result.respond_to? :to_s, include_all=false
puts result
end
end
else
puts start(@command, *@args)
end
else
puts show
end
rescue CommandError => e
$stderr.puts e
exit 1
rescue RuntimeError => e
$stderr.puts "Error: #{e}"
exit 1
rescue Faraday::Error => e
$stderr.puts "Connection failed. (#{e.message})"
exit 1
rescue HarvestMiddleware::ThrottleFailure => e
$stderr.puts "Too many requests, retrying in #{e.retry_after+5} seconds..."
sleep e.retry_after+5
run
rescue HarvestMiddleware::AuthFailure => e
$stderr.puts "Unable to authenticate: #{e}"
request_config
run
rescue HarvestMiddleware::Failure => e
$stderr.puts "API failure: #{e}"
exit 1
end
end
|
[
"def",
"run",
"request_config",
"if",
"@options",
"[",
":reauth",
"]",
"if",
"@options",
"[",
":changelog",
"]",
"system",
"%[ more \"#{File.join(File.dirname(__FILE__), '../../CHANGELOG.markdown')}\" ]",
"exit",
"end",
"begin",
"if",
"@command",
"if",
"command?",
"@command",
"result",
"=",
"send",
"@command",
",",
"@args",
"if",
"not",
"result",
".",
"nil?",
"if",
"result",
".",
"respond_to?",
":join",
",",
"include_all",
"=",
"false",
"puts",
"result",
".",
"join",
"(",
"', '",
")",
"elsif",
"result",
".",
"respond_to?",
":to_s",
",",
"include_all",
"=",
"false",
"puts",
"result",
"end",
"end",
"else",
"puts",
"start",
"(",
"@command",
",",
"@args",
")",
"end",
"else",
"puts",
"show",
"end",
"rescue",
"CommandError",
"=>",
"e",
"$stderr",
".",
"puts",
"e",
"exit",
"1",
"rescue",
"RuntimeError",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Error: #{e}\"",
"exit",
"1",
"rescue",
"Faraday",
"::",
"Error",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Connection failed. (#{e.message})\"",
"exit",
"1",
"rescue",
"HarvestMiddleware",
"::",
"ThrottleFailure",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Too many requests, retrying in #{e.retry_after+5} seconds...\"",
"sleep",
"e",
".",
"retry_after",
"+",
"5",
"run",
"rescue",
"HarvestMiddleware",
"::",
"AuthFailure",
"=>",
"e",
"$stderr",
".",
"puts",
"\"Unable to authenticate: #{e}\"",
"request_config",
"run",
"rescue",
"HarvestMiddleware",
"::",
"Failure",
"=>",
"e",
"$stderr",
".",
"puts",
"\"API failure: #{e}\"",
"exit",
"1",
"end",
"end"
] |
Start the application.
|
[
"Start",
"the",
"application",
"."
] |
31a014960b100b2ced9316547a01054fc768d7a9
|
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/app.rb#L40-L84
|
18,491
|
zenhob/hcl
|
lib/hcl/utility.rb
|
HCl.Utility.time2float
|
def time2float time_string
if time_string =~ /:/
hours, minutes = time_string.split(':')
hours.to_f + (minutes.to_f / 60.0)
else
time_string.to_f
end
end
|
ruby
|
def time2float time_string
if time_string =~ /:/
hours, minutes = time_string.split(':')
hours.to_f + (minutes.to_f / 60.0)
else
time_string.to_f
end
end
|
[
"def",
"time2float",
"time_string",
"if",
"time_string",
"=~",
"/",
"/",
"hours",
",",
"minutes",
"=",
"time_string",
".",
"split",
"(",
"':'",
")",
"hours",
".",
"to_f",
"+",
"(",
"minutes",
".",
"to_f",
"/",
"60.0",
")",
"else",
"time_string",
".",
"to_f",
"end",
"end"
] |
Convert from a time span in hour or decimal format to a float.
@param [String] time_string either "M:MM" or decimal
@return [#to_f] converted to a floating-point number
|
[
"Convert",
"from",
"a",
"time",
"span",
"in",
"hour",
"or",
"decimal",
"format",
"to",
"a",
"float",
"."
] |
31a014960b100b2ced9316547a01054fc768d7a9
|
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/utility.rb#L55-L62
|
18,492
|
zenhob/hcl
|
lib/hcl/day_entry.rb
|
HCl.DayEntry.append_note
|
def append_note http, new_notes
# If I don't include hours it gets reset.
# This doens't appear to be the case for task and project.
(self.notes << "\n#{new_notes}").lstrip!
http.post "daily/update/#{id}", notes:notes, hours:hours
end
|
ruby
|
def append_note http, new_notes
# If I don't include hours it gets reset.
# This doens't appear to be the case for task and project.
(self.notes << "\n#{new_notes}").lstrip!
http.post "daily/update/#{id}", notes:notes, hours:hours
end
|
[
"def",
"append_note",
"http",
",",
"new_notes",
"# If I don't include hours it gets reset.",
"# This doens't appear to be the case for task and project.",
"(",
"self",
".",
"notes",
"<<",
"\"\\n#{new_notes}\"",
")",
".",
"lstrip!",
"http",
".",
"post",
"\"daily/update/#{id}\"",
",",
"notes",
":",
"notes",
",",
"hours",
":",
"hours",
"end"
] |
Append a string to the notes for this task.
|
[
"Append",
"a",
"string",
"to",
"the",
"notes",
"for",
"this",
"task",
"."
] |
31a014960b100b2ced9316547a01054fc768d7a9
|
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/day_entry.rb#L32-L37
|
18,493
|
zenhob/hcl
|
lib/hcl/commands.rb
|
HCl.Commands.status
|
def status
result = Faraday.new("http://kccljmymlslr.statuspage.io/api/v2") do |f|
f.adapter Faraday.default_adapter
end.get('status.json').body
json = Yajl::Parser.parse result, symbolize_keys: true
status = json[:status][:description]
updated_at = DateTime.parse(json[:page][:updated_at]).strftime "%F %T %:z"
"#{status} [#{updated_at}]"
end
|
ruby
|
def status
result = Faraday.new("http://kccljmymlslr.statuspage.io/api/v2") do |f|
f.adapter Faraday.default_adapter
end.get('status.json').body
json = Yajl::Parser.parse result, symbolize_keys: true
status = json[:status][:description]
updated_at = DateTime.parse(json[:page][:updated_at]).strftime "%F %T %:z"
"#{status} [#{updated_at}]"
end
|
[
"def",
"status",
"result",
"=",
"Faraday",
".",
"new",
"(",
"\"http://kccljmymlslr.statuspage.io/api/v2\"",
")",
"do",
"|",
"f",
"|",
"f",
".",
"adapter",
"Faraday",
".",
"default_adapter",
"end",
".",
"get",
"(",
"'status.json'",
")",
".",
"body",
"json",
"=",
"Yajl",
"::",
"Parser",
".",
"parse",
"result",
",",
"symbolize_keys",
":",
"true",
"status",
"=",
"json",
"[",
":status",
"]",
"[",
":description",
"]",
"updated_at",
"=",
"DateTime",
".",
"parse",
"(",
"json",
"[",
":page",
"]",
"[",
":updated_at",
"]",
")",
".",
"strftime",
"\"%F %T %:z\"",
"\"#{status} [#{updated_at}]\"",
"end"
] |
Show the network status of the Harvest service.
|
[
"Show",
"the",
"network",
"status",
"of",
"the",
"Harvest",
"service",
"."
] |
31a014960b100b2ced9316547a01054fc768d7a9
|
https://github.com/zenhob/hcl/blob/31a014960b100b2ced9316547a01054fc768d7a9/lib/hcl/commands.rb#L14-L24
|
18,494
|
sosedoff/goodreads
|
lib/goodreads/client/shelves.rb
|
Goodreads.Shelves.shelves
|
def shelves(user_id, options = {})
options = options.merge(user_id: user_id, v: 2)
data = request("/shelf/list.xml", options)
shelves = data["shelves"]
shelves = data["shelves"]["user_shelf"].map do |s|
Hashie::Mash.new({
id: s["id"],
name: s["name"],
book_count: s["book_count"],
exclusive: s["exclusive_flag"],
description: s["description"],
sort: s["sort"],
order: s["order"],
per_page: s["per_page"],
display_fields: s["display_fields"],
featured: s["featured"],
recommend_for: s["recommend_for"],
sticky: s["sticky"],
})
end
Hashie::Mash.new(
start: data["shelves"]["start"].to_i,
end: data["shelves"]["end"].to_i,
total: data["shelves"]["total"].to_i,
shelves: shelves
)
end
|
ruby
|
def shelves(user_id, options = {})
options = options.merge(user_id: user_id, v: 2)
data = request("/shelf/list.xml", options)
shelves = data["shelves"]
shelves = data["shelves"]["user_shelf"].map do |s|
Hashie::Mash.new({
id: s["id"],
name: s["name"],
book_count: s["book_count"],
exclusive: s["exclusive_flag"],
description: s["description"],
sort: s["sort"],
order: s["order"],
per_page: s["per_page"],
display_fields: s["display_fields"],
featured: s["featured"],
recommend_for: s["recommend_for"],
sticky: s["sticky"],
})
end
Hashie::Mash.new(
start: data["shelves"]["start"].to_i,
end: data["shelves"]["end"].to_i,
total: data["shelves"]["total"].to_i,
shelves: shelves
)
end
|
[
"def",
"shelves",
"(",
"user_id",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"merge",
"(",
"user_id",
":",
"user_id",
",",
"v",
":",
"2",
")",
"data",
"=",
"request",
"(",
"\"/shelf/list.xml\"",
",",
"options",
")",
"shelves",
"=",
"data",
"[",
"\"shelves\"",
"]",
"shelves",
"=",
"data",
"[",
"\"shelves\"",
"]",
"[",
"\"user_shelf\"",
"]",
".",
"map",
"do",
"|",
"s",
"|",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"{",
"id",
":",
"s",
"[",
"\"id\"",
"]",
",",
"name",
":",
"s",
"[",
"\"name\"",
"]",
",",
"book_count",
":",
"s",
"[",
"\"book_count\"",
"]",
",",
"exclusive",
":",
"s",
"[",
"\"exclusive_flag\"",
"]",
",",
"description",
":",
"s",
"[",
"\"description\"",
"]",
",",
"sort",
":",
"s",
"[",
"\"sort\"",
"]",
",",
"order",
":",
"s",
"[",
"\"order\"",
"]",
",",
"per_page",
":",
"s",
"[",
"\"per_page\"",
"]",
",",
"display_fields",
":",
"s",
"[",
"\"display_fields\"",
"]",
",",
"featured",
":",
"s",
"[",
"\"featured\"",
"]",
",",
"recommend_for",
":",
"s",
"[",
"\"recommend_for\"",
"]",
",",
"sticky",
":",
"s",
"[",
"\"sticky\"",
"]",
",",
"}",
")",
"end",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"start",
":",
"data",
"[",
"\"shelves\"",
"]",
"[",
"\"start\"",
"]",
".",
"to_i",
",",
"end",
":",
"data",
"[",
"\"shelves\"",
"]",
"[",
"\"end\"",
"]",
".",
"to_i",
",",
"total",
":",
"data",
"[",
"\"shelves\"",
"]",
"[",
"\"total\"",
"]",
".",
"to_i",
",",
"shelves",
":",
"shelves",
")",
"end"
] |
Lists shelves for a user
|
[
"Lists",
"shelves",
"for",
"a",
"user"
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L4-L32
|
18,495
|
sosedoff/goodreads
|
lib/goodreads/client/shelves.rb
|
Goodreads.Shelves.shelf
|
def shelf(user_id, shelf_name, options = {})
options = options.merge(shelf: shelf_name, v: 2)
data = request("/review/list/#{user_id}.xml", options)
reviews = data["reviews"]["review"]
books = []
unless reviews.nil?
# one-book results come back as a single hash
reviews = [reviews] unless reviews.instance_of?(Array)
books = reviews.map { |e| Hashie::Mash.new(e) }
end
Hashie::Mash.new(
start: data["reviews"]["start"].to_i,
end: data["reviews"]["end"].to_i,
total: data["reviews"]["total"].to_i,
books: books
)
end
|
ruby
|
def shelf(user_id, shelf_name, options = {})
options = options.merge(shelf: shelf_name, v: 2)
data = request("/review/list/#{user_id}.xml", options)
reviews = data["reviews"]["review"]
books = []
unless reviews.nil?
# one-book results come back as a single hash
reviews = [reviews] unless reviews.instance_of?(Array)
books = reviews.map { |e| Hashie::Mash.new(e) }
end
Hashie::Mash.new(
start: data["reviews"]["start"].to_i,
end: data["reviews"]["end"].to_i,
total: data["reviews"]["total"].to_i,
books: books
)
end
|
[
"def",
"shelf",
"(",
"user_id",
",",
"shelf_name",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"merge",
"(",
"shelf",
":",
"shelf_name",
",",
"v",
":",
"2",
")",
"data",
"=",
"request",
"(",
"\"/review/list/#{user_id}.xml\"",
",",
"options",
")",
"reviews",
"=",
"data",
"[",
"\"reviews\"",
"]",
"[",
"\"review\"",
"]",
"books",
"=",
"[",
"]",
"unless",
"reviews",
".",
"nil?",
"# one-book results come back as a single hash",
"reviews",
"=",
"[",
"reviews",
"]",
"unless",
"reviews",
".",
"instance_of?",
"(",
"Array",
")",
"books",
"=",
"reviews",
".",
"map",
"{",
"|",
"e",
"|",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"e",
")",
"}",
"end",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"start",
":",
"data",
"[",
"\"reviews\"",
"]",
"[",
"\"start\"",
"]",
".",
"to_i",
",",
"end",
":",
"data",
"[",
"\"reviews\"",
"]",
"[",
"\"end\"",
"]",
".",
"to_i",
",",
"total",
":",
"data",
"[",
"\"reviews\"",
"]",
"[",
"\"total\"",
"]",
".",
"to_i",
",",
"books",
":",
"books",
")",
"end"
] |
Get books from a user's shelf
|
[
"Get",
"books",
"from",
"a",
"user",
"s",
"shelf"
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L35-L53
|
18,496
|
sosedoff/goodreads
|
lib/goodreads/client/shelves.rb
|
Goodreads.Shelves.add_to_shelf
|
def add_to_shelf(book_id, shelf_name, options = {})
options = options.merge(book_id: book_id, name: shelf_name, v: 2)
data = oauth_request_method(:post, "/shelf/add_to_shelf.xml", options)
# when a book is on a single shelf it is a single hash
shelves = data["my_review"]["shelves"]["shelf"]
shelves = [shelves] unless shelves.instance_of?(Array)
shelves = shelves.map do |s|
Hashie::Mash.new({
id: s["id"].to_i,
name: s["name"],
exclusive: s["exclusive"] == "true",
sortable: s["sortable"] == "true",
})
end
Hashie::Mash.new(
id: data["my_review"]["id"].to_i,
book_id: data["my_review"]["book_id"].to_i,
rating: data["my_review"]["rating"].to_i,
body: data["my_review"]["body"],
body_raw: data["my_review"]["body_raw"],
spoiler: data["my_review"]["spoiler_flag"] == "true",
shelves: shelves,
read_at: data["my_review"]["read_at"],
started_at: data["my_review"]["started_at"],
date_added: data["my_review"]["date_added"],
updated_at: data["my_review"]["updated_at"],
)
end
|
ruby
|
def add_to_shelf(book_id, shelf_name, options = {})
options = options.merge(book_id: book_id, name: shelf_name, v: 2)
data = oauth_request_method(:post, "/shelf/add_to_shelf.xml", options)
# when a book is on a single shelf it is a single hash
shelves = data["my_review"]["shelves"]["shelf"]
shelves = [shelves] unless shelves.instance_of?(Array)
shelves = shelves.map do |s|
Hashie::Mash.new({
id: s["id"].to_i,
name: s["name"],
exclusive: s["exclusive"] == "true",
sortable: s["sortable"] == "true",
})
end
Hashie::Mash.new(
id: data["my_review"]["id"].to_i,
book_id: data["my_review"]["book_id"].to_i,
rating: data["my_review"]["rating"].to_i,
body: data["my_review"]["body"],
body_raw: data["my_review"]["body_raw"],
spoiler: data["my_review"]["spoiler_flag"] == "true",
shelves: shelves,
read_at: data["my_review"]["read_at"],
started_at: data["my_review"]["started_at"],
date_added: data["my_review"]["date_added"],
updated_at: data["my_review"]["updated_at"],
)
end
|
[
"def",
"add_to_shelf",
"(",
"book_id",
",",
"shelf_name",
",",
"options",
"=",
"{",
"}",
")",
"options",
"=",
"options",
".",
"merge",
"(",
"book_id",
":",
"book_id",
",",
"name",
":",
"shelf_name",
",",
"v",
":",
"2",
")",
"data",
"=",
"oauth_request_method",
"(",
":post",
",",
"\"/shelf/add_to_shelf.xml\"",
",",
"options",
")",
"# when a book is on a single shelf it is a single hash",
"shelves",
"=",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"shelves\"",
"]",
"[",
"\"shelf\"",
"]",
"shelves",
"=",
"[",
"shelves",
"]",
"unless",
"shelves",
".",
"instance_of?",
"(",
"Array",
")",
"shelves",
"=",
"shelves",
".",
"map",
"do",
"|",
"s",
"|",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"{",
"id",
":",
"s",
"[",
"\"id\"",
"]",
".",
"to_i",
",",
"name",
":",
"s",
"[",
"\"name\"",
"]",
",",
"exclusive",
":",
"s",
"[",
"\"exclusive\"",
"]",
"==",
"\"true\"",
",",
"sortable",
":",
"s",
"[",
"\"sortable\"",
"]",
"==",
"\"true\"",
",",
"}",
")",
"end",
"Hashie",
"::",
"Mash",
".",
"new",
"(",
"id",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"id\"",
"]",
".",
"to_i",
",",
"book_id",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"book_id\"",
"]",
".",
"to_i",
",",
"rating",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"rating\"",
"]",
".",
"to_i",
",",
"body",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"body\"",
"]",
",",
"body_raw",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"body_raw\"",
"]",
",",
"spoiler",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"spoiler_flag\"",
"]",
"==",
"\"true\"",
",",
"shelves",
":",
"shelves",
",",
"read_at",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"read_at\"",
"]",
",",
"started_at",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"started_at\"",
"]",
",",
"date_added",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"date_added\"",
"]",
",",
"updated_at",
":",
"data",
"[",
"\"my_review\"",
"]",
"[",
"\"updated_at\"",
"]",
",",
")",
"end"
] |
Add book to a user's shelf
Returns the user's review for the book, which includes all its current shelves
|
[
"Add",
"book",
"to",
"a",
"user",
"s",
"shelf"
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/client/shelves.rb#L58-L90
|
18,497
|
sosedoff/goodreads
|
lib/goodreads/request.rb
|
Goodreads.Request.request
|
def request(path, params = {})
if oauth_configured?
oauth_request(path, params)
else
http_request(path, params)
end
end
|
ruby
|
def request(path, params = {})
if oauth_configured?
oauth_request(path, params)
else
http_request(path, params)
end
end
|
[
"def",
"request",
"(",
"path",
",",
"params",
"=",
"{",
"}",
")",
"if",
"oauth_configured?",
"oauth_request",
"(",
"path",
",",
"params",
")",
"else",
"http_request",
"(",
"path",
",",
"params",
")",
"end",
"end"
] |
Perform an API request using API key or OAuth token
path - Request path
params - Parameters hash
Will make a request with the configured API key (application
authentication) or OAuth token (user authentication) if available.
|
[
"Perform",
"an",
"API",
"request",
"using",
"API",
"key",
"or",
"OAuth",
"token"
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L19-L25
|
18,498
|
sosedoff/goodreads
|
lib/goodreads/request.rb
|
Goodreads.Request.http_request
|
def http_request(path, params)
token = api_key || Goodreads.configuration[:api_key]
fail(Goodreads::ConfigurationError, "API key required.") if token.nil?
params.merge!(format: API_FORMAT, key: token)
url = "#{API_URL}#{path}"
resp = RestClient.get(url, params: params) do |response, request, result, &block|
case response.code
when 200
response.return!(&block)
when 401
fail(Goodreads::Unauthorized)
when 403
fail(Goodreads::Forbidden)
when 404
fail(Goodreads::NotFound)
end
end
parse(resp)
end
|
ruby
|
def http_request(path, params)
token = api_key || Goodreads.configuration[:api_key]
fail(Goodreads::ConfigurationError, "API key required.") if token.nil?
params.merge!(format: API_FORMAT, key: token)
url = "#{API_URL}#{path}"
resp = RestClient.get(url, params: params) do |response, request, result, &block|
case response.code
when 200
response.return!(&block)
when 401
fail(Goodreads::Unauthorized)
when 403
fail(Goodreads::Forbidden)
when 404
fail(Goodreads::NotFound)
end
end
parse(resp)
end
|
[
"def",
"http_request",
"(",
"path",
",",
"params",
")",
"token",
"=",
"api_key",
"||",
"Goodreads",
".",
"configuration",
"[",
":api_key",
"]",
"fail",
"(",
"Goodreads",
"::",
"ConfigurationError",
",",
"\"API key required.\"",
")",
"if",
"token",
".",
"nil?",
"params",
".",
"merge!",
"(",
"format",
":",
"API_FORMAT",
",",
"key",
":",
"token",
")",
"url",
"=",
"\"#{API_URL}#{path}\"",
"resp",
"=",
"RestClient",
".",
"get",
"(",
"url",
",",
"params",
":",
"params",
")",
"do",
"|",
"response",
",",
"request",
",",
"result",
",",
"&",
"block",
"|",
"case",
"response",
".",
"code",
"when",
"200",
"response",
".",
"return!",
"(",
"block",
")",
"when",
"401",
"fail",
"(",
"Goodreads",
"::",
"Unauthorized",
")",
"when",
"403",
"fail",
"(",
"Goodreads",
"::",
"Forbidden",
")",
"when",
"404",
"fail",
"(",
"Goodreads",
"::",
"NotFound",
")",
"end",
"end",
"parse",
"(",
"resp",
")",
"end"
] |
Perform an API request using API key
path - Request path
params - Parameters hash
|
[
"Perform",
"an",
"API",
"request",
"using",
"API",
"key"
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L31-L53
|
18,499
|
sosedoff/goodreads
|
lib/goodreads/request.rb
|
Goodreads.Request.oauth_request_method
|
def oauth_request_method(http_method, path, params = {})
fail "OAuth access token required!" unless @oauth_token
headers = { "Accept" => "application/xml" }
resp = if http_method == :get || http_method == :delete
if params
url_params = params.map { |k, v| "#{k}=#{v}" }.join("&")
path = "#{path}?#{url_params}"
end
@oauth_token.request(http_method, path, headers)
else
@oauth_token.request(http_method, path, params || {}, headers)
end
case resp
when Net::HTTPUnauthorized
fail Goodreads::Unauthorized
when Net::HTTPNotFound
fail Goodreads::NotFound
end
parse(resp)
end
|
ruby
|
def oauth_request_method(http_method, path, params = {})
fail "OAuth access token required!" unless @oauth_token
headers = { "Accept" => "application/xml" }
resp = if http_method == :get || http_method == :delete
if params
url_params = params.map { |k, v| "#{k}=#{v}" }.join("&")
path = "#{path}?#{url_params}"
end
@oauth_token.request(http_method, path, headers)
else
@oauth_token.request(http_method, path, params || {}, headers)
end
case resp
when Net::HTTPUnauthorized
fail Goodreads::Unauthorized
when Net::HTTPNotFound
fail Goodreads::NotFound
end
parse(resp)
end
|
[
"def",
"oauth_request_method",
"(",
"http_method",
",",
"path",
",",
"params",
"=",
"{",
"}",
")",
"fail",
"\"OAuth access token required!\"",
"unless",
"@oauth_token",
"headers",
"=",
"{",
"\"Accept\"",
"=>",
"\"application/xml\"",
"}",
"resp",
"=",
"if",
"http_method",
"==",
":get",
"||",
"http_method",
"==",
":delete",
"if",
"params",
"url_params",
"=",
"params",
".",
"map",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k}=#{v}\"",
"}",
".",
"join",
"(",
"\"&\"",
")",
"path",
"=",
"\"#{path}?#{url_params}\"",
"end",
"@oauth_token",
".",
"request",
"(",
"http_method",
",",
"path",
",",
"headers",
")",
"else",
"@oauth_token",
".",
"request",
"(",
"http_method",
",",
"path",
",",
"params",
"||",
"{",
"}",
",",
"headers",
")",
"end",
"case",
"resp",
"when",
"Net",
"::",
"HTTPUnauthorized",
"fail",
"Goodreads",
"::",
"Unauthorized",
"when",
"Net",
"::",
"HTTPNotFound",
"fail",
"Goodreads",
"::",
"NotFound",
"end",
"parse",
"(",
"resp",
")",
"end"
] |
Perform an OAuth API request. Goodreads must have been initialized with a valid OAuth access token.
http_method - HTTP verb supported by OAuth gem (one of :get, :post, :delete, etc.)
path - Request path
params - Parameters hash
|
[
"Perform",
"an",
"OAuth",
"API",
"request",
".",
"Goodreads",
"must",
"have",
"been",
"initialized",
"with",
"a",
"valid",
"OAuth",
"access",
"token",
"."
] |
aa571069ab07190c93b8a8aff77e1da2c79ab694
|
https://github.com/sosedoff/goodreads/blob/aa571069ab07190c93b8a8aff77e1da2c79ab694/lib/goodreads/request.rb#L70-L93
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.