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
sequence | docstring
stringlengths 8
16k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 94
266
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
voltrb/volt | lib/volt/models/model_hash_behaviour.rb | Volt.ModelHashBehaviour.to_h | def to_h
@size_dep.depend
if @attributes.nil?
nil
else
hash = {}
@attributes.each_pair do |key, value|
hash[key] = deep_unwrap(value)
end
hash
end
end | ruby | def to_h
@size_dep.depend
if @attributes.nil?
nil
else
hash = {}
@attributes.each_pair do |key, value|
hash[key] = deep_unwrap(value)
end
hash
end
end | [
"def",
"to_h",
"@size_dep",
".",
"depend",
"if",
"@attributes",
".",
"nil?",
"nil",
"else",
"hash",
"=",
"{",
"}",
"@attributes",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"hash",
"[",
"key",
"]",
"=",
"deep_unwrap",
"(",
"value",
")",
"end",
"hash",
"end",
"end"
] | Convert the model to a hash all of the way down. | [
"Convert",
"the",
"model",
"to",
"a",
"hash",
"all",
"of",
"the",
"way",
"down",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model_hash_behaviour.rb#L80-L92 | train |
voltrb/volt | lib/volt/models/array_model.rb | Volt.ArrayModel.to_a | def to_a
@size_dep.depend
array = []
Volt.run_in_mode(:no_model_promises) do
attributes.size.times do |index|
array << deep_unwrap(self[index])
end
end
array
end | ruby | def to_a
@size_dep.depend
array = []
Volt.run_in_mode(:no_model_promises) do
attributes.size.times do |index|
array << deep_unwrap(self[index])
end
end
array
end | [
"def",
"to_a",
"@size_dep",
".",
"depend",
"array",
"=",
"[",
"]",
"Volt",
".",
"run_in_mode",
"(",
":no_model_promises",
")",
"do",
"attributes",
".",
"size",
".",
"times",
"do",
"|",
"index",
"|",
"array",
"<<",
"deep_unwrap",
"(",
"self",
"[",
"index",
"]",
")",
"end",
"end",
"array",
"end"
] | Convert the model to an array all of the way down | [
"Convert",
"the",
"model",
"to",
"an",
"array",
"all",
"of",
"the",
"way",
"down"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/array_model.rb#L251-L260 | train |
voltrb/volt | lib/volt/models/array_model.rb | Volt.ArrayModel.create_new_model | def create_new_model(model, from_method)
if model.is_a?(Model)
if model.buffer?
fail "The #{from_method} does not take a buffer. Call .save! on buffer's to persist them."
end
# Set the new path and the persistor.
model.options = @options.merge(parent: self, path: @options[:path] + [:[]])
else
model = wrap_values([model]).first
end
if model.is_a?(Model)
promise = model.can_create?.then do |can_create|
unless can_create
fail "permissions did not allow create for #{model.inspect}"
end
end.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end.then do
nil.then do
# Validate and save
model.run_changed
end.then do
# Mark the model as not new
model.instance_variable_set('@new', false)
# Mark the model as loaded
model.change_state_to(:loaded_state, :loaded)
end.fail do |err|
# remove from the collection because it failed to save on the server
# we don't need to call delete on the server.
index = @array.index(model)
delete_at(index, true)
# remove from the id list
@persistor.try(:remove_tracking_id, model)
# re-raise, err might not be an Error object, so we use a rejected promise to re-raise
Promise.new.reject(err)
end
end
else
promise = nil.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end
end
promise = promise.then do
# resolve the model
model
end
# unwrap the promise if the persistor is synchronus.
# This will return the value or raise the exception.
promise = promise.unwrap unless @persistor.async?
# return
promise
end | ruby | def create_new_model(model, from_method)
if model.is_a?(Model)
if model.buffer?
fail "The #{from_method} does not take a buffer. Call .save! on buffer's to persist them."
end
# Set the new path and the persistor.
model.options = @options.merge(parent: self, path: @options[:path] + [:[]])
else
model = wrap_values([model]).first
end
if model.is_a?(Model)
promise = model.can_create?.then do |can_create|
unless can_create
fail "permissions did not allow create for #{model.inspect}"
end
end.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end.then do
nil.then do
# Validate and save
model.run_changed
end.then do
# Mark the model as not new
model.instance_variable_set('@new', false)
# Mark the model as loaded
model.change_state_to(:loaded_state, :loaded)
end.fail do |err|
# remove from the collection because it failed to save on the server
# we don't need to call delete on the server.
index = @array.index(model)
delete_at(index, true)
# remove from the id list
@persistor.try(:remove_tracking_id, model)
# re-raise, err might not be an Error object, so we use a rejected promise to re-raise
Promise.new.reject(err)
end
end
else
promise = nil.then do
# Add it to the array and trigger any watches or on events.
reactive_array_append(model)
@persistor.added(model, @array.size - 1)
end
end
promise = promise.then do
# resolve the model
model
end
# unwrap the promise if the persistor is synchronus.
# This will return the value or raise the exception.
promise = promise.unwrap unless @persistor.async?
# return
promise
end | [
"def",
"create_new_model",
"(",
"model",
",",
"from_method",
")",
"if",
"model",
".",
"is_a?",
"(",
"Model",
")",
"if",
"model",
".",
"buffer?",
"fail",
"\"The #{from_method} does not take a buffer. Call .save! on buffer's to persist them.\"",
"end",
"# Set the new path and the persistor.",
"model",
".",
"options",
"=",
"@options",
".",
"merge",
"(",
"parent",
":",
"self",
",",
"path",
":",
"@options",
"[",
":path",
"]",
"+",
"[",
":[]",
"]",
")",
"else",
"model",
"=",
"wrap_values",
"(",
"[",
"model",
"]",
")",
".",
"first",
"end",
"if",
"model",
".",
"is_a?",
"(",
"Model",
")",
"promise",
"=",
"model",
".",
"can_create?",
".",
"then",
"do",
"|",
"can_create",
"|",
"unless",
"can_create",
"fail",
"\"permissions did not allow create for #{model.inspect}\"",
"end",
"end",
".",
"then",
"do",
"# Add it to the array and trigger any watches or on events.",
"reactive_array_append",
"(",
"model",
")",
"@persistor",
".",
"added",
"(",
"model",
",",
"@array",
".",
"size",
"-",
"1",
")",
"end",
".",
"then",
"do",
"nil",
".",
"then",
"do",
"# Validate and save",
"model",
".",
"run_changed",
"end",
".",
"then",
"do",
"# Mark the model as not new",
"model",
".",
"instance_variable_set",
"(",
"'@new'",
",",
"false",
")",
"# Mark the model as loaded",
"model",
".",
"change_state_to",
"(",
":loaded_state",
",",
":loaded",
")",
"end",
".",
"fail",
"do",
"|",
"err",
"|",
"# remove from the collection because it failed to save on the server",
"# we don't need to call delete on the server.",
"index",
"=",
"@array",
".",
"index",
"(",
"model",
")",
"delete_at",
"(",
"index",
",",
"true",
")",
"# remove from the id list",
"@persistor",
".",
"try",
"(",
":remove_tracking_id",
",",
"model",
")",
"# re-raise, err might not be an Error object, so we use a rejected promise to re-raise",
"Promise",
".",
"new",
".",
"reject",
"(",
"err",
")",
"end",
"end",
"else",
"promise",
"=",
"nil",
".",
"then",
"do",
"# Add it to the array and trigger any watches or on events.",
"reactive_array_append",
"(",
"model",
")",
"@persistor",
".",
"added",
"(",
"model",
",",
"@array",
".",
"size",
"-",
"1",
")",
"end",
"end",
"promise",
"=",
"promise",
".",
"then",
"do",
"# resolve the model",
"model",
"end",
"# unwrap the promise if the persistor is synchronus.",
"# This will return the value or raise the exception.",
"promise",
"=",
"promise",
".",
"unwrap",
"unless",
"@persistor",
".",
"async?",
"# return",
"promise",
"end"
] | called form <<, append, and create. If a hash is passed in, it converts
it to a model. Then it takes the model and inserts it into the ArrayModel
then persists it. | [
"called",
"form",
"<<",
"append",
"and",
"create",
".",
"If",
"a",
"hash",
"is",
"passed",
"in",
"it",
"converts",
"it",
"to",
"a",
"model",
".",
"Then",
"it",
"takes",
"the",
"model",
"and",
"inserts",
"it",
"into",
"the",
"ArrayModel",
"then",
"persists",
"it",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/array_model.rb#L319-L387 | train |
voltrb/volt | lib/volt/models/url.rb | Volt.URL.url_for | def url_for(params)
host_with_port = host || location.host
host_with_port += ":#{port}" if port && port != 80
scheme = scheme || location.scheme
unless RUBY_PLATFORM == 'opal'
# lazy load routes and views on the server
if !@router && @routes_loader
# Load the templates
@routes_loader.call
end
end
path, params = @router.params_to_url(params)
if path == nil
raise "No route matched, make sure you have the base route defined last: `client '/', {}`"
end
new_url = "#{scheme}://#{host_with_port}#{path.chomp('/')}"
# Add query params
params_str = ''
unless params.empty?
query_parts = []
nested_params_hash(params).each_pair do |key, value|
# remove the _ from the front
value = Volt::Parsing.encodeURI(value)
query_parts << "#{key}=#{value}"
end
if query_parts.size > 0
query = query_parts.join('&')
new_url += "?#{query}"
end
end
# Add fragment
frag = fragment
new_url += '#' + frag if frag.present?
new_url
end | ruby | def url_for(params)
host_with_port = host || location.host
host_with_port += ":#{port}" if port && port != 80
scheme = scheme || location.scheme
unless RUBY_PLATFORM == 'opal'
# lazy load routes and views on the server
if !@router && @routes_loader
# Load the templates
@routes_loader.call
end
end
path, params = @router.params_to_url(params)
if path == nil
raise "No route matched, make sure you have the base route defined last: `client '/', {}`"
end
new_url = "#{scheme}://#{host_with_port}#{path.chomp('/')}"
# Add query params
params_str = ''
unless params.empty?
query_parts = []
nested_params_hash(params).each_pair do |key, value|
# remove the _ from the front
value = Volt::Parsing.encodeURI(value)
query_parts << "#{key}=#{value}"
end
if query_parts.size > 0
query = query_parts.join('&')
new_url += "?#{query}"
end
end
# Add fragment
frag = fragment
new_url += '#' + frag if frag.present?
new_url
end | [
"def",
"url_for",
"(",
"params",
")",
"host_with_port",
"=",
"host",
"||",
"location",
".",
"host",
"host_with_port",
"+=",
"\":#{port}\"",
"if",
"port",
"&&",
"port",
"!=",
"80",
"scheme",
"=",
"scheme",
"||",
"location",
".",
"scheme",
"unless",
"RUBY_PLATFORM",
"==",
"'opal'",
"# lazy load routes and views on the server",
"if",
"!",
"@router",
"&&",
"@routes_loader",
"# Load the templates",
"@routes_loader",
".",
"call",
"end",
"end",
"path",
",",
"params",
"=",
"@router",
".",
"params_to_url",
"(",
"params",
")",
"if",
"path",
"==",
"nil",
"raise",
"\"No route matched, make sure you have the base route defined last: `client '/', {}`\"",
"end",
"new_url",
"=",
"\"#{scheme}://#{host_with_port}#{path.chomp('/')}\"",
"# Add query params",
"params_str",
"=",
"''",
"unless",
"params",
".",
"empty?",
"query_parts",
"=",
"[",
"]",
"nested_params_hash",
"(",
"params",
")",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"# remove the _ from the front",
"value",
"=",
"Volt",
"::",
"Parsing",
".",
"encodeURI",
"(",
"value",
")",
"query_parts",
"<<",
"\"#{key}=#{value}\"",
"end",
"if",
"query_parts",
".",
"size",
">",
"0",
"query",
"=",
"query_parts",
".",
"join",
"(",
"'&'",
")",
"new_url",
"+=",
"\"?#{query}\"",
"end",
"end",
"# Add fragment",
"frag",
"=",
"fragment",
"new_url",
"+=",
"'#'",
"+",
"frag",
"if",
"frag",
".",
"present?",
"new_url",
"end"
] | Full url rebuilds the url from it's constituent parts.
The params passed in are used to generate the urls. | [
"Full",
"url",
"rebuilds",
"the",
"url",
"from",
"it",
"s",
"constituent",
"parts",
".",
"The",
"params",
"passed",
"in",
"are",
"used",
"to",
"generate",
"the",
"urls",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/url.rb#L72-L114 | train |
voltrb/volt | lib/volt/models/url.rb | Volt.URL.assign_query_hash_to_params | def assign_query_hash_to_params
# Get a nested hash representing the current url params.
query_hash = parse_query
# Get the params that are in the route
new_params = @router.url_to_params(path)
fail "no routes match path: #{path}" if new_params == false
return false if new_params == nil
query_hash.merge!(new_params)
# Loop through the .params we already have assigned.
lparams = params
assign_from_old(lparams, query_hash)
assign_new(lparams, query_hash)
true
end | ruby | def assign_query_hash_to_params
# Get a nested hash representing the current url params.
query_hash = parse_query
# Get the params that are in the route
new_params = @router.url_to_params(path)
fail "no routes match path: #{path}" if new_params == false
return false if new_params == nil
query_hash.merge!(new_params)
# Loop through the .params we already have assigned.
lparams = params
assign_from_old(lparams, query_hash)
assign_new(lparams, query_hash)
true
end | [
"def",
"assign_query_hash_to_params",
"# Get a nested hash representing the current url params.",
"query_hash",
"=",
"parse_query",
"# Get the params that are in the route",
"new_params",
"=",
"@router",
".",
"url_to_params",
"(",
"path",
")",
"fail",
"\"no routes match path: #{path}\"",
"if",
"new_params",
"==",
"false",
"return",
"false",
"if",
"new_params",
"==",
"nil",
"query_hash",
".",
"merge!",
"(",
"new_params",
")",
"# Loop through the .params we already have assigned.",
"lparams",
"=",
"params",
"assign_from_old",
"(",
"lparams",
",",
"query_hash",
")",
"assign_new",
"(",
"lparams",
",",
"query_hash",
")",
"true",
"end"
] | Assigning the params is tricky since we don't want to trigger changed on
any values that have not changed. So we first loop through all current
url params, removing any not present in the params, while also removing
them from the list of new params as added. Then we loop through the
remaining new parameters and assign them. | [
"Assigning",
"the",
"params",
"is",
"tricky",
"since",
"we",
"don",
"t",
"want",
"to",
"trigger",
"changed",
"on",
"any",
"values",
"that",
"have",
"not",
"changed",
".",
"So",
"we",
"first",
"loop",
"through",
"all",
"current",
"url",
"params",
"removing",
"any",
"not",
"present",
"in",
"the",
"params",
"while",
"also",
"removing",
"them",
"from",
"the",
"list",
"of",
"new",
"params",
"as",
"added",
".",
"Then",
"we",
"loop",
"through",
"the",
"remaining",
"new",
"parameters",
"and",
"assign",
"them",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/url.rb#L173-L192 | train |
voltrb/volt | lib/volt/models/url.rb | Volt.URL.assign_new | def assign_new(params, new_params)
new_params.each_pair do |name, value|
if value.is_a?(Hash)
assign_new(params.get(name), value)
else
# assign
params.set(name, value)
end
end
end | ruby | def assign_new(params, new_params)
new_params.each_pair do |name, value|
if value.is_a?(Hash)
assign_new(params.get(name), value)
else
# assign
params.set(name, value)
end
end
end | [
"def",
"assign_new",
"(",
"params",
",",
"new_params",
")",
"new_params",
".",
"each_pair",
"do",
"|",
"name",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"assign_new",
"(",
"params",
".",
"get",
"(",
"name",
")",
",",
"value",
")",
"else",
"# assign",
"params",
".",
"set",
"(",
"name",
",",
"value",
")",
"end",
"end",
"end"
] | Assign any new params, which weren't in the old params. | [
"Assign",
"any",
"new",
"params",
"which",
"weren",
"t",
"in",
"the",
"old",
"params",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/url.rb#L220-L229 | train |
voltrb/volt | lib/volt/models/url.rb | Volt.URL.query_key | def query_key(path)
i = 0
path.map do |v|
i += 1
if i != 1
"[#{v}]"
else
v
end
end.join('')
end | ruby | def query_key(path)
i = 0
path.map do |v|
i += 1
if i != 1
"[#{v}]"
else
v
end
end.join('')
end | [
"def",
"query_key",
"(",
"path",
")",
"i",
"=",
"0",
"path",
".",
"map",
"do",
"|",
"v",
"|",
"i",
"+=",
"1",
"if",
"i",
"!=",
"1",
"\"[#{v}]\"",
"else",
"v",
"end",
"end",
".",
"join",
"(",
"''",
")",
"end"
] | Generate the key for a nested param attribute | [
"Generate",
"the",
"key",
"for",
"a",
"nested",
"param",
"attribute"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/url.rb#L265-L275 | train |
voltrb/volt | lib/volt/page/bindings/view_binding.rb | Volt.ViewBinding.create_controller_handler | def create_controller_handler(full_path, controller_path)
# If arguments is nil, then an blank SubContext will be created
args = [SubContext.new(@arguments, nil, true)]
# get the controller class and action
controller_class, action = ControllerHandler.get_controller_and_action(controller_path)
generated_new = false
new_controller = proc do
# Mark that we needed to generate a new controller instance (not reused
# from the group)
generated_new = true
# Setup the controller
controller_class.new(@volt_app, *args)
end
# Fetch grouped controllers if we're grouping
if @grouped_controller
# Find the controller in the group, or create it
controller = @grouped_controller.lookup_or_create(controller_class, &new_controller)
else
# Just create the controller
controller = new_controller.call
end
handler = ControllerHandler.fetch(controller, action)
if generated_new
# Call the action
stopped = handler.call_action
controller.instance_variable_set('@chain_stopped', true) if stopped
else
stopped = controller.instance_variable_get('@chain_stopped')
end
[handler, generated_new, stopped]
end | ruby | def create_controller_handler(full_path, controller_path)
# If arguments is nil, then an blank SubContext will be created
args = [SubContext.new(@arguments, nil, true)]
# get the controller class and action
controller_class, action = ControllerHandler.get_controller_and_action(controller_path)
generated_new = false
new_controller = proc do
# Mark that we needed to generate a new controller instance (not reused
# from the group)
generated_new = true
# Setup the controller
controller_class.new(@volt_app, *args)
end
# Fetch grouped controllers if we're grouping
if @grouped_controller
# Find the controller in the group, or create it
controller = @grouped_controller.lookup_or_create(controller_class, &new_controller)
else
# Just create the controller
controller = new_controller.call
end
handler = ControllerHandler.fetch(controller, action)
if generated_new
# Call the action
stopped = handler.call_action
controller.instance_variable_set('@chain_stopped', true) if stopped
else
stopped = controller.instance_variable_get('@chain_stopped')
end
[handler, generated_new, stopped]
end | [
"def",
"create_controller_handler",
"(",
"full_path",
",",
"controller_path",
")",
"# If arguments is nil, then an blank SubContext will be created",
"args",
"=",
"[",
"SubContext",
".",
"new",
"(",
"@arguments",
",",
"nil",
",",
"true",
")",
"]",
"# get the controller class and action",
"controller_class",
",",
"action",
"=",
"ControllerHandler",
".",
"get_controller_and_action",
"(",
"controller_path",
")",
"generated_new",
"=",
"false",
"new_controller",
"=",
"proc",
"do",
"# Mark that we needed to generate a new controller instance (not reused",
"# from the group)",
"generated_new",
"=",
"true",
"# Setup the controller",
"controller_class",
".",
"new",
"(",
"@volt_app",
",",
"args",
")",
"end",
"# Fetch grouped controllers if we're grouping",
"if",
"@grouped_controller",
"# Find the controller in the group, or create it",
"controller",
"=",
"@grouped_controller",
".",
"lookup_or_create",
"(",
"controller_class",
",",
"new_controller",
")",
"else",
"# Just create the controller",
"controller",
"=",
"new_controller",
".",
"call",
"end",
"handler",
"=",
"ControllerHandler",
".",
"fetch",
"(",
"controller",
",",
"action",
")",
"if",
"generated_new",
"# Call the action",
"stopped",
"=",
"handler",
".",
"call_action",
"controller",
".",
"instance_variable_set",
"(",
"'@chain_stopped'",
",",
"true",
")",
"if",
"stopped",
"else",
"stopped",
"=",
"controller",
".",
"instance_variable_get",
"(",
"'@chain_stopped'",
")",
"end",
"[",
"handler",
",",
"generated_new",
",",
"stopped",
"]",
"end"
] | Create controller handler loads up a controller inside of the controller handler for the paths | [
"Create",
"controller",
"handler",
"loads",
"up",
"a",
"controller",
"inside",
"of",
"the",
"controller",
"handler",
"for",
"the",
"paths"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/bindings/view_binding.rb#L181-L218 | train |
voltrb/volt | lib/volt/server/rack/component_paths.rb | Volt.ComponentPaths.app_folders | def app_folders
# Find all app folders
@app_folders ||= begin
volt_app = File.expand_path(File.join(File.dirname(__FILE__), '../../../../app'))
app_folders = [volt_app, "#{@root}/app", "#{@root}/vendor/app"].map { |f| File.expand_path(f) }
# Gem folders with volt in them
# TODO: we should probably qualify this a bit more
app_folders += Gem.loaded_specs.values
.select {|gem| gem.name =~ /^volt/ }
.map {|gem| "#{gem.full_gem_path}/app" }
app_folders.uniq
end
# Yield each app folder and return a flattened array with
# the results
files = []
@app_folders.each do |app_folder|
files << yield(app_folder)
end
files.flatten
end | ruby | def app_folders
# Find all app folders
@app_folders ||= begin
volt_app = File.expand_path(File.join(File.dirname(__FILE__), '../../../../app'))
app_folders = [volt_app, "#{@root}/app", "#{@root}/vendor/app"].map { |f| File.expand_path(f) }
# Gem folders with volt in them
# TODO: we should probably qualify this a bit more
app_folders += Gem.loaded_specs.values
.select {|gem| gem.name =~ /^volt/ }
.map {|gem| "#{gem.full_gem_path}/app" }
app_folders.uniq
end
# Yield each app folder and return a flattened array with
# the results
files = []
@app_folders.each do |app_folder|
files << yield(app_folder)
end
files.flatten
end | [
"def",
"app_folders",
"# Find all app folders",
"@app_folders",
"||=",
"begin",
"volt_app",
"=",
"File",
".",
"expand_path",
"(",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"'../../../../app'",
")",
")",
"app_folders",
"=",
"[",
"volt_app",
",",
"\"#{@root}/app\"",
",",
"\"#{@root}/vendor/app\"",
"]",
".",
"map",
"{",
"|",
"f",
"|",
"File",
".",
"expand_path",
"(",
"f",
")",
"}",
"# Gem folders with volt in them",
"# TODO: we should probably qualify this a bit more",
"app_folders",
"+=",
"Gem",
".",
"loaded_specs",
".",
"values",
".",
"select",
"{",
"|",
"gem",
"|",
"gem",
".",
"name",
"=~",
"/",
"/",
"}",
".",
"map",
"{",
"|",
"gem",
"|",
"\"#{gem.full_gem_path}/app\"",
"}",
"app_folders",
".",
"uniq",
"end",
"# Yield each app folder and return a flattened array with",
"# the results",
"files",
"=",
"[",
"]",
"@app_folders",
".",
"each",
"do",
"|",
"app_folder",
"|",
"files",
"<<",
"yield",
"(",
"app_folder",
")",
"end",
"files",
".",
"flatten",
"end"
] | Yield for every folder where we might find components | [
"Yield",
"for",
"every",
"folder",
"where",
"we",
"might",
"find",
"components"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/component_paths.rb#L11-L35 | train |
voltrb/volt | lib/volt/server/rack/component_paths.rb | Volt.ComponentPaths.components | def components
return @components if @components
@components = {}
app_folders do |app_folder|
Dir["#{app_folder}/*"].sort.each do |folder|
if File.directory?(folder)
folder_name = folder[/[^\/]+$/]
# Add in the folder if it's not alreay in there
folders = (@components[folder_name] ||= [])
folders << folder unless folders.include?(folder)
end
end
end
@components
end | ruby | def components
return @components if @components
@components = {}
app_folders do |app_folder|
Dir["#{app_folder}/*"].sort.each do |folder|
if File.directory?(folder)
folder_name = folder[/[^\/]+$/]
# Add in the folder if it's not alreay in there
folders = (@components[folder_name] ||= [])
folders << folder unless folders.include?(folder)
end
end
end
@components
end | [
"def",
"components",
"return",
"@components",
"if",
"@components",
"@components",
"=",
"{",
"}",
"app_folders",
"do",
"|",
"app_folder",
"|",
"Dir",
"[",
"\"#{app_folder}/*\"",
"]",
".",
"sort",
".",
"each",
"do",
"|",
"folder",
"|",
"if",
"File",
".",
"directory?",
"(",
"folder",
")",
"folder_name",
"=",
"folder",
"[",
"/",
"\\/",
"/",
"]",
"# Add in the folder if it's not alreay in there",
"folders",
"=",
"(",
"@components",
"[",
"folder_name",
"]",
"||=",
"[",
"]",
")",
"folders",
"<<",
"folder",
"unless",
"folders",
".",
"include?",
"(",
"folder",
")",
"end",
"end",
"end",
"@components",
"end"
] | returns an array of every folder that is a component | [
"returns",
"an",
"array",
"of",
"every",
"folder",
"that",
"is",
"a",
"component"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/component_paths.rb#L38-L55 | train |
voltrb/volt | lib/volt/server/rack/component_paths.rb | Volt.ComponentPaths.asset_folders | def asset_folders
folders = []
app_folders do |app_folder|
Dir["#{app_folder}/*/assets"].sort.each do |asset_folder|
folders << yield(asset_folder)
end
end
folders.flatten
end | ruby | def asset_folders
folders = []
app_folders do |app_folder|
Dir["#{app_folder}/*/assets"].sort.each do |asset_folder|
folders << yield(asset_folder)
end
end
folders.flatten
end | [
"def",
"asset_folders",
"folders",
"=",
"[",
"]",
"app_folders",
"do",
"|",
"app_folder",
"|",
"Dir",
"[",
"\"#{app_folder}/*/assets\"",
"]",
".",
"sort",
".",
"each",
"do",
"|",
"asset_folder",
"|",
"folders",
"<<",
"yield",
"(",
"asset_folder",
")",
"end",
"end",
"folders",
".",
"flatten",
"end"
] | Return every asset folder we need to serve from | [
"Return",
"every",
"asset",
"folder",
"we",
"need",
"to",
"serve",
"from"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/component_paths.rb#L117-L126 | train |
voltrb/volt | lib/volt/page/targets/dom_template.rb | Volt.DomTemplate.track_binding_anchors | def track_binding_anchors
@binding_anchors = {}
# Loop through the bindings, find in nodes.
@bindings.each_pair do |name, binding|
if name.is_a?(String)
# Find the dom node for an attribute anchor
node = nil
`
node = self.nodes.querySelector('#' + name);
`
@binding_anchors[name] = node
else
# Find the dom node for a comment anchor
start_comment = find_by_comment("$#{name}", @nodes)
end_comment = find_by_comment("$/#{name}", @nodes)
@binding_anchors[name] = [start_comment, end_comment]
end
end
end | ruby | def track_binding_anchors
@binding_anchors = {}
# Loop through the bindings, find in nodes.
@bindings.each_pair do |name, binding|
if name.is_a?(String)
# Find the dom node for an attribute anchor
node = nil
`
node = self.nodes.querySelector('#' + name);
`
@binding_anchors[name] = node
else
# Find the dom node for a comment anchor
start_comment = find_by_comment("$#{name}", @nodes)
end_comment = find_by_comment("$/#{name}", @nodes)
@binding_anchors[name] = [start_comment, end_comment]
end
end
end | [
"def",
"track_binding_anchors",
"@binding_anchors",
"=",
"{",
"}",
"# Loop through the bindings, find in nodes.",
"@bindings",
".",
"each_pair",
"do",
"|",
"name",
",",
"binding",
"|",
"if",
"name",
".",
"is_a?",
"(",
"String",
")",
"# Find the dom node for an attribute anchor",
"node",
"=",
"nil",
"`",
"`",
"@binding_anchors",
"[",
"name",
"]",
"=",
"node",
"else",
"# Find the dom node for a comment anchor",
"start_comment",
"=",
"find_by_comment",
"(",
"\"$#{name}\"",
",",
"@nodes",
")",
"end_comment",
"=",
"find_by_comment",
"(",
"\"$/#{name}\"",
",",
"@nodes",
")",
"@binding_anchors",
"[",
"name",
"]",
"=",
"[",
"start_comment",
",",
"end_comment",
"]",
"end",
"end",
"end"
] | Finds each of the binding anchors in the temp dom, then stores a reference
to them so they can be quickly updated without using xpath to find them again. | [
"Finds",
"each",
"of",
"the",
"binding",
"anchors",
"in",
"the",
"temp",
"dom",
"then",
"stores",
"a",
"reference",
"to",
"them",
"so",
"they",
"can",
"be",
"quickly",
"updated",
"without",
"using",
"xpath",
"to",
"find",
"them",
"again",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/targets/dom_template.rb#L39-L59 | train |
voltrb/volt | lib/volt/page/bindings/view_binding/view_lookup_for_path.rb | Volt.ViewLookupForPath.path_for_template | def path_for_template(lookup_path, force_section = nil)
parts = lookup_path.split('/')
parts_size = parts.size
return nil, nil if parts_size == 0
default_parts = %w(main main index body)
# When forcing a sub template, we can default the sub template section
default_parts[-1] = force_section if force_section
(5 - parts_size).times do |path_position|
# If they passed in a force_section, we can skip the first
next if force_section && path_position == 0
full_path = [@collection_name, @controller_name, @page_name, nil]
start_at = full_path.size - parts_size - path_position
full_path.size.times do |index|
if index >= start_at
if (part = parts[index - start_at])
full_path[index] = part
else
full_path[index] = default_parts[index]
end
end
end
path = full_path.join('/')
if check_for_template?(path)
controller = nil
if path_position >= 1
init_method = full_path[2]
else
init_method = full_path[3]
end
# Lookup the controller
controller = [full_path[0], full_path[1] + '_controller', init_method]
return path, controller
end
end
[nil, nil]
end | ruby | def path_for_template(lookup_path, force_section = nil)
parts = lookup_path.split('/')
parts_size = parts.size
return nil, nil if parts_size == 0
default_parts = %w(main main index body)
# When forcing a sub template, we can default the sub template section
default_parts[-1] = force_section if force_section
(5 - parts_size).times do |path_position|
# If they passed in a force_section, we can skip the first
next if force_section && path_position == 0
full_path = [@collection_name, @controller_name, @page_name, nil]
start_at = full_path.size - parts_size - path_position
full_path.size.times do |index|
if index >= start_at
if (part = parts[index - start_at])
full_path[index] = part
else
full_path[index] = default_parts[index]
end
end
end
path = full_path.join('/')
if check_for_template?(path)
controller = nil
if path_position >= 1
init_method = full_path[2]
else
init_method = full_path[3]
end
# Lookup the controller
controller = [full_path[0], full_path[1] + '_controller', init_method]
return path, controller
end
end
[nil, nil]
end | [
"def",
"path_for_template",
"(",
"lookup_path",
",",
"force_section",
"=",
"nil",
")",
"parts",
"=",
"lookup_path",
".",
"split",
"(",
"'/'",
")",
"parts_size",
"=",
"parts",
".",
"size",
"return",
"nil",
",",
"nil",
"if",
"parts_size",
"==",
"0",
"default_parts",
"=",
"%w(",
"main",
"main",
"index",
"body",
")",
"# When forcing a sub template, we can default the sub template section",
"default_parts",
"[",
"-",
"1",
"]",
"=",
"force_section",
"if",
"force_section",
"(",
"5",
"-",
"parts_size",
")",
".",
"times",
"do",
"|",
"path_position",
"|",
"# If they passed in a force_section, we can skip the first",
"next",
"if",
"force_section",
"&&",
"path_position",
"==",
"0",
"full_path",
"=",
"[",
"@collection_name",
",",
"@controller_name",
",",
"@page_name",
",",
"nil",
"]",
"start_at",
"=",
"full_path",
".",
"size",
"-",
"parts_size",
"-",
"path_position",
"full_path",
".",
"size",
".",
"times",
"do",
"|",
"index",
"|",
"if",
"index",
">=",
"start_at",
"if",
"(",
"part",
"=",
"parts",
"[",
"index",
"-",
"start_at",
"]",
")",
"full_path",
"[",
"index",
"]",
"=",
"part",
"else",
"full_path",
"[",
"index",
"]",
"=",
"default_parts",
"[",
"index",
"]",
"end",
"end",
"end",
"path",
"=",
"full_path",
".",
"join",
"(",
"'/'",
")",
"if",
"check_for_template?",
"(",
"path",
")",
"controller",
"=",
"nil",
"if",
"path_position",
">=",
"1",
"init_method",
"=",
"full_path",
"[",
"2",
"]",
"else",
"init_method",
"=",
"full_path",
"[",
"3",
"]",
"end",
"# Lookup the controller",
"controller",
"=",
"[",
"full_path",
"[",
"0",
"]",
",",
"full_path",
"[",
"1",
"]",
"+",
"'_controller'",
",",
"init_method",
"]",
"return",
"path",
",",
"controller",
"end",
"end",
"[",
"nil",
",",
"nil",
"]",
"end"
] | Takes in a lookup path and returns the full path for the matching
template. Also returns the controller and action name if applicable.
Looking up a path is fairly simple. There are 4 parts needed to find
the html to be rendered. File paths look like this:
app/{component}/views/{controller_name}/{view}.html
Within the html file may be one or more sections.
1. component (app/{comp})
2. controller
3. view
4. sections
When searching for a file, the lookup starts at the section, and moves up.
when moving up, default values are provided for the section, then view/section, etc..
until a file is either found or the component level is reached.
The defaults are as follows:
1. component - main
2. controller - main
3. view - index
4. section - body | [
"Takes",
"in",
"a",
"lookup",
"path",
"and",
"returns",
"the",
"full",
"path",
"for",
"the",
"matching",
"template",
".",
"Also",
"returns",
"the",
"controller",
"and",
"action",
"name",
"if",
"applicable",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/bindings/view_binding/view_lookup_for_path.rb#L44-L91 | train |
voltrb/volt | lib/volt/controllers/model_controller.rb | Volt.ModelController.first_element | def first_element
check_section!('first_element')
range = dom_nodes
nodes = `range.startContainer.childNodes`
start_index = `range.startOffset`
end_index = `range.endOffset`
start_index.upto(end_index) do |index|
node = `nodes[index]`
# Return if an element
if `node.nodeType === 1`
return node
end
end
return nil
end | ruby | def first_element
check_section!('first_element')
range = dom_nodes
nodes = `range.startContainer.childNodes`
start_index = `range.startOffset`
end_index = `range.endOffset`
start_index.upto(end_index) do |index|
node = `nodes[index]`
# Return if an element
if `node.nodeType === 1`
return node
end
end
return nil
end | [
"def",
"first_element",
"check_section!",
"(",
"'first_element'",
")",
"range",
"=",
"dom_nodes",
"nodes",
"=",
"`",
"`",
"start_index",
"=",
"`",
"`",
"end_index",
"=",
"`",
"`",
"start_index",
".",
"upto",
"(",
"end_index",
")",
"do",
"|",
"index",
"|",
"node",
"=",
"`",
"`",
"# Return if an element",
"if",
"`",
"`",
"return",
"node",
"end",
"end",
"return",
"nil",
"end"
] | Walks the dom_nodes range until it finds an element. Typically this will
be the container element without the whitespace text nodes. | [
"Walks",
"the",
"dom_nodes",
"range",
"until",
"it",
"finds",
"an",
"element",
".",
"Typically",
"this",
"will",
"be",
"the",
"container",
"element",
"without",
"the",
"whitespace",
"text",
"nodes",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/model_controller.rb#L41-L59 | train |
voltrb/volt | lib/volt/controllers/model_controller.rb | Volt.ModelController.yield_html | def yield_html
if (template_path = attrs.content_template_path)
@yield_renderer ||= StringTemplateRenderer.new(@volt_app, attrs.content_controller, template_path)
@yield_renderer.html
else
# no template, empty string
''
end
end | ruby | def yield_html
if (template_path = attrs.content_template_path)
@yield_renderer ||= StringTemplateRenderer.new(@volt_app, attrs.content_controller, template_path)
@yield_renderer.html
else
# no template, empty string
''
end
end | [
"def",
"yield_html",
"if",
"(",
"template_path",
"=",
"attrs",
".",
"content_template_path",
")",
"@yield_renderer",
"||=",
"StringTemplateRenderer",
".",
"new",
"(",
"@volt_app",
",",
"attrs",
".",
"content_controller",
",",
"template_path",
")",
"@yield_renderer",
".",
"html",
"else",
"# no template, empty string",
"''",
"end",
"end"
] | yield_html renders the content passed into a tag as a string. You can ```.watch!```
```yield_html``` and it will be run again when anything in the template changes. | [
"yield_html",
"renders",
"the",
"content",
"passed",
"into",
"a",
"tag",
"as",
"a",
"string",
".",
"You",
"can",
".",
"watch!",
"yield_html",
"and",
"it",
"will",
"be",
"run",
"again",
"when",
"anything",
"in",
"the",
"template",
"changes",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/model_controller.rb#L72-L80 | train |
voltrb/volt | lib/volt/controllers/model_controller.rb | Volt.ModelController.model= | def model=(val)
if val.is_a?(Promise)
# Resolve the promise before setting
self.last_promise = val
val.then do |result|
# Only assign if nothing else has been assigned since we started the resolve
self.model = result if last_promise == val
end.fail do |err|
Volt.logger.error("Unable to resolve promise assigned to model on #{inspect}")
end
return
end
# Clear
self.last_promise = nil
# Start with a nil reactive value.
self.current_model ||= Model.new
if Symbol === val || String === val
collections = [:page, :store, :params, :controller]
if collections.include?(val.to_sym)
self.current_model = send(val)
else
fail "#{val} is not the name of a valid model, choose from: #{collections.join(', ')}"
end
else
self.current_model = val
end
end | ruby | def model=(val)
if val.is_a?(Promise)
# Resolve the promise before setting
self.last_promise = val
val.then do |result|
# Only assign if nothing else has been assigned since we started the resolve
self.model = result if last_promise == val
end.fail do |err|
Volt.logger.error("Unable to resolve promise assigned to model on #{inspect}")
end
return
end
# Clear
self.last_promise = nil
# Start with a nil reactive value.
self.current_model ||= Model.new
if Symbol === val || String === val
collections = [:page, :store, :params, :controller]
if collections.include?(val.to_sym)
self.current_model = send(val)
else
fail "#{val} is not the name of a valid model, choose from: #{collections.join(', ')}"
end
else
self.current_model = val
end
end | [
"def",
"model",
"=",
"(",
"val",
")",
"if",
"val",
".",
"is_a?",
"(",
"Promise",
")",
"# Resolve the promise before setting",
"self",
".",
"last_promise",
"=",
"val",
"val",
".",
"then",
"do",
"|",
"result",
"|",
"# Only assign if nothing else has been assigned since we started the resolve",
"self",
".",
"model",
"=",
"result",
"if",
"last_promise",
"==",
"val",
"end",
".",
"fail",
"do",
"|",
"err",
"|",
"Volt",
".",
"logger",
".",
"error",
"(",
"\"Unable to resolve promise assigned to model on #{inspect}\"",
")",
"end",
"return",
"end",
"# Clear",
"self",
".",
"last_promise",
"=",
"nil",
"# Start with a nil reactive value.",
"self",
".",
"current_model",
"||=",
"Model",
".",
"new",
"if",
"Symbol",
"===",
"val",
"||",
"String",
"===",
"val",
"collections",
"=",
"[",
":page",
",",
":store",
",",
":params",
",",
":controller",
"]",
"if",
"collections",
".",
"include?",
"(",
"val",
".",
"to_sym",
")",
"self",
".",
"current_model",
"=",
"send",
"(",
"val",
")",
"else",
"fail",
"\"#{val} is not the name of a valid model, choose from: #{collections.join(', ')}\"",
"end",
"else",
"self",
".",
"current_model",
"=",
"val",
"end",
"end"
] | Sets the current model on this controller | [
"Sets",
"the",
"current",
"model",
"on",
"this",
"controller"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/model_controller.rb#L105-L136 | train |
voltrb/volt | lib/volt/controllers/model_controller.rb | Volt.ModelController.loaded? | def loaded?
if model.respond_to?(:loaded?)
# There is a model and it is loaded
return model.loaded?
elsif last_promise || model.is_a?(Promise)
# The model is a promise or is resolving
return false
else
# Otherwise, its loaded
return true
end
end | ruby | def loaded?
if model.respond_to?(:loaded?)
# There is a model and it is loaded
return model.loaded?
elsif last_promise || model.is_a?(Promise)
# The model is a promise or is resolving
return false
else
# Otherwise, its loaded
return true
end
end | [
"def",
"loaded?",
"if",
"model",
".",
"respond_to?",
"(",
":loaded?",
")",
"# There is a model and it is loaded",
"return",
"model",
".",
"loaded?",
"elsif",
"last_promise",
"||",
"model",
".",
"is_a?",
"(",
"Promise",
")",
"# The model is a promise or is resolving",
"return",
"false",
"else",
"# Otherwise, its loaded",
"return",
"true",
"end",
"end"
] | loaded? is a quick way to see if the model for the controller is loaded
yet. If the model is there, it asks the model if its loaded. If the model
was set to a promise, it waits for the promise to resolve. | [
"loaded?",
"is",
"a",
"quick",
"way",
"to",
"see",
"if",
"the",
"model",
"for",
"the",
"controller",
"is",
"loaded",
"yet",
".",
"If",
"the",
"model",
"is",
"there",
"it",
"asks",
"the",
"model",
"if",
"its",
"loaded",
".",
"If",
"the",
"model",
"was",
"set",
"to",
"a",
"promise",
"it",
"waits",
"for",
"the",
"promise",
"to",
"resolve",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/model_controller.rb#L207-L218 | train |
voltrb/volt | lib/volt/controllers/model_controller.rb | Volt.ModelController.raw | def raw(str)
# Promises need to have .to_s called using .then, since .to_s is a promise
# method, so it won't be passed down to the value.
if str.is_a?(Promise)
str = str.then(&:to_s)
else
str = str.to_s unless str.is_a?(String)
end
str.html_safe
end | ruby | def raw(str)
# Promises need to have .to_s called using .then, since .to_s is a promise
# method, so it won't be passed down to the value.
if str.is_a?(Promise)
str = str.then(&:to_s)
else
str = str.to_s unless str.is_a?(String)
end
str.html_safe
end | [
"def",
"raw",
"(",
"str",
")",
"# Promises need to have .to_s called using .then, since .to_s is a promise",
"# method, so it won't be passed down to the value.",
"if",
"str",
".",
"is_a?",
"(",
"Promise",
")",
"str",
"=",
"str",
".",
"then",
"(",
":to_s",
")",
"else",
"str",
"=",
"str",
".",
"to_s",
"unless",
"str",
".",
"is_a?",
"(",
"String",
")",
"end",
"str",
".",
"html_safe",
"end"
] | Raw marks a string as html safe, so bindings can be rendered as html.
With great power comes great responsibility. | [
"Raw",
"marks",
"a",
"string",
"as",
"html",
"safe",
"so",
"bindings",
"can",
"be",
"rendered",
"as",
"html",
".",
"With",
"great",
"power",
"comes",
"great",
"responsibility",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/model_controller.rb#L231-L241 | train |
voltrb/volt | lib/volt/models/validators/numericality_validator.rb | Volt.NumericalityValidator.check_errors | def check_errors
if @value && @value.is_a?(Numeric)
if @args.is_a?(Hash)
@args.each do |arg, val|
case arg
when :min
add_error("number must be greater than #{val}") if @value < val
when :max
add_error("number must be less than #{val}") if @value > val
end
end
end
else
message = (@args.is_a?(Hash) && @args[:message]) || 'must be a number'
add_error(message)
end
end | ruby | def check_errors
if @value && @value.is_a?(Numeric)
if @args.is_a?(Hash)
@args.each do |arg, val|
case arg
when :min
add_error("number must be greater than #{val}") if @value < val
when :max
add_error("number must be less than #{val}") if @value > val
end
end
end
else
message = (@args.is_a?(Hash) && @args[:message]) || 'must be a number'
add_error(message)
end
end | [
"def",
"check_errors",
"if",
"@value",
"&&",
"@value",
".",
"is_a?",
"(",
"Numeric",
")",
"if",
"@args",
".",
"is_a?",
"(",
"Hash",
")",
"@args",
".",
"each",
"do",
"|",
"arg",
",",
"val",
"|",
"case",
"arg",
"when",
":min",
"add_error",
"(",
"\"number must be greater than #{val}\"",
")",
"if",
"@value",
"<",
"val",
"when",
":max",
"add_error",
"(",
"\"number must be less than #{val}\"",
")",
"if",
"@value",
">",
"val",
"end",
"end",
"end",
"else",
"message",
"=",
"(",
"@args",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"@args",
"[",
":message",
"]",
")",
"||",
"'must be a number'",
"add_error",
"(",
"message",
")",
"end",
"end"
] | Looks at the value | [
"Looks",
"at",
"the",
"value"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/validators/numericality_validator.rb#L37-L55 | train |
voltrb/volt | lib/volt/controllers/http_controller.rb | Volt.HttpController.params | def params
@params ||= begin
params = request.params.symbolize_keys.merge(@initial_params)
Volt::Model.new(params, persistor: Volt::Persistors::Params)
end
end | ruby | def params
@params ||= begin
params = request.params.symbolize_keys.merge(@initial_params)
Volt::Model.new(params, persistor: Volt::Persistors::Params)
end
end | [
"def",
"params",
"@params",
"||=",
"begin",
"params",
"=",
"request",
".",
"params",
".",
"symbolize_keys",
".",
"merge",
"(",
"@initial_params",
")",
"Volt",
"::",
"Model",
".",
"new",
"(",
"params",
",",
"persistor",
":",
"Volt",
"::",
"Persistors",
"::",
"Params",
")",
"end",
"end"
] | Initialzed with the params parsed from the route and the HttpRequest | [
"Initialzed",
"with",
"the",
"params",
"parsed",
"from",
"the",
"route",
"and",
"the",
"HttpRequest"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/controllers/http_controller.rb#L25-L30 | train |
voltrb/volt | lib/volt/page/targets/attribute_section.rb | Volt.AttributeSection.rezero_bindings | def rezero_bindings(html, bindings)
@@base_binding_id ||= 20_000
# rezero
parts = html.split(/(\<\!\-\- \$\/?[0-9]+ \-\-\>)/).reject { |v| v == '' }
new_html = []
new_bindings = {}
id_map = {}
parts.each do |part|
case part
when /\<\!\-\- \$[0-9]+ \-\-\>/
# Open
binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i
binding = bindings[binding_id]
new_bindings[@@base_binding_id] = binding if binding
new_html << "<!-- $#{@@base_binding_id} -->"
id_map[binding_id] = @@base_binding_id
@@base_binding_id += 1
when /\<\!\-\- \$\/[0-9]+ \-\-\>/
# Close
binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i
new_html << "<!-- $/#{id_map[binding_id]} -->"
else
# html string
new_html << part
end
end
# Also copy the attribute bindings
bindings.each_pair do |name, binding|
if name.is_a?(String) && name[0..1] == 'id'
new_bindings[name] = binding
end
end
return new_html.join(''), new_bindings
end | ruby | def rezero_bindings(html, bindings)
@@base_binding_id ||= 20_000
# rezero
parts = html.split(/(\<\!\-\- \$\/?[0-9]+ \-\-\>)/).reject { |v| v == '' }
new_html = []
new_bindings = {}
id_map = {}
parts.each do |part|
case part
when /\<\!\-\- \$[0-9]+ \-\-\>/
# Open
binding_id = part.match(/\<\!\-\- \$([0-9]+) \-\-\>/)[1].to_i
binding = bindings[binding_id]
new_bindings[@@base_binding_id] = binding if binding
new_html << "<!-- $#{@@base_binding_id} -->"
id_map[binding_id] = @@base_binding_id
@@base_binding_id += 1
when /\<\!\-\- \$\/[0-9]+ \-\-\>/
# Close
binding_id = part.match(/\<\!\-\- \$\/([0-9]+) \-\-\>/)[1].to_i
new_html << "<!-- $/#{id_map[binding_id]} -->"
else
# html string
new_html << part
end
end
# Also copy the attribute bindings
bindings.each_pair do |name, binding|
if name.is_a?(String) && name[0..1] == 'id'
new_bindings[name] = binding
end
end
return new_html.join(''), new_bindings
end | [
"def",
"rezero_bindings",
"(",
"html",
",",
"bindings",
")",
"@@base_binding_id",
"||=",
"20_000",
"# rezero",
"parts",
"=",
"html",
".",
"split",
"(",
"/",
"\\<",
"\\!",
"\\-",
"\\-",
"\\$",
"\\/",
"\\-",
"\\-",
"\\>",
"/",
")",
".",
"reject",
"{",
"|",
"v",
"|",
"v",
"==",
"''",
"}",
"new_html",
"=",
"[",
"]",
"new_bindings",
"=",
"{",
"}",
"id_map",
"=",
"{",
"}",
"parts",
".",
"each",
"do",
"|",
"part",
"|",
"case",
"part",
"when",
"/",
"\\<",
"\\!",
"\\-",
"\\-",
"\\$",
"\\-",
"\\-",
"\\>",
"/",
"# Open",
"binding_id",
"=",
"part",
".",
"match",
"(",
"/",
"\\<",
"\\!",
"\\-",
"\\-",
"\\$",
"\\-",
"\\-",
"\\>",
"/",
")",
"[",
"1",
"]",
".",
"to_i",
"binding",
"=",
"bindings",
"[",
"binding_id",
"]",
"new_bindings",
"[",
"@@base_binding_id",
"]",
"=",
"binding",
"if",
"binding",
"new_html",
"<<",
"\"<!-- $#{@@base_binding_id} -->\"",
"id_map",
"[",
"binding_id",
"]",
"=",
"@@base_binding_id",
"@@base_binding_id",
"+=",
"1",
"when",
"/",
"\\<",
"\\!",
"\\-",
"\\-",
"\\$",
"\\/",
"\\-",
"\\-",
"\\>",
"/",
"# Close",
"binding_id",
"=",
"part",
".",
"match",
"(",
"/",
"\\<",
"\\!",
"\\-",
"\\-",
"\\$",
"\\/",
"\\-",
"\\-",
"\\>",
"/",
")",
"[",
"1",
"]",
".",
"to_i",
"new_html",
"<<",
"\"<!-- $/#{id_map[binding_id]} -->\"",
"else",
"# html string",
"new_html",
"<<",
"part",
"end",
"end",
"# Also copy the attribute bindings",
"bindings",
".",
"each_pair",
"do",
"|",
"name",
",",
"binding",
"|",
"if",
"name",
".",
"is_a?",
"(",
"String",
")",
"&&",
"name",
"[",
"0",
"..",
"1",
"]",
"==",
"'id'",
"new_bindings",
"[",
"name",
"]",
"=",
"binding",
"end",
"end",
"return",
"new_html",
".",
"join",
"(",
"''",
")",
",",
"new_bindings",
"end"
] | When using bindings, we have to change the binding id so we don't reuse
the same id when rendering a binding multiple times. | [
"When",
"using",
"bindings",
"we",
"have",
"to",
"change",
"the",
"binding",
"id",
"so",
"we",
"don",
"t",
"reuse",
"the",
"same",
"id",
"when",
"rendering",
"a",
"binding",
"multiple",
"times",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/targets/attribute_section.rb#L33-L71 | train |
voltrb/volt | lib/volt/page/targets/attribute_section.rb | Volt.AttributeSection.set_content_and_rezero_bindings | def set_content_and_rezero_bindings(html, bindings)
html, bindings = rezero_bindings(html, bindings)
if @binding_name == 'main'
@target.html = html
else
@target.find_by_binding_id(@binding_name).html = html
end
bindings
end | ruby | def set_content_and_rezero_bindings(html, bindings)
html, bindings = rezero_bindings(html, bindings)
if @binding_name == 'main'
@target.html = html
else
@target.find_by_binding_id(@binding_name).html = html
end
bindings
end | [
"def",
"set_content_and_rezero_bindings",
"(",
"html",
",",
"bindings",
")",
"html",
",",
"bindings",
"=",
"rezero_bindings",
"(",
"html",
",",
"bindings",
")",
"if",
"@binding_name",
"==",
"'main'",
"@target",
".",
"html",
"=",
"html",
"else",
"@target",
".",
"find_by_binding_id",
"(",
"@binding_name",
")",
".",
"html",
"=",
"html",
"end",
"bindings",
"end"
] | Takes in our html and bindings, and rezero's the comment names, and the
bindings. Returns an updated bindings hash | [
"Takes",
"in",
"our",
"html",
"and",
"bindings",
"and",
"rezero",
"s",
"the",
"comment",
"names",
"and",
"the",
"bindings",
".",
"Returns",
"an",
"updated",
"bindings",
"hash"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/targets/attribute_section.rb#L75-L85 | train |
voltrb/volt | lib/volt/server/html_parser/view_parser.rb | Volt.ViewParser.code | def code(app_reference)
code = ''
templates.each_pair do |name, template|
binding_code = []
if template['bindings']
template['bindings'].each_pair do |key, value|
binding_code << "#{key.inspect} => [#{value.join(', ')}]"
end
end
binding_code = "{#{binding_code.join(', ')}}"
code << "#{app_reference}.add_template(#{name.inspect}, #{template['html'].inspect}, #{binding_code})\n"
end
code
end | ruby | def code(app_reference)
code = ''
templates.each_pair do |name, template|
binding_code = []
if template['bindings']
template['bindings'].each_pair do |key, value|
binding_code << "#{key.inspect} => [#{value.join(', ')}]"
end
end
binding_code = "{#{binding_code.join(', ')}}"
code << "#{app_reference}.add_template(#{name.inspect}, #{template['html'].inspect}, #{binding_code})\n"
end
code
end | [
"def",
"code",
"(",
"app_reference",
")",
"code",
"=",
"''",
"templates",
".",
"each_pair",
"do",
"|",
"name",
",",
"template",
"|",
"binding_code",
"=",
"[",
"]",
"if",
"template",
"[",
"'bindings'",
"]",
"template",
"[",
"'bindings'",
"]",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"binding_code",
"<<",
"\"#{key.inspect} => [#{value.join(', ')}]\"",
"end",
"end",
"binding_code",
"=",
"\"{#{binding_code.join(', ')}}\"",
"code",
"<<",
"\"#{app_reference}.add_template(#{name.inspect}, #{template['html'].inspect}, #{binding_code})\\n\"",
"end",
"code",
"end"
] | Generate code for the view that can be evaled. | [
"Generate",
"code",
"for",
"the",
"view",
"that",
"can",
"be",
"evaled",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/view_parser.rb#L48-L65 | train |
voltrb/volt | lib/volt/helpers/time/distance.rb | Volt.Duration.duration_in_words | def duration_in_words(places=2, min_unit=:minutes, recent_message='just now')
parts = []
secs = to_i
UNIT_MAP.each_pair do |unit, count|
val = (secs / count).floor
secs = secs % count
parts << [val, unit] if val > 0
break if unit == min_unit
end
# Trim number of units
parts = parts.take(places) if places
parts = parts.map do |val, unit|
pl_units = val == 1 ? unit.singularize : unit
"#{val} #{pl_units}"
end
# Round up to the nearest unit
if parts.size == 0
parts << recent_message
end
parts.to_sentence
end | ruby | def duration_in_words(places=2, min_unit=:minutes, recent_message='just now')
parts = []
secs = to_i
UNIT_MAP.each_pair do |unit, count|
val = (secs / count).floor
secs = secs % count
parts << [val, unit] if val > 0
break if unit == min_unit
end
# Trim number of units
parts = parts.take(places) if places
parts = parts.map do |val, unit|
pl_units = val == 1 ? unit.singularize : unit
"#{val} #{pl_units}"
end
# Round up to the nearest unit
if parts.size == 0
parts << recent_message
end
parts.to_sentence
end | [
"def",
"duration_in_words",
"(",
"places",
"=",
"2",
",",
"min_unit",
"=",
":minutes",
",",
"recent_message",
"=",
"'just now'",
")",
"parts",
"=",
"[",
"]",
"secs",
"=",
"to_i",
"UNIT_MAP",
".",
"each_pair",
"do",
"|",
"unit",
",",
"count",
"|",
"val",
"=",
"(",
"secs",
"/",
"count",
")",
".",
"floor",
"secs",
"=",
"secs",
"%",
"count",
"parts",
"<<",
"[",
"val",
",",
"unit",
"]",
"if",
"val",
">",
"0",
"break",
"if",
"unit",
"==",
"min_unit",
"end",
"# Trim number of units",
"parts",
"=",
"parts",
".",
"take",
"(",
"places",
")",
"if",
"places",
"parts",
"=",
"parts",
".",
"map",
"do",
"|",
"val",
",",
"unit",
"|",
"pl_units",
"=",
"val",
"==",
"1",
"?",
"unit",
".",
"singularize",
":",
"unit",
"\"#{val} #{pl_units}\"",
"end",
"# Round up to the nearest unit",
"if",
"parts",
".",
"size",
"==",
"0",
"parts",
"<<",
"recent_message",
"end",
"parts",
".",
"to_sentence",
"end"
] | Returns a string representation of the duration.
@param How many places in time units to show.
@param The minimum unit to show, anything below will be ignored. Results
will be rounded up the the nearest min_unit. | [
"Returns",
"a",
"string",
"representation",
"of",
"the",
"duration",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/helpers/time/distance.rb#L18-L43 | train |
voltrb/volt | lib/volt/page/tasks.rb | Volt.Tasks.response | def response(promise_id, result, error, cookies)
# Set the cookies
if cookies
cookies.each do |key, value|
@volt_app.cookies.set(key, value)
end
end
promise = @promises.delete(promise_id)
if promise
if error
# TODO: full error handling
Volt.logger.error('Task Response:')
Volt.logger.error(error)
promise.reject(error)
else
promise.resolve(result)
end
end
end | ruby | def response(promise_id, result, error, cookies)
# Set the cookies
if cookies
cookies.each do |key, value|
@volt_app.cookies.set(key, value)
end
end
promise = @promises.delete(promise_id)
if promise
if error
# TODO: full error handling
Volt.logger.error('Task Response:')
Volt.logger.error(error)
promise.reject(error)
else
promise.resolve(result)
end
end
end | [
"def",
"response",
"(",
"promise_id",
",",
"result",
",",
"error",
",",
"cookies",
")",
"# Set the cookies",
"if",
"cookies",
"cookies",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"@volt_app",
".",
"cookies",
".",
"set",
"(",
"key",
",",
"value",
")",
"end",
"end",
"promise",
"=",
"@promises",
".",
"delete",
"(",
"promise_id",
")",
"if",
"promise",
"if",
"error",
"# TODO: full error handling",
"Volt",
".",
"logger",
".",
"error",
"(",
"'Task Response:'",
")",
"Volt",
".",
"logger",
".",
"error",
"(",
"error",
")",
"promise",
".",
"reject",
"(",
"error",
")",
"else",
"promise",
".",
"resolve",
"(",
"result",
")",
"end",
"end",
"end"
] | When a request is sent to the backend, it can attach a callback,
this is called from the backend to pass to the callback. | [
"When",
"a",
"request",
"is",
"sent",
"to",
"the",
"backend",
"it",
"can",
"attach",
"a",
"callback",
"this",
"is",
"called",
"from",
"the",
"backend",
"to",
"pass",
"to",
"the",
"callback",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/tasks.rb#L44-L65 | train |
voltrb/volt | lib/volt/page/tasks.rb | Volt.Tasks.notify_query | def notify_query(method_name, collection, query, *args)
query_obj = Persistors::ArrayStore.query_pool.lookup(collection, query)
query_obj.send(method_name, *args)
end | ruby | def notify_query(method_name, collection, query, *args)
query_obj = Persistors::ArrayStore.query_pool.lookup(collection, query)
query_obj.send(method_name, *args)
end | [
"def",
"notify_query",
"(",
"method_name",
",",
"collection",
",",
"query",
",",
"*",
"args",
")",
"query_obj",
"=",
"Persistors",
"::",
"ArrayStore",
".",
"query_pool",
".",
"lookup",
"(",
"collection",
",",
"query",
")",
"query_obj",
".",
"send",
"(",
"method_name",
",",
"args",
")",
"end"
] | Called when the backend sends a notification to change the results of
a query. | [
"Called",
"when",
"the",
"backend",
"sends",
"a",
"notification",
"to",
"change",
"the",
"results",
"of",
"a",
"query",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/tasks.rb#L69-L72 | train |
voltrb/volt | lib/volt/reactive/dependency.rb | Volt.Dependency.depend | def depend
# If there is no @dependencies, don't depend because it has been removed
return unless @dependencies
current = Computation.current
if current
added = @dependencies.add?(current)
if added
# The first time the dependency is depended on by this computation, we call on_dep
@on_dep.call if @on_dep && @dependencies.size == 1
current.on_invalidate do
# If @dependencies is nil, this Dependency has been removed
if @dependencies
# For set, .delete returns a boolean if it was deleted
deleted = @dependencies.delete?(current)
# Call on stop dep if no more deps
@on_stop_dep.call if @on_stop_dep && deleted && @dependencies.size == 0
end
end
end
end
end | ruby | def depend
# If there is no @dependencies, don't depend because it has been removed
return unless @dependencies
current = Computation.current
if current
added = @dependencies.add?(current)
if added
# The first time the dependency is depended on by this computation, we call on_dep
@on_dep.call if @on_dep && @dependencies.size == 1
current.on_invalidate do
# If @dependencies is nil, this Dependency has been removed
if @dependencies
# For set, .delete returns a boolean if it was deleted
deleted = @dependencies.delete?(current)
# Call on stop dep if no more deps
@on_stop_dep.call if @on_stop_dep && deleted && @dependencies.size == 0
end
end
end
end
end | [
"def",
"depend",
"# If there is no @dependencies, don't depend because it has been removed",
"return",
"unless",
"@dependencies",
"current",
"=",
"Computation",
".",
"current",
"if",
"current",
"added",
"=",
"@dependencies",
".",
"add?",
"(",
"current",
")",
"if",
"added",
"# The first time the dependency is depended on by this computation, we call on_dep",
"@on_dep",
".",
"call",
"if",
"@on_dep",
"&&",
"@dependencies",
".",
"size",
"==",
"1",
"current",
".",
"on_invalidate",
"do",
"# If @dependencies is nil, this Dependency has been removed",
"if",
"@dependencies",
"# For set, .delete returns a boolean if it was deleted",
"deleted",
"=",
"@dependencies",
".",
"delete?",
"(",
"current",
")",
"# Call on stop dep if no more deps",
"@on_stop_dep",
".",
"call",
"if",
"@on_stop_dep",
"&&",
"deleted",
"&&",
"@dependencies",
".",
"size",
"==",
"0",
"end",
"end",
"end",
"end",
"end"
] | Setup a new dependency.
@param on_dep [Proc] a proc to be called the first time a computation depends
on this dependency.
@param on_stop_dep [Proc] a proc to be called when no computations are depending
on this dependency anymore. | [
"Setup",
"a",
"new",
"dependency",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/reactive/dependency.rb#L21-L45 | train |
voltrb/volt | lib/volt/models/model.rb | Volt.Model.assign_attributes | def assign_attributes(attrs, initial_setup = false, skip_changes = false)
attrs = wrap_values(attrs)
if attrs
# When doing a mass-assign, we don't validate or save until the end.
if initial_setup || skip_changes
Model.no_change_tracking do
assign_all_attributes(attrs, skip_changes)
end
else
assign_all_attributes(attrs)
end
else
# Assign to empty
@attributes = {}
end
# Trigger and change all
@deps.changed_all!
@deps = HashDependency.new
run_initial_setup(initial_setup)
end | ruby | def assign_attributes(attrs, initial_setup = false, skip_changes = false)
attrs = wrap_values(attrs)
if attrs
# When doing a mass-assign, we don't validate or save until the end.
if initial_setup || skip_changes
Model.no_change_tracking do
assign_all_attributes(attrs, skip_changes)
end
else
assign_all_attributes(attrs)
end
else
# Assign to empty
@attributes = {}
end
# Trigger and change all
@deps.changed_all!
@deps = HashDependency.new
run_initial_setup(initial_setup)
end | [
"def",
"assign_attributes",
"(",
"attrs",
",",
"initial_setup",
"=",
"false",
",",
"skip_changes",
"=",
"false",
")",
"attrs",
"=",
"wrap_values",
"(",
"attrs",
")",
"if",
"attrs",
"# When doing a mass-assign, we don't validate or save until the end.",
"if",
"initial_setup",
"||",
"skip_changes",
"Model",
".",
"no_change_tracking",
"do",
"assign_all_attributes",
"(",
"attrs",
",",
"skip_changes",
")",
"end",
"else",
"assign_all_attributes",
"(",
"attrs",
")",
"end",
"else",
"# Assign to empty",
"@attributes",
"=",
"{",
"}",
"end",
"# Trigger and change all",
"@deps",
".",
"changed_all!",
"@deps",
"=",
"HashDependency",
".",
"new",
"run_initial_setup",
"(",
"initial_setup",
")",
"end"
] | Assign multiple attributes as a hash, directly. | [
"Assign",
"multiple",
"attributes",
"as",
"a",
"hash",
"directly",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model.rb#L140-L162 | train |
voltrb/volt | lib/volt/models/model.rb | Volt.Model.set | def set(attribute_name, value, &block)
# Assign, without the =
attribute_name = attribute_name.to_sym
check_valid_field_name(attribute_name)
old_value = @attributes[attribute_name]
new_value = wrap_value(value, [attribute_name])
if old_value != new_value
# Track the old value, skip if we are in no_validate
attribute_will_change!(attribute_name, old_value) unless Volt.in_mode?(:no_change_tracking)
# Assign the new value
@attributes[attribute_name] = new_value
@deps.changed!(attribute_name)
@size_dep.changed! if old_value.nil? || new_value.nil?
# TODO: Can we make this so it doesn't need to be handled for non store collections
# (maybe move it to persistor, though thats weird since buffers don't have a persistor)
clear_server_errors(attribute_name) if @server_errors.present?
# Save the changes
run_changed(attribute_name) unless Volt.in_mode?(:no_change_tracking)
end
new_value
end | ruby | def set(attribute_name, value, &block)
# Assign, without the =
attribute_name = attribute_name.to_sym
check_valid_field_name(attribute_name)
old_value = @attributes[attribute_name]
new_value = wrap_value(value, [attribute_name])
if old_value != new_value
# Track the old value, skip if we are in no_validate
attribute_will_change!(attribute_name, old_value) unless Volt.in_mode?(:no_change_tracking)
# Assign the new value
@attributes[attribute_name] = new_value
@deps.changed!(attribute_name)
@size_dep.changed! if old_value.nil? || new_value.nil?
# TODO: Can we make this so it doesn't need to be handled for non store collections
# (maybe move it to persistor, though thats weird since buffers don't have a persistor)
clear_server_errors(attribute_name) if @server_errors.present?
# Save the changes
run_changed(attribute_name) unless Volt.in_mode?(:no_change_tracking)
end
new_value
end | [
"def",
"set",
"(",
"attribute_name",
",",
"value",
",",
"&",
"block",
")",
"# Assign, without the =",
"attribute_name",
"=",
"attribute_name",
".",
"to_sym",
"check_valid_field_name",
"(",
"attribute_name",
")",
"old_value",
"=",
"@attributes",
"[",
"attribute_name",
"]",
"new_value",
"=",
"wrap_value",
"(",
"value",
",",
"[",
"attribute_name",
"]",
")",
"if",
"old_value",
"!=",
"new_value",
"# Track the old value, skip if we are in no_validate",
"attribute_will_change!",
"(",
"attribute_name",
",",
"old_value",
")",
"unless",
"Volt",
".",
"in_mode?",
"(",
":no_change_tracking",
")",
"# Assign the new value",
"@attributes",
"[",
"attribute_name",
"]",
"=",
"new_value",
"@deps",
".",
"changed!",
"(",
"attribute_name",
")",
"@size_dep",
".",
"changed!",
"if",
"old_value",
".",
"nil?",
"||",
"new_value",
".",
"nil?",
"# TODO: Can we make this so it doesn't need to be handled for non store collections",
"# (maybe move it to persistor, though thats weird since buffers don't have a persistor)",
"clear_server_errors",
"(",
"attribute_name",
")",
"if",
"@server_errors",
".",
"present?",
"# Save the changes",
"run_changed",
"(",
"attribute_name",
")",
"unless",
"Volt",
".",
"in_mode?",
"(",
":no_change_tracking",
")",
"end",
"new_value",
"end"
] | Do the assignment to a model and trigger a changed event | [
"Do",
"the",
"assignment",
"to",
"a",
"model",
"and",
"trigger",
"a",
"changed",
"event"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model.rb#L204-L233 | train |
voltrb/volt | lib/volt/models/model.rb | Volt.Model.read_new_model | def read_new_model(method_name)
if @persistor && @persistor.respond_to?(:read_new_model)
return @persistor.read_new_model(method_name)
else
opts = @options.merge(parent: self, path: path + [method_name])
if method_name.plural?
return new_array_model([], opts)
else
return new_model({}, opts)
end
end
end | ruby | def read_new_model(method_name)
if @persistor && @persistor.respond_to?(:read_new_model)
return @persistor.read_new_model(method_name)
else
opts = @options.merge(parent: self, path: path + [method_name])
if method_name.plural?
return new_array_model([], opts)
else
return new_model({}, opts)
end
end
end | [
"def",
"read_new_model",
"(",
"method_name",
")",
"if",
"@persistor",
"&&",
"@persistor",
".",
"respond_to?",
"(",
":read_new_model",
")",
"return",
"@persistor",
".",
"read_new_model",
"(",
"method_name",
")",
"else",
"opts",
"=",
"@options",
".",
"merge",
"(",
"parent",
":",
"self",
",",
"path",
":",
"path",
"+",
"[",
"method_name",
"]",
")",
"if",
"method_name",
".",
"plural?",
"return",
"new_array_model",
"(",
"[",
"]",
",",
"opts",
")",
"else",
"return",
"new_model",
"(",
"{",
"}",
",",
"opts",
")",
"end",
"end",
"end"
] | Get a new model, make it easy to override | [
"Get",
"a",
"new",
"model",
"make",
"it",
"easy",
"to",
"override"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model.rb#L284-L296 | train |
voltrb/volt | lib/volt/models/model.rb | Volt.Model.update | def update(attrs)
old_attrs = @attributes.dup
Model.no_change_tracking do
assign_all_attributes(attrs, false)
validate!.then do |errs|
if errs && errs.present?
# Revert wholesale
@attributes = old_attrs
Promise.new.resolve(errs)
else
# Persist
persist_changes(nil)
end
end
end
end | ruby | def update(attrs)
old_attrs = @attributes.dup
Model.no_change_tracking do
assign_all_attributes(attrs, false)
validate!.then do |errs|
if errs && errs.present?
# Revert wholesale
@attributes = old_attrs
Promise.new.resolve(errs)
else
# Persist
persist_changes(nil)
end
end
end
end | [
"def",
"update",
"(",
"attrs",
")",
"old_attrs",
"=",
"@attributes",
".",
"dup",
"Model",
".",
"no_change_tracking",
"do",
"assign_all_attributes",
"(",
"attrs",
",",
"false",
")",
"validate!",
".",
"then",
"do",
"|",
"errs",
"|",
"if",
"errs",
"&&",
"errs",
".",
"present?",
"# Revert wholesale",
"@attributes",
"=",
"old_attrs",
"Promise",
".",
"new",
".",
"resolve",
"(",
"errs",
")",
"else",
"# Persist",
"persist_changes",
"(",
"nil",
")",
"end",
"end",
"end",
"end"
] | Update tries to update the model and returns | [
"Update",
"tries",
"to",
"update",
"the",
"model",
"and",
"returns"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model.rb#L361-L377 | train |
voltrb/volt | lib/volt/server/html_parser/view_scope.rb | Volt.ViewScope.close_scope | def close_scope(pop = true)
if pop
scope = @handler.scope.pop
else
scope = @handler.last
end
fail "template path already exists: #{scope.path}" if @handler.templates[scope.path]
template = {
'html' => scope.html
}
if scope.bindings.size > 0
# Add the bindings if there are any
template['bindings'] = scope.bindings
end
@handler.templates[scope.path] = template
end | ruby | def close_scope(pop = true)
if pop
scope = @handler.scope.pop
else
scope = @handler.last
end
fail "template path already exists: #{scope.path}" if @handler.templates[scope.path]
template = {
'html' => scope.html
}
if scope.bindings.size > 0
# Add the bindings if there are any
template['bindings'] = scope.bindings
end
@handler.templates[scope.path] = template
end | [
"def",
"close_scope",
"(",
"pop",
"=",
"true",
")",
"if",
"pop",
"scope",
"=",
"@handler",
".",
"scope",
".",
"pop",
"else",
"scope",
"=",
"@handler",
".",
"last",
"end",
"fail",
"\"template path already exists: #{scope.path}\"",
"if",
"@handler",
".",
"templates",
"[",
"scope",
".",
"path",
"]",
"template",
"=",
"{",
"'html'",
"=>",
"scope",
".",
"html",
"}",
"if",
"scope",
".",
"bindings",
".",
"size",
">",
"0",
"# Add the bindings if there are any",
"template",
"[",
"'bindings'",
"]",
"=",
"scope",
".",
"bindings",
"end",
"@handler",
".",
"templates",
"[",
"scope",
".",
"path",
"]",
"=",
"template",
"end"
] | Called when this scope should be closed out | [
"Called",
"when",
"this",
"scope",
"should",
"be",
"closed",
"out"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/view_scope.rb#L157-L176 | train |
voltrb/volt | lib/volt/helpers/time/duration.rb | Volt.Duration.+ | def +(other)
if other.is_a?(Volt::Duration)
Volt::Duration.new(value + other.value, parts + other.parts)
else
Volt::Duration.new(value + other, parts + [[:seconds, other]])
end
end | ruby | def +(other)
if other.is_a?(Volt::Duration)
Volt::Duration.new(value + other.value, parts + other.parts)
else
Volt::Duration.new(value + other, parts + [[:seconds, other]])
end
end | [
"def",
"+",
"(",
"other",
")",
"if",
"other",
".",
"is_a?",
"(",
"Volt",
"::",
"Duration",
")",
"Volt",
"::",
"Duration",
".",
"new",
"(",
"value",
"+",
"other",
".",
"value",
",",
"parts",
"+",
"other",
".",
"parts",
")",
"else",
"Volt",
"::",
"Duration",
".",
"new",
"(",
"value",
"+",
"other",
",",
"parts",
"+",
"[",
"[",
":seconds",
",",
"other",
"]",
"]",
")",
"end",
"end"
] | Compares with the value on another Duration if Duration is passed
or just compares value with the other object
Adds durations or duration to a VoltTime or seconds to the duration | [
"Compares",
"with",
"the",
"value",
"on",
"another",
"Duration",
"if",
"Duration",
"is",
"passed",
"or",
"just",
"compares",
"value",
"with",
"the",
"other",
"object",
"Adds",
"durations",
"or",
"duration",
"to",
"a",
"VoltTime",
"or",
"seconds",
"to",
"the",
"duration"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/helpers/time/duration.rb#L23-L29 | train |
voltrb/volt | lib/volt/server/html_parser/sandlebars_parser.rb | Volt.SandlebarsParser.start_binding | def start_binding
binding = ''
open_count = 1
# scan until we reach a {{ or }}
loop do
binding << @html.scan_until(/(\{\{|\}\}|\n|\Z)/)
match = @html[1]
if match == '}}'
# close
open_count -= 1
break if open_count == 0
elsif match == '{{'
# open more
open_count += 1
elsif match == "\n" || @html.eos?
# Starting new tag, should be closed before this
# or end of doc before closed binding
raise_parse_error("unclosed binding: {#{binding.strip}")
else
#:nocov:
fail 'should not reach here'
#:nocov:
end
end
binding = binding[0..-3]
@handler.binding(binding) if @handler.respond_to?(:binding)
end | ruby | def start_binding
binding = ''
open_count = 1
# scan until we reach a {{ or }}
loop do
binding << @html.scan_until(/(\{\{|\}\}|\n|\Z)/)
match = @html[1]
if match == '}}'
# close
open_count -= 1
break if open_count == 0
elsif match == '{{'
# open more
open_count += 1
elsif match == "\n" || @html.eos?
# Starting new tag, should be closed before this
# or end of doc before closed binding
raise_parse_error("unclosed binding: {#{binding.strip}")
else
#:nocov:
fail 'should not reach here'
#:nocov:
end
end
binding = binding[0..-3]
@handler.binding(binding) if @handler.respond_to?(:binding)
end | [
"def",
"start_binding",
"binding",
"=",
"''",
"open_count",
"=",
"1",
"# scan until we reach a {{ or }}",
"loop",
"do",
"binding",
"<<",
"@html",
".",
"scan_until",
"(",
"/",
"\\{",
"\\{",
"\\}",
"\\}",
"\\n",
"\\Z",
"/",
")",
"match",
"=",
"@html",
"[",
"1",
"]",
"if",
"match",
"==",
"'}}'",
"# close",
"open_count",
"-=",
"1",
"break",
"if",
"open_count",
"==",
"0",
"elsif",
"match",
"==",
"'{{'",
"# open more",
"open_count",
"+=",
"1",
"elsif",
"match",
"==",
"\"\\n\"",
"||",
"@html",
".",
"eos?",
"# Starting new tag, should be closed before this",
"# or end of doc before closed binding",
"raise_parse_error",
"(",
"\"unclosed binding: {#{binding.strip}\"",
")",
"else",
"#:nocov:",
"fail",
"'should not reach here'",
"#:nocov:",
"end",
"end",
"binding",
"=",
"binding",
"[",
"0",
"..",
"-",
"3",
"]",
"@handler",
".",
"binding",
"(",
"binding",
")",
"if",
"@handler",
".",
"respond_to?",
"(",
":binding",
")",
"end"
] | Findings the end of a binding | [
"Findings",
"the",
"end",
"of",
"a",
"binding"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/sandlebars_parser.rb#L104-L133 | train |
voltrb/volt | lib/volt/server/rack/http_resource.rb | Volt.HttpResource.dispatch_to_controller | def dispatch_to_controller(params, request)
namespace = params[:component] || 'main'
controller_name = params[:controller] + '_controller'
action = params[:action]
namespace_module = Object.const_get(namespace.camelize.to_sym)
klass = namespace_module.const_get(controller_name.camelize.to_sym)
controller = klass.new(@volt_app, params, request)
# Use the 'meta' thread local to set the user_id for Volt.current_user
meta_data = {}
user_id = request.cookies['user_id']
meta_data['user_id'] = user_id if user_id
Thread.current['meta'] = meta_data
controller.perform(action)
end | ruby | def dispatch_to_controller(params, request)
namespace = params[:component] || 'main'
controller_name = params[:controller] + '_controller'
action = params[:action]
namespace_module = Object.const_get(namespace.camelize.to_sym)
klass = namespace_module.const_get(controller_name.camelize.to_sym)
controller = klass.new(@volt_app, params, request)
# Use the 'meta' thread local to set the user_id for Volt.current_user
meta_data = {}
user_id = request.cookies['user_id']
meta_data['user_id'] = user_id if user_id
Thread.current['meta'] = meta_data
controller.perform(action)
end | [
"def",
"dispatch_to_controller",
"(",
"params",
",",
"request",
")",
"namespace",
"=",
"params",
"[",
":component",
"]",
"||",
"'main'",
"controller_name",
"=",
"params",
"[",
":controller",
"]",
"+",
"'_controller'",
"action",
"=",
"params",
"[",
":action",
"]",
"namespace_module",
"=",
"Object",
".",
"const_get",
"(",
"namespace",
".",
"camelize",
".",
"to_sym",
")",
"klass",
"=",
"namespace_module",
".",
"const_get",
"(",
"controller_name",
".",
"camelize",
".",
"to_sym",
")",
"controller",
"=",
"klass",
".",
"new",
"(",
"@volt_app",
",",
"params",
",",
"request",
")",
"# Use the 'meta' thread local to set the user_id for Volt.current_user",
"meta_data",
"=",
"{",
"}",
"user_id",
"=",
"request",
".",
"cookies",
"[",
"'user_id'",
"]",
"meta_data",
"[",
"'user_id'",
"]",
"=",
"user_id",
"if",
"user_id",
"Thread",
".",
"current",
"[",
"'meta'",
"]",
"=",
"meta_data",
"controller",
".",
"perform",
"(",
"action",
")",
"end"
] | Find the correct controller and call the correct action on it.
The controller name and actions need to be set as params for the
matching route | [
"Find",
"the",
"correct",
"controller",
"and",
"call",
"the",
"correct",
"action",
"on",
"it",
".",
"The",
"controller",
"name",
"and",
"actions",
"need",
"to",
"be",
"set",
"as",
"params",
"for",
"the",
"matching",
"route"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/http_resource.rb#L34-L51 | train |
voltrb/volt | lib/volt/page/bindings/each_binding.rb | Volt.EachBinding.update | def update(value)
# Since we're checking things like size, we don't want this to be re-triggered on a
# size change, so we run without tracking.
Computation.run_without_tracking do
# Adjust to the new size
values = current_values(value)
@value = values
remove_listeners
if @value.respond_to?(:on)
@added_listener = @value.on('added') { |position| item_added(position) }
@removed_listener = @value.on('removed') { |position| item_removed(position) }
end
templates_size = nil
values_size = nil
Volt.run_in_mode(:no_model_promises) do
templates_size = @templates.size
unless values.respond_to?(:size)
fail InvalidObjectForEachBinding, "Each binding's require an object that responds to size and [] methods. The binding received: #{values.inspect}"
end
values_size = values.size
end
# Start over, re-create all nodes
(templates_size - 1).downto(0) do |index|
item_removed(index)
end
0.upto(values_size - 1) do |index|
item_added(index)
end
end
end | ruby | def update(value)
# Since we're checking things like size, we don't want this to be re-triggered on a
# size change, so we run without tracking.
Computation.run_without_tracking do
# Adjust to the new size
values = current_values(value)
@value = values
remove_listeners
if @value.respond_to?(:on)
@added_listener = @value.on('added') { |position| item_added(position) }
@removed_listener = @value.on('removed') { |position| item_removed(position) }
end
templates_size = nil
values_size = nil
Volt.run_in_mode(:no_model_promises) do
templates_size = @templates.size
unless values.respond_to?(:size)
fail InvalidObjectForEachBinding, "Each binding's require an object that responds to size and [] methods. The binding received: #{values.inspect}"
end
values_size = values.size
end
# Start over, re-create all nodes
(templates_size - 1).downto(0) do |index|
item_removed(index)
end
0.upto(values_size - 1) do |index|
item_added(index)
end
end
end | [
"def",
"update",
"(",
"value",
")",
"# Since we're checking things like size, we don't want this to be re-triggered on a",
"# size change, so we run without tracking.",
"Computation",
".",
"run_without_tracking",
"do",
"# Adjust to the new size",
"values",
"=",
"current_values",
"(",
"value",
")",
"@value",
"=",
"values",
"remove_listeners",
"if",
"@value",
".",
"respond_to?",
"(",
":on",
")",
"@added_listener",
"=",
"@value",
".",
"on",
"(",
"'added'",
")",
"{",
"|",
"position",
"|",
"item_added",
"(",
"position",
")",
"}",
"@removed_listener",
"=",
"@value",
".",
"on",
"(",
"'removed'",
")",
"{",
"|",
"position",
"|",
"item_removed",
"(",
"position",
")",
"}",
"end",
"templates_size",
"=",
"nil",
"values_size",
"=",
"nil",
"Volt",
".",
"run_in_mode",
"(",
":no_model_promises",
")",
"do",
"templates_size",
"=",
"@templates",
".",
"size",
"unless",
"values",
".",
"respond_to?",
"(",
":size",
")",
"fail",
"InvalidObjectForEachBinding",
",",
"\"Each binding's require an object that responds to size and [] methods. The binding received: #{values.inspect}\"",
"end",
"values_size",
"=",
"values",
".",
"size",
"end",
"# Start over, re-create all nodes",
"(",
"templates_size",
"-",
"1",
")",
".",
"downto",
"(",
"0",
")",
"do",
"|",
"index",
"|",
"item_removed",
"(",
"index",
")",
"end",
"0",
".",
"upto",
"(",
"values_size",
"-",
"1",
")",
"do",
"|",
"index",
"|",
"item_added",
"(",
"index",
")",
"end",
"end",
"end"
] | When a changed event happens, we update to the new size. | [
"When",
"a",
"changed",
"event",
"happens",
"we",
"update",
"to",
"the",
"new",
"size",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/bindings/each_binding.rb#L41-L78 | train |
voltrb/volt | lib/volt/page/bindings/each_binding.rb | Volt.EachBinding.update_indexes_after | def update_indexes_after(start_index)
size = @templates.size
if size > 0
start_index.upto(size - 1) do |index|
@templates[index].context.locals[:_index=].call(index)
end
end
end | ruby | def update_indexes_after(start_index)
size = @templates.size
if size > 0
start_index.upto(size - 1) do |index|
@templates[index].context.locals[:_index=].call(index)
end
end
end | [
"def",
"update_indexes_after",
"(",
"start_index",
")",
"size",
"=",
"@templates",
".",
"size",
"if",
"size",
">",
"0",
"start_index",
".",
"upto",
"(",
"size",
"-",
"1",
")",
"do",
"|",
"index",
"|",
"@templates",
"[",
"index",
"]",
".",
"context",
".",
"locals",
"[",
":_index=",
"]",
".",
"call",
"(",
"index",
")",
"end",
"end",
"end"
] | When items are added or removed in the middle of the list, we need
to update each templates index value. | [
"When",
"items",
"are",
"added",
"or",
"removed",
"in",
"the",
"middle",
"of",
"the",
"list",
"we",
"need",
"to",
"update",
"each",
"templates",
"index",
"value",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/bindings/each_binding.rb#L152-L159 | train |
voltrb/volt | lib/volt/page/bindings/each_binding.rb | Volt.EachBinding.remove | def remove
@computation.stop
@computation = nil
# Clear value
@value = []
@getter = nil
remove_listeners
if @templates
template_count = @templates.size
template_count.times do |index|
item_removed(template_count - index - 1)
end
# @templates.compact.each(&:remove)
@templates = nil
end
super
end | ruby | def remove
@computation.stop
@computation = nil
# Clear value
@value = []
@getter = nil
remove_listeners
if @templates
template_count = @templates.size
template_count.times do |index|
item_removed(template_count - index - 1)
end
# @templates.compact.each(&:remove)
@templates = nil
end
super
end | [
"def",
"remove",
"@computation",
".",
"stop",
"@computation",
"=",
"nil",
"# Clear value",
"@value",
"=",
"[",
"]",
"@getter",
"=",
"nil",
"remove_listeners",
"if",
"@templates",
"template_count",
"=",
"@templates",
".",
"size",
"template_count",
".",
"times",
"do",
"|",
"index",
"|",
"item_removed",
"(",
"template_count",
"-",
"index",
"-",
"1",
")",
"end",
"# @templates.compact.each(&:remove)",
"@templates",
"=",
"nil",
"end",
"super",
"end"
] | When this each_binding is removed, cleanup. | [
"When",
"this",
"each_binding",
"is",
"removed",
"cleanup",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/page/bindings/each_binding.rb#L180-L201 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.rest | def rest(path, params)
endpoints = (params.delete(:only) || [:index, :show, :create, :update, :destroy]).to_a
endpoints = endpoints - params.delete(:except).to_a
endpoints.each do |endpoint|
self.send(('restful_' + endpoint.to_s).to_sym, path, params)
end
end | ruby | def rest(path, params)
endpoints = (params.delete(:only) || [:index, :show, :create, :update, :destroy]).to_a
endpoints = endpoints - params.delete(:except).to_a
endpoints.each do |endpoint|
self.send(('restful_' + endpoint.to_s).to_sym, path, params)
end
end | [
"def",
"rest",
"(",
"path",
",",
"params",
")",
"endpoints",
"=",
"(",
"params",
".",
"delete",
"(",
":only",
")",
"||",
"[",
":index",
",",
":show",
",",
":create",
",",
":update",
",",
":destroy",
"]",
")",
".",
"to_a",
"endpoints",
"=",
"endpoints",
"-",
"params",
".",
"delete",
"(",
":except",
")",
".",
"to_a",
"endpoints",
".",
"each",
"do",
"|",
"endpoint",
"|",
"self",
".",
"send",
"(",
"(",
"'restful_'",
"+",
"endpoint",
".",
"to_s",
")",
".",
"to_sym",
",",
"path",
",",
"params",
")",
"end",
"end"
] | Create rest endpoints | [
"Create",
"rest",
"endpoints"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L93-L99 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.params_to_url | def params_to_url(test_params)
# Extract the desired method from the params
method = test_params.delete(:method) || :client
method = method.to_sym
# Add in underscores
test_params = test_params.each_with_object({}) do |(k, v), obj|
obj[k.to_sym] = v
end
@param_matches[method].each do |param_matcher|
# TODO: Maybe a deep dup?
result, new_params = check_params_match(test_params.dup, param_matcher[0])
return param_matcher[1].call(new_params) if result
end
[nil, nil]
end | ruby | def params_to_url(test_params)
# Extract the desired method from the params
method = test_params.delete(:method) || :client
method = method.to_sym
# Add in underscores
test_params = test_params.each_with_object({}) do |(k, v), obj|
obj[k.to_sym] = v
end
@param_matches[method].each do |param_matcher|
# TODO: Maybe a deep dup?
result, new_params = check_params_match(test_params.dup, param_matcher[0])
return param_matcher[1].call(new_params) if result
end
[nil, nil]
end | [
"def",
"params_to_url",
"(",
"test_params",
")",
"# Extract the desired method from the params",
"method",
"=",
"test_params",
".",
"delete",
"(",
":method",
")",
"||",
":client",
"method",
"=",
"method",
".",
"to_sym",
"# Add in underscores",
"test_params",
"=",
"test_params",
".",
"each_with_object",
"(",
"{",
"}",
")",
"do",
"|",
"(",
"k",
",",
"v",
")",
",",
"obj",
"|",
"obj",
"[",
"k",
".",
"to_sym",
"]",
"=",
"v",
"end",
"@param_matches",
"[",
"method",
"]",
".",
"each",
"do",
"|",
"param_matcher",
"|",
"# TODO: Maybe a deep dup?",
"result",
",",
"new_params",
"=",
"check_params_match",
"(",
"test_params",
".",
"dup",
",",
"param_matcher",
"[",
"0",
"]",
")",
"return",
"param_matcher",
"[",
"1",
"]",
".",
"call",
"(",
"new_params",
")",
"if",
"result",
"end",
"[",
"nil",
",",
"nil",
"]",
"end"
] | Takes in params and generates a path and the remaining params
that should be shown in the url. The extra "unused" params
will be tacked onto the end of the url ?param1=value1, etc...
returns the url and new params, or nil, nil if no match is found. | [
"Takes",
"in",
"params",
"and",
"generates",
"a",
"path",
"and",
"the",
"remaining",
"params",
"that",
"should",
"be",
"shown",
"in",
"the",
"url",
".",
"The",
"extra",
"unused",
"params",
"will",
"be",
"tacked",
"onto",
"the",
"end",
"of",
"the",
"url",
"?param1",
"=",
"value1",
"etc",
"..."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L126-L144 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.url_to_params | def url_to_params(*args)
if args.size < 2
path = args[0]
method = :client
else
path = args[1]
method = args[0].to_sym
end
# First try a direct match
result = @direct_routes[method][path]
return result if result
# Next, split the url and walk the sections
parts = url_parts(path)
match_path(parts, parts, @indirect_routes[method])
end | ruby | def url_to_params(*args)
if args.size < 2
path = args[0]
method = :client
else
path = args[1]
method = args[0].to_sym
end
# First try a direct match
result = @direct_routes[method][path]
return result if result
# Next, split the url and walk the sections
parts = url_parts(path)
match_path(parts, parts, @indirect_routes[method])
end | [
"def",
"url_to_params",
"(",
"*",
"args",
")",
"if",
"args",
".",
"size",
"<",
"2",
"path",
"=",
"args",
"[",
"0",
"]",
"method",
"=",
":client",
"else",
"path",
"=",
"args",
"[",
"1",
"]",
"method",
"=",
"args",
"[",
"0",
"]",
".",
"to_sym",
"end",
"# First try a direct match",
"result",
"=",
"@direct_routes",
"[",
"method",
"]",
"[",
"path",
"]",
"return",
"result",
"if",
"result",
"# Next, split the url and walk the sections",
"parts",
"=",
"url_parts",
"(",
"path",
")",
"match_path",
"(",
"parts",
",",
"parts",
",",
"@indirect_routes",
"[",
"method",
"]",
")",
"end"
] | Takes in a path and returns the matching params.
returns params as a hash | [
"Takes",
"in",
"a",
"path",
"and",
"returns",
"the",
"matching",
"params",
".",
"returns",
"params",
"as",
"a",
"hash"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L148-L165 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.match_path | def match_path(original_parts, remaining_parts, node)
# Take off the top part and get the rest into a new array
# part will be nil if we are out of parts (fancy how that works out, now
# stand in wonder about how much someone thought this through, though
# really I just got lucky)
part, *parts = remaining_parts
if part.nil?
if node[part]
# We found a match, replace the bindings and return
# TODO: Handle nested
setup_bindings_in_params(original_parts, node[part])
else
false
end
else
if (new_node = node[part])
# Direct match for section, continue
result = match_path(original_parts, parts, new_node)
return result if result
end
if (new_node = node['*'])
# Match on binding single section
result = match_path(original_parts, parts, new_node)
return result if result
end
if ((params = node['**']) && params && (params = params[nil]))
# Match on binding multiple sections
result = setup_bindings_in_params(original_parts, params)
return result if result
end
return false
end
end | ruby | def match_path(original_parts, remaining_parts, node)
# Take off the top part and get the rest into a new array
# part will be nil if we are out of parts (fancy how that works out, now
# stand in wonder about how much someone thought this through, though
# really I just got lucky)
part, *parts = remaining_parts
if part.nil?
if node[part]
# We found a match, replace the bindings and return
# TODO: Handle nested
setup_bindings_in_params(original_parts, node[part])
else
false
end
else
if (new_node = node[part])
# Direct match for section, continue
result = match_path(original_parts, parts, new_node)
return result if result
end
if (new_node = node['*'])
# Match on binding single section
result = match_path(original_parts, parts, new_node)
return result if result
end
if ((params = node['**']) && params && (params = params[nil]))
# Match on binding multiple sections
result = setup_bindings_in_params(original_parts, params)
return result if result
end
return false
end
end | [
"def",
"match_path",
"(",
"original_parts",
",",
"remaining_parts",
",",
"node",
")",
"# Take off the top part and get the rest into a new array",
"# part will be nil if we are out of parts (fancy how that works out, now",
"# stand in wonder about how much someone thought this through, though",
"# really I just got lucky)",
"part",
",",
"*",
"parts",
"=",
"remaining_parts",
"if",
"part",
".",
"nil?",
"if",
"node",
"[",
"part",
"]",
"# We found a match, replace the bindings and return",
"# TODO: Handle nested",
"setup_bindings_in_params",
"(",
"original_parts",
",",
"node",
"[",
"part",
"]",
")",
"else",
"false",
"end",
"else",
"if",
"(",
"new_node",
"=",
"node",
"[",
"part",
"]",
")",
"# Direct match for section, continue",
"result",
"=",
"match_path",
"(",
"original_parts",
",",
"parts",
",",
"new_node",
")",
"return",
"result",
"if",
"result",
"end",
"if",
"(",
"new_node",
"=",
"node",
"[",
"'*'",
"]",
")",
"# Match on binding single section",
"result",
"=",
"match_path",
"(",
"original_parts",
",",
"parts",
",",
"new_node",
")",
"return",
"result",
"if",
"result",
"end",
"if",
"(",
"(",
"params",
"=",
"node",
"[",
"'**'",
"]",
")",
"&&",
"params",
"&&",
"(",
"params",
"=",
"params",
"[",
"nil",
"]",
")",
")",
"# Match on binding multiple sections",
"result",
"=",
"setup_bindings_in_params",
"(",
"original_parts",
",",
"params",
")",
"return",
"result",
"if",
"result",
"end",
"return",
"false",
"end",
"end"
] | Recursively walk the @indirect_routes hash, return the params for a route, return
false for non-matches. | [
"Recursively",
"walk",
"the"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L183-L217 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.setup_bindings_in_params | def setup_bindings_in_params(original_parts, params)
# Create a copy of the params we can modify and return
params = params.dup
params.each_pair do |key, value|
if value.is_a?(Fixnum)
# Lookup the param's value in the original url parts
params[key] = original_parts[value]
elsif value.is_a?(Range)
# When doing multiple section bindings, we lookup the parts as a range
# then join them with /
params[key] = original_parts[value].join('/')
end
end
params
end | ruby | def setup_bindings_in_params(original_parts, params)
# Create a copy of the params we can modify and return
params = params.dup
params.each_pair do |key, value|
if value.is_a?(Fixnum)
# Lookup the param's value in the original url parts
params[key] = original_parts[value]
elsif value.is_a?(Range)
# When doing multiple section bindings, we lookup the parts as a range
# then join them with /
params[key] = original_parts[value].join('/')
end
end
params
end | [
"def",
"setup_bindings_in_params",
"(",
"original_parts",
",",
"params",
")",
"# Create a copy of the params we can modify and return",
"params",
"=",
"params",
".",
"dup",
"params",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Fixnum",
")",
"# Lookup the param's value in the original url parts",
"params",
"[",
"key",
"]",
"=",
"original_parts",
"[",
"value",
"]",
"elsif",
"value",
".",
"is_a?",
"(",
"Range",
")",
"# When doing multiple section bindings, we lookup the parts as a range",
"# then join them with /",
"params",
"[",
"key",
"]",
"=",
"original_parts",
"[",
"value",
"]",
".",
"join",
"(",
"'/'",
")",
"end",
"end",
"params",
"end"
] | The params out of match_path will have integers in the params that came from bindings
in the url. This replaces those with the values from the url. | [
"The",
"params",
"out",
"of",
"match_path",
"will",
"have",
"integers",
"in",
"the",
"params",
"that",
"came",
"from",
"bindings",
"in",
"the",
"url",
".",
"This",
"replaces",
"those",
"with",
"the",
"values",
"from",
"the",
"url",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L221-L237 | train |
voltrb/volt | lib/volt/router/routes.rb | Volt.Routes.check_params_match | def check_params_match(test_params, param_matcher)
param_matcher.each_pair do |key, value|
if value.is_a?(Hash)
if test_params[key]
result = check_params_match(test_params[key], value)
if result == false
return false
else
test_params.delete(key)
end
else
# test_params did not have matching key
return false
end
elsif value.nil?
return false unless test_params.key?(key)
else
if test_params[key] == value
test_params.delete(key)
else
return false
end
end
end
[true, test_params]
end | ruby | def check_params_match(test_params, param_matcher)
param_matcher.each_pair do |key, value|
if value.is_a?(Hash)
if test_params[key]
result = check_params_match(test_params[key], value)
if result == false
return false
else
test_params.delete(key)
end
else
# test_params did not have matching key
return false
end
elsif value.nil?
return false unless test_params.key?(key)
else
if test_params[key] == value
test_params.delete(key)
else
return false
end
end
end
[true, test_params]
end | [
"def",
"check_params_match",
"(",
"test_params",
",",
"param_matcher",
")",
"param_matcher",
".",
"each_pair",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"if",
"test_params",
"[",
"key",
"]",
"result",
"=",
"check_params_match",
"(",
"test_params",
"[",
"key",
"]",
",",
"value",
")",
"if",
"result",
"==",
"false",
"return",
"false",
"else",
"test_params",
".",
"delete",
"(",
"key",
")",
"end",
"else",
"# test_params did not have matching key",
"return",
"false",
"end",
"elsif",
"value",
".",
"nil?",
"return",
"false",
"unless",
"test_params",
".",
"key?",
"(",
"key",
")",
"else",
"if",
"test_params",
"[",
"key",
"]",
"==",
"value",
"test_params",
".",
"delete",
"(",
"key",
")",
"else",
"return",
"false",
"end",
"end",
"end",
"[",
"true",
",",
"test_params",
"]",
"end"
] | Takes in a hash of params and checks to make sure keys in param_matcher
are in test_params. Checks for equal value unless value in param_matcher
is nil.
returns false or true, new_params - where the new params are a the params not
used in the basic match. Later some of these may be inserted into the url. | [
"Takes",
"in",
"a",
"hash",
"of",
"params",
"and",
"checks",
"to",
"make",
"sure",
"keys",
"in",
"param_matcher",
"are",
"in",
"test_params",
".",
"Checks",
"for",
"equal",
"value",
"unless",
"value",
"in",
"param_matcher",
"is",
"nil",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/router/routes.rb#L323-L350 | train |
voltrb/volt | lib/volt/models/associations.rb | Volt.Associations.association_with_root_model | def association_with_root_model(method_name)
persistor = self.persistor || (respond_to?(:save_to) && save_to && save_to.persistor)
# Check if we are on the store collection
if persistor.is_a?(Volt::Persistors::ModelStore) ||
persistor.is_a?(Volt::Persistors::Page)
# Get the root node
root = persistor.try(:root_model)
# Yield to the block passing in the root node
yield(root)
else
# raise an error about the method not being supported on this collection
fail "#{method_name} currently only works on the store and page collection (support for other collections coming soon)"
end
end | ruby | def association_with_root_model(method_name)
persistor = self.persistor || (respond_to?(:save_to) && save_to && save_to.persistor)
# Check if we are on the store collection
if persistor.is_a?(Volt::Persistors::ModelStore) ||
persistor.is_a?(Volt::Persistors::Page)
# Get the root node
root = persistor.try(:root_model)
# Yield to the block passing in the root node
yield(root)
else
# raise an error about the method not being supported on this collection
fail "#{method_name} currently only works on the store and page collection (support for other collections coming soon)"
end
end | [
"def",
"association_with_root_model",
"(",
"method_name",
")",
"persistor",
"=",
"self",
".",
"persistor",
"||",
"(",
"respond_to?",
"(",
":save_to",
")",
"&&",
"save_to",
"&&",
"save_to",
".",
"persistor",
")",
"# Check if we are on the store collection",
"if",
"persistor",
".",
"is_a?",
"(",
"Volt",
"::",
"Persistors",
"::",
"ModelStore",
")",
"||",
"persistor",
".",
"is_a?",
"(",
"Volt",
"::",
"Persistors",
"::",
"Page",
")",
"# Get the root node",
"root",
"=",
"persistor",
".",
"try",
"(",
":root_model",
")",
"# Yield to the block passing in the root node",
"yield",
"(",
"root",
")",
"else",
"# raise an error about the method not being supported on this collection",
"fail",
"\"#{method_name} currently only works on the store and page collection (support for other collections coming soon)\"",
"end",
"end"
] | Currently the has_many and belongs_to associations only work on the store collection,
this method checks to make sure we are on store and returns the root reference to it. | [
"Currently",
"the",
"has_many",
"and",
"belongs_to",
"associations",
"only",
"work",
"on",
"the",
"store",
"collection",
"this",
"method",
"checks",
"to",
"make",
"sure",
"we",
"are",
"on",
"store",
"and",
"returns",
"the",
"root",
"reference",
"to",
"it",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/associations.rb#L77-L92 | train |
voltrb/volt | lib/volt/server/forking_server.rb | Volt.ForkingServer.boot_error | def boot_error(error)
msg = error.inspect
if error.respond_to?(:backtrace)
msg << "\n" + error.backtrace.join("\n")
end
Volt.logger.error(msg)
# Only require when needed
require 'cgi'
@rack_app = Proc.new do
path = File.join(File.dirname(__FILE__), "forking_server/boot_error.html.erb")
html = File.read(path)
error_page = ERB.new(html, nil, '-').result(binding)
[500, {"Content-Type" => "text/html"}, error_page]
end
@dispatcher = ErrorDispatcher.new
end | ruby | def boot_error(error)
msg = error.inspect
if error.respond_to?(:backtrace)
msg << "\n" + error.backtrace.join("\n")
end
Volt.logger.error(msg)
# Only require when needed
require 'cgi'
@rack_app = Proc.new do
path = File.join(File.dirname(__FILE__), "forking_server/boot_error.html.erb")
html = File.read(path)
error_page = ERB.new(html, nil, '-').result(binding)
[500, {"Content-Type" => "text/html"}, error_page]
end
@dispatcher = ErrorDispatcher.new
end | [
"def",
"boot_error",
"(",
"error",
")",
"msg",
"=",
"error",
".",
"inspect",
"if",
"error",
".",
"respond_to?",
"(",
":backtrace",
")",
"msg",
"<<",
"\"\\n\"",
"+",
"error",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"end",
"Volt",
".",
"logger",
".",
"error",
"(",
"msg",
")",
"# Only require when needed",
"require",
"'cgi'",
"@rack_app",
"=",
"Proc",
".",
"new",
"do",
"path",
"=",
"File",
".",
"join",
"(",
"File",
".",
"dirname",
"(",
"__FILE__",
")",
",",
"\"forking_server/boot_error.html.erb\"",
")",
"html",
"=",
"File",
".",
"read",
"(",
"path",
")",
"error_page",
"=",
"ERB",
".",
"new",
"(",
"html",
",",
"nil",
",",
"'-'",
")",
".",
"result",
"(",
"binding",
")",
"[",
"500",
",",
"{",
"\"Content-Type\"",
"=>",
"\"text/html\"",
"}",
",",
"error_page",
"]",
"end",
"@dispatcher",
"=",
"ErrorDispatcher",
".",
"new",
"end"
] | called from the child when the boot failes. Sets up an error page rack
app to show the user the error and handle reloading requests. | [
"called",
"from",
"the",
"child",
"when",
"the",
"boot",
"failes",
".",
"Sets",
"up",
"an",
"error",
"page",
"rack",
"app",
"to",
"show",
"the",
"user",
"the",
"error",
"and",
"handle",
"reloading",
"requests",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/forking_server.rb#L102-L120 | train |
voltrb/volt | lib/volt/server/html_parser/attribute_scope.rb | Volt.AttributeScope.process_attributes | def process_attributes(tag_name, attributes)
new_attributes = attributes.dup
attributes.each_pair do |name, value|
if name[0..1] == 'e-'
process_event_binding(tag_name, new_attributes, name, value)
else
process_attribute(tag_name, new_attributes, name, value)
end
end
new_attributes
end | ruby | def process_attributes(tag_name, attributes)
new_attributes = attributes.dup
attributes.each_pair do |name, value|
if name[0..1] == 'e-'
process_event_binding(tag_name, new_attributes, name, value)
else
process_attribute(tag_name, new_attributes, name, value)
end
end
new_attributes
end | [
"def",
"process_attributes",
"(",
"tag_name",
",",
"attributes",
")",
"new_attributes",
"=",
"attributes",
".",
"dup",
"attributes",
".",
"each_pair",
"do",
"|",
"name",
",",
"value",
"|",
"if",
"name",
"[",
"0",
"..",
"1",
"]",
"==",
"'e-'",
"process_event_binding",
"(",
"tag_name",
",",
"new_attributes",
",",
"name",
",",
"value",
")",
"else",
"process_attribute",
"(",
"tag_name",
",",
"new_attributes",
",",
"name",
",",
"value",
")",
"end",
"end",
"new_attributes",
"end"
] | Take the attributes and create any bindings | [
"Take",
"the",
"attributes",
"and",
"create",
"any",
"bindings"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/attribute_scope.rb#L29-L41 | train |
voltrb/volt | lib/volt/server/html_parser/attribute_scope.rb | Volt.AttributeScope.binding_parts_and_count | def binding_parts_and_count(value)
if value.is_a?(String)
parts = value.split(/(\{\{[^\}]+\}\})/).reject(&:blank?)
else
parts = ['']
end
binding_count = parts.count { |p| p[0] == '{' && p[1] == '{' && p[-2] == '}' && p[-1] == '}' }
[parts, binding_count]
end | ruby | def binding_parts_and_count(value)
if value.is_a?(String)
parts = value.split(/(\{\{[^\}]+\}\})/).reject(&:blank?)
else
parts = ['']
end
binding_count = parts.count { |p| p[0] == '{' && p[1] == '{' && p[-2] == '}' && p[-1] == '}' }
[parts, binding_count]
end | [
"def",
"binding_parts_and_count",
"(",
"value",
")",
"if",
"value",
".",
"is_a?",
"(",
"String",
")",
"parts",
"=",
"value",
".",
"split",
"(",
"/",
"\\{",
"\\{",
"\\}",
"\\}",
"\\}",
"/",
")",
".",
"reject",
"(",
":blank?",
")",
"else",
"parts",
"=",
"[",
"''",
"]",
"end",
"binding_count",
"=",
"parts",
".",
"count",
"{",
"|",
"p",
"|",
"p",
"[",
"0",
"]",
"==",
"'{'",
"&&",
"p",
"[",
"1",
"]",
"==",
"'{'",
"&&",
"p",
"[",
"-",
"2",
"]",
"==",
"'}'",
"&&",
"p",
"[",
"-",
"1",
"]",
"==",
"'}'",
"}",
"[",
"parts",
",",
"binding_count",
"]",
"end"
] | Takes a string and splits on bindings, returns the string split on bindings
and the number of bindings. | [
"Takes",
"a",
"string",
"and",
"splits",
"on",
"bindings",
"returns",
"the",
"string",
"split",
"on",
"bindings",
"and",
"the",
"number",
"of",
"bindings",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/attribute_scope.rb#L63-L72 | train |
voltrb/volt | lib/volt/server/html_parser/component_view_scope.rb | Volt.ComponentViewScope.close_scope | def close_scope
binding_number = @handler.scope[-2].binding_number
@handler.scope[-2].binding_number += 1
@path += "/__template/#{binding_number}"
super
@handler.html << "<!-- $#{binding_number} --><!-- $/#{binding_number} -->"
@handler.scope.last.save_binding(binding_number, "lambda { |__p, __t, __c, __id| Volt::ComponentBinding.new(__p, __t, __c, __id, #{@binding_in_path.inspect}, Proc.new { [#{@arguments}] }, #{@path.inspect}) }")
end | ruby | def close_scope
binding_number = @handler.scope[-2].binding_number
@handler.scope[-2].binding_number += 1
@path += "/__template/#{binding_number}"
super
@handler.html << "<!-- $#{binding_number} --><!-- $/#{binding_number} -->"
@handler.scope.last.save_binding(binding_number, "lambda { |__p, __t, __c, __id| Volt::ComponentBinding.new(__p, __t, __c, __id, #{@binding_in_path.inspect}, Proc.new { [#{@arguments}] }, #{@path.inspect}) }")
end | [
"def",
"close_scope",
"binding_number",
"=",
"@handler",
".",
"scope",
"[",
"-",
"2",
"]",
".",
"binding_number",
"@handler",
".",
"scope",
"[",
"-",
"2",
"]",
".",
"binding_number",
"+=",
"1",
"@path",
"+=",
"\"/__template/#{binding_number}\"",
"super",
"@handler",
".",
"html",
"<<",
"\"<!-- $#{binding_number} --><!-- $/#{binding_number} -->\"",
"@handler",
".",
"scope",
".",
"last",
".",
"save_binding",
"(",
"binding_number",
",",
"\"lambda { |__p, __t, __c, __id| Volt::ComponentBinding.new(__p, __t, __c, __id, #{@binding_in_path.inspect}, Proc.new { [#{@arguments}] }, #{@path.inspect}) }\"",
")",
"end"
] | The path passed in is the path used to lookup view's. The path from the tag is passed in
as tag_name | [
"The",
"path",
"passed",
"in",
"is",
"the",
"path",
"used",
"to",
"lookup",
"view",
"s",
".",
"The",
"path",
"from",
"the",
"tag",
"is",
"passed",
"in",
"as",
"tag_name"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/component_view_scope.rb#L56-L65 | train |
voltrb/volt | lib/volt/server/rack/asset_files.rb | Volt.AssetFiles.javascript_tags | def javascript_tags(volt_app)
@opal_tag_generator ||= Opal::Server::Index.new(nil, volt_app.opal_files.server)
javascript_files = []
@assets.each do |type, path|
case type
when :folder
# for a folder, we search for all .js files and return a tag for them
base_path = base(path)
javascript_files += Dir["#{path}/**/*.js"].sort.map do |folder|
# Grab the component folder/assets/js/file.js
local_path = folder[path.size..-1]
@app_url + '/' + base_path + local_path
end
when :javascript_file
# javascript_file is a cdn path to a JS file
javascript_files << path
end
end
javascript_files = javascript_files.uniq
scripts = javascript_files.map {|url| "<script src=\"#{url}\"></script>" }
# Include volt itself. Unless we are running with MAPS=all, just include
# the main file without sourcemaps.
volt_path = 'volt/volt/app'
if ENV['MAPS'] == 'all'
scripts << @opal_tag_generator.javascript_include_tag(volt_path)
else
scripts << "<script src=\"#{volt_app.app_url}/#{volt_path}.js\"></script>"
scripts << "<script>#{Opal::Processor.load_asset_code(volt_app.sprockets, volt_path)}</script>"
end
scripts << @opal_tag_generator.javascript_include_tag('components/main')
scripts.join("\n")
end | ruby | def javascript_tags(volt_app)
@opal_tag_generator ||= Opal::Server::Index.new(nil, volt_app.opal_files.server)
javascript_files = []
@assets.each do |type, path|
case type
when :folder
# for a folder, we search for all .js files and return a tag for them
base_path = base(path)
javascript_files += Dir["#{path}/**/*.js"].sort.map do |folder|
# Grab the component folder/assets/js/file.js
local_path = folder[path.size..-1]
@app_url + '/' + base_path + local_path
end
when :javascript_file
# javascript_file is a cdn path to a JS file
javascript_files << path
end
end
javascript_files = javascript_files.uniq
scripts = javascript_files.map {|url| "<script src=\"#{url}\"></script>" }
# Include volt itself. Unless we are running with MAPS=all, just include
# the main file without sourcemaps.
volt_path = 'volt/volt/app'
if ENV['MAPS'] == 'all'
scripts << @opal_tag_generator.javascript_include_tag(volt_path)
else
scripts << "<script src=\"#{volt_app.app_url}/#{volt_path}.js\"></script>"
scripts << "<script>#{Opal::Processor.load_asset_code(volt_app.sprockets, volt_path)}</script>"
end
scripts << @opal_tag_generator.javascript_include_tag('components/main')
scripts.join("\n")
end | [
"def",
"javascript_tags",
"(",
"volt_app",
")",
"@opal_tag_generator",
"||=",
"Opal",
"::",
"Server",
"::",
"Index",
".",
"new",
"(",
"nil",
",",
"volt_app",
".",
"opal_files",
".",
"server",
")",
"javascript_files",
"=",
"[",
"]",
"@assets",
".",
"each",
"do",
"|",
"type",
",",
"path",
"|",
"case",
"type",
"when",
":folder",
"# for a folder, we search for all .js files and return a tag for them",
"base_path",
"=",
"base",
"(",
"path",
")",
"javascript_files",
"+=",
"Dir",
"[",
"\"#{path}/**/*.js\"",
"]",
".",
"sort",
".",
"map",
"do",
"|",
"folder",
"|",
"# Grab the component folder/assets/js/file.js",
"local_path",
"=",
"folder",
"[",
"path",
".",
"size",
"..",
"-",
"1",
"]",
"@app_url",
"+",
"'/'",
"+",
"base_path",
"+",
"local_path",
"end",
"when",
":javascript_file",
"# javascript_file is a cdn path to a JS file",
"javascript_files",
"<<",
"path",
"end",
"end",
"javascript_files",
"=",
"javascript_files",
".",
"uniq",
"scripts",
"=",
"javascript_files",
".",
"map",
"{",
"|",
"url",
"|",
"\"<script src=\\\"#{url}\\\"></script>\"",
"}",
"# Include volt itself. Unless we are running with MAPS=all, just include",
"# the main file without sourcemaps.",
"volt_path",
"=",
"'volt/volt/app'",
"if",
"ENV",
"[",
"'MAPS'",
"]",
"==",
"'all'",
"scripts",
"<<",
"@opal_tag_generator",
".",
"javascript_include_tag",
"(",
"volt_path",
")",
"else",
"scripts",
"<<",
"\"<script src=\\\"#{volt_app.app_url}/#{volt_path}.js\\\"></script>\"",
"scripts",
"<<",
"\"<script>#{Opal::Processor.load_asset_code(volt_app.sprockets, volt_path)}</script>\"",
"end",
"scripts",
"<<",
"@opal_tag_generator",
".",
"javascript_include_tag",
"(",
"'components/main'",
")",
"scripts",
".",
"join",
"(",
"\"\\n\"",
")",
"end"
] | Returns script tags that should be included | [
"Returns",
"script",
"tags",
"that",
"should",
"be",
"included"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/asset_files.rb#L125-L162 | train |
voltrb/volt | lib/volt/server/rack/asset_files.rb | Volt.AssetFiles.css | def css
css_files = []
@assets.each do |type, path|
case type
when :folder
# Don't import any css/scss files that start with an underscore, so scss partials
# aren't imported by default:
# http://sass-lang.com/guide
base_path = base(path)
css_files += Dir["#{path}/**/[^_]*.{css,scss,sass}"].sort.map do |folder|
local_path = folder[path.size..-1].gsub(/[.](scss|sass)$/, '')
css_path = @app_url + '/' + base_path + local_path
css_path += '.css' unless css_path =~ /[.]css$/
css_path
end
when :css_file
css_files << path
end
end
css_files.uniq
end | ruby | def css
css_files = []
@assets.each do |type, path|
case type
when :folder
# Don't import any css/scss files that start with an underscore, so scss partials
# aren't imported by default:
# http://sass-lang.com/guide
base_path = base(path)
css_files += Dir["#{path}/**/[^_]*.{css,scss,sass}"].sort.map do |folder|
local_path = folder[path.size..-1].gsub(/[.](scss|sass)$/, '')
css_path = @app_url + '/' + base_path + local_path
css_path += '.css' unless css_path =~ /[.]css$/
css_path
end
when :css_file
css_files << path
end
end
css_files.uniq
end | [
"def",
"css",
"css_files",
"=",
"[",
"]",
"@assets",
".",
"each",
"do",
"|",
"type",
",",
"path",
"|",
"case",
"type",
"when",
":folder",
"# Don't import any css/scss files that start with an underscore, so scss partials",
"# aren't imported by default:",
"# http://sass-lang.com/guide",
"base_path",
"=",
"base",
"(",
"path",
")",
"css_files",
"+=",
"Dir",
"[",
"\"#{path}/**/[^_]*.{css,scss,sass}\"",
"]",
".",
"sort",
".",
"map",
"do",
"|",
"folder",
"|",
"local_path",
"=",
"folder",
"[",
"path",
".",
"size",
"..",
"-",
"1",
"]",
".",
"gsub",
"(",
"/",
"/",
",",
"''",
")",
"css_path",
"=",
"@app_url",
"+",
"'/'",
"+",
"base_path",
"+",
"local_path",
"css_path",
"+=",
"'.css'",
"unless",
"css_path",
"=~",
"/",
"/",
"css_path",
"end",
"when",
":css_file",
"css_files",
"<<",
"path",
"end",
"end",
"css_files",
".",
"uniq",
"end"
] | Returns an array of all css files that should be included. | [
"Returns",
"an",
"array",
"of",
"all",
"css",
"files",
"that",
"should",
"be",
"included",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/asset_files.rb#L172-L193 | train |
voltrb/volt | lib/volt/utils/generic_pool.rb | Volt.GenericPool.lookup_without_generate | def lookup_without_generate(*args)
section = @pool
args.each_with_index do |arg, index|
section = section[arg]
return nil unless section
end
section
end | ruby | def lookup_without_generate(*args)
section = @pool
args.each_with_index do |arg, index|
section = section[arg]
return nil unless section
end
section
end | [
"def",
"lookup_without_generate",
"(",
"*",
"args",
")",
"section",
"=",
"@pool",
"args",
".",
"each_with_index",
"do",
"|",
"arg",
",",
"index",
"|",
"section",
"=",
"section",
"[",
"arg",
"]",
"return",
"nil",
"unless",
"section",
"end",
"section",
"end"
] | Looks up the path without generating a new one | [
"Looks",
"up",
"the",
"path",
"without",
"generating",
"a",
"new",
"one"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/utils/generic_pool.rb#L46-L55 | train |
voltrb/volt | lib/volt/models/errors.rb | Volt.Errors.merge! | def merge!(errors)
if errors
errors.each_pair do |field, messages|
messages.each do |message|
add(field, message)
end
end
end
end | ruby | def merge!(errors)
if errors
errors.each_pair do |field, messages|
messages.each do |message|
add(field, message)
end
end
end
end | [
"def",
"merge!",
"(",
"errors",
")",
"if",
"errors",
"errors",
".",
"each_pair",
"do",
"|",
"field",
",",
"messages",
"|",
"messages",
".",
"each",
"do",
"|",
"message",
"|",
"add",
"(",
"field",
",",
"message",
")",
"end",
"end",
"end",
"end"
] | Merge another set of errors in | [
"Merge",
"another",
"set",
"of",
"errors",
"in"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/errors.rb#L11-L19 | train |
voltrb/volt | lib/volt/server/html_parser/view_handler.rb | Volt.ViewHandler.link_asset | def link_asset(url, link=true)
if @sprockets_context
# Getting the asset_path also links to the context.
linked_url = @sprockets_context.asset_path(url)
else
# When compiling on the server, we don't use sprockets (atm), so the
# context won't exist. Typically compiling on the server is just used
# to test, so we simply return the url.
linked_url = url
end
last << url if link
linked_url
end | ruby | def link_asset(url, link=true)
if @sprockets_context
# Getting the asset_path also links to the context.
linked_url = @sprockets_context.asset_path(url)
else
# When compiling on the server, we don't use sprockets (atm), so the
# context won't exist. Typically compiling on the server is just used
# to test, so we simply return the url.
linked_url = url
end
last << url if link
linked_url
end | [
"def",
"link_asset",
"(",
"url",
",",
"link",
"=",
"true",
")",
"if",
"@sprockets_context",
"# Getting the asset_path also links to the context.",
"linked_url",
"=",
"@sprockets_context",
".",
"asset_path",
"(",
"url",
")",
"else",
"# When compiling on the server, we don't use sprockets (atm), so the",
"# context won't exist. Typically compiling on the server is just used",
"# to test, so we simply return the url.",
"linked_url",
"=",
"url",
"end",
"last",
"<<",
"url",
"if",
"link",
"linked_url",
"end"
] | Called from the view scope when an asset_url binding is hit. | [
"Called",
"from",
"the",
"view",
"scope",
"when",
"an",
"asset_url",
"binding",
"is",
"hit",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/html_parser/view_handler.rb#L92-L106 | train |
voltrb/volt | lib/volt/server/rack/component_code.rb | Volt.ComponentCode.code | def code
# Start with config code
initializer_code = @client ? generate_config_code : ''
component_code = ''
asset_files = AssetFiles.from_cache(@volt_app.app_url, @component_name, @component_paths)
asset_files.component_paths.each do |component_path, component_name|
comp_template = ComponentTemplates.new(component_path, component_name, @client)
initializer_code << comp_template.initializer_code + "\n\n"
component_code << comp_template.component_code + "\n\n"
end
initializer_code + component_code
end | ruby | def code
# Start with config code
initializer_code = @client ? generate_config_code : ''
component_code = ''
asset_files = AssetFiles.from_cache(@volt_app.app_url, @component_name, @component_paths)
asset_files.component_paths.each do |component_path, component_name|
comp_template = ComponentTemplates.new(component_path, component_name, @client)
initializer_code << comp_template.initializer_code + "\n\n"
component_code << comp_template.component_code + "\n\n"
end
initializer_code + component_code
end | [
"def",
"code",
"# Start with config code",
"initializer_code",
"=",
"@client",
"?",
"generate_config_code",
":",
"''",
"component_code",
"=",
"''",
"asset_files",
"=",
"AssetFiles",
".",
"from_cache",
"(",
"@volt_app",
".",
"app_url",
",",
"@component_name",
",",
"@component_paths",
")",
"asset_files",
".",
"component_paths",
".",
"each",
"do",
"|",
"component_path",
",",
"component_name",
"|",
"comp_template",
"=",
"ComponentTemplates",
".",
"new",
"(",
"component_path",
",",
"component_name",
",",
"@client",
")",
"initializer_code",
"<<",
"comp_template",
".",
"initializer_code",
"+",
"\"\\n\\n\"",
"component_code",
"<<",
"comp_template",
".",
"component_code",
"+",
"\"\\n\\n\"",
"end",
"initializer_code",
"+",
"component_code",
"end"
] | The client argument is for if this code is being generated for the client | [
"The",
"client",
"argument",
"is",
"for",
"if",
"this",
"code",
"is",
"being",
"generated",
"for",
"the",
"client"
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/server/rack/component_code.rb#L17-L30 | train |
voltrb/volt | lib/volt/models/model_wrapper.rb | Volt.ModelWrapper.wrap_value | def wrap_value(value, lookup)
if value.is_a?(Array)
new_array_model(value, @options.merge(parent: self, path: path + lookup))
elsif value.is_a?(Hash)
new_model(value, @options.merge(parent: self, path: path + lookup))
else
value
end
end | ruby | def wrap_value(value, lookup)
if value.is_a?(Array)
new_array_model(value, @options.merge(parent: self, path: path + lookup))
elsif value.is_a?(Hash)
new_model(value, @options.merge(parent: self, path: path + lookup))
else
value
end
end | [
"def",
"wrap_value",
"(",
"value",
",",
"lookup",
")",
"if",
"value",
".",
"is_a?",
"(",
"Array",
")",
"new_array_model",
"(",
"value",
",",
"@options",
".",
"merge",
"(",
"parent",
":",
"self",
",",
"path",
":",
"path",
"+",
"lookup",
")",
")",
"elsif",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"new_model",
"(",
"value",
",",
"@options",
".",
"merge",
"(",
"parent",
":",
"self",
",",
"path",
":",
"path",
"+",
"lookup",
")",
")",
"else",
"value",
"end",
"end"
] | For cretain values, we wrap them to make the behave as a
model. | [
"For",
"cretain",
"values",
"we",
"wrap",
"them",
"to",
"make",
"the",
"behave",
"as",
"a",
"model",
"."
] | f942b92385adbc894ee4a37903ee6a9c1a65e9a4 | https://github.com/voltrb/volt/blob/f942b92385adbc894ee4a37903ee6a9c1a65e9a4/lib/volt/models/model_wrapper.rb#L5-L13 | train |
jfairbank/chroma | lib/chroma/harmonies.rb | Chroma.Harmonies.analogous | def analogous(options = {})
size = options[:size] || 6
slices = options[:slice_by] || 30
hsl = @color.hsl
part = 360 / slices
hsl.h = ((hsl.h - (part * size >> 1)) + 720) % 360
palette = (size - 1).times.reduce([@color]) do |arr, n|
hsl.h = (hsl.h + part) % 360
arr << Color.new(hsl, @color.format)
end
with_reformat(palette, options[:as])
end | ruby | def analogous(options = {})
size = options[:size] || 6
slices = options[:slice_by] || 30
hsl = @color.hsl
part = 360 / slices
hsl.h = ((hsl.h - (part * size >> 1)) + 720) % 360
palette = (size - 1).times.reduce([@color]) do |arr, n|
hsl.h = (hsl.h + part) % 360
arr << Color.new(hsl, @color.format)
end
with_reformat(palette, options[:as])
end | [
"def",
"analogous",
"(",
"options",
"=",
"{",
"}",
")",
"size",
"=",
"options",
"[",
":size",
"]",
"||",
"6",
"slices",
"=",
"options",
"[",
":slice_by",
"]",
"||",
"30",
"hsl",
"=",
"@color",
".",
"hsl",
"part",
"=",
"360",
"/",
"slices",
"hsl",
".",
"h",
"=",
"(",
"(",
"hsl",
".",
"h",
"-",
"(",
"part",
"*",
"size",
">>",
"1",
")",
")",
"+",
"720",
")",
"%",
"360",
"palette",
"=",
"(",
"size",
"-",
"1",
")",
".",
"times",
".",
"reduce",
"(",
"[",
"@color",
"]",
")",
"do",
"|",
"arr",
",",
"n",
"|",
"hsl",
".",
"h",
"=",
"(",
"hsl",
".",
"h",
"+",
"part",
")",
"%",
"360",
"arr",
"<<",
"Color",
".",
"new",
"(",
"hsl",
",",
"@color",
".",
"format",
")",
"end",
"with_reformat",
"(",
"palette",
",",
"options",
"[",
":as",
"]",
")",
"end"
] | Generate an analogous palette.
@example
'red'.paint.palette.analogous #=> [red, #ff0066, #ff0033, red, #ff3300, #ff6600]
'red'.paint.palette.analogous(as: :hex) #=> ['#f00', '#f06', '#f03', '#f00', '#f30', '#f60']
'red'.paint.palette.analogous(size: 3) #=> [red, #ff001a, #ff1a00]
'red'.paint.palette.analogous(size: 3, slice_by: 60) #=> [red, #ff000d, #ff0d00]
@param options [Hash]
@option options :size [Symbol] (6) number of results to return
@option options :slice_by [Symbol] (30)
the angle in degrees to slice the hue circle per color
@option options :as [Symbol] (nil) optional format to output colors as strings
@return [Array<Color>, Array<String>] depending on presence of `options[:as]` | [
"Generate",
"an",
"analogous",
"palette",
"."
] | acbb19f98172c969ba887ab5cee3c1e12e125a9c | https://github.com/jfairbank/chroma/blob/acbb19f98172c969ba887ab5cee3c1e12e125a9c/lib/chroma/harmonies.rb#L79-L93 | train |
jfairbank/chroma | lib/chroma/harmonies.rb | Chroma.Harmonies.monochromatic | def monochromatic(options = {})
size = options[:size] || 6
h, s, v = @color.hsv
modification = 1.0 / size
palette = size.times.map do
Color.new(ColorModes::Hsv.new(h, s, v), @color.format).tap do
v = (v + modification) % 1
end
end
with_reformat(palette, options[:as])
end | ruby | def monochromatic(options = {})
size = options[:size] || 6
h, s, v = @color.hsv
modification = 1.0 / size
palette = size.times.map do
Color.new(ColorModes::Hsv.new(h, s, v), @color.format).tap do
v = (v + modification) % 1
end
end
with_reformat(palette, options[:as])
end | [
"def",
"monochromatic",
"(",
"options",
"=",
"{",
"}",
")",
"size",
"=",
"options",
"[",
":size",
"]",
"||",
"6",
"h",
",",
"s",
",",
"v",
"=",
"@color",
".",
"hsv",
"modification",
"=",
"1.0",
"/",
"size",
"palette",
"=",
"size",
".",
"times",
".",
"map",
"do",
"Color",
".",
"new",
"(",
"ColorModes",
"::",
"Hsv",
".",
"new",
"(",
"h",
",",
"s",
",",
"v",
")",
",",
"@color",
".",
"format",
")",
".",
"tap",
"do",
"v",
"=",
"(",
"v",
"+",
"modification",
")",
"%",
"1",
"end",
"end",
"with_reformat",
"(",
"palette",
",",
"options",
"[",
":as",
"]",
")",
"end"
] | Generate a monochromatic palette.
@example
'red'.paint.palette.monochromatic #=> [red, #2a0000, #550000, maroon, #aa0000, #d40000]
'red'.paint.palette.monochromatic(as: :hex) #=> ['#ff0000', '#2a0000', '#550000', '#800000', '#aa0000', '#d40000']
'red'.paint.palette.monochromatic(size: 3) #=> [red, #550000, #aa0000]
@param options [Hash]
@option options :size [Symbol] (6) number of results to return
@option options :as [Symbol] (nil) optional format to output colors as strings
@return [Array<Color>, Array<String>] depending on presence of `options[:as]` | [
"Generate",
"a",
"monochromatic",
"palette",
"."
] | acbb19f98172c969ba887ab5cee3c1e12e125a9c | https://github.com/jfairbank/chroma/blob/acbb19f98172c969ba887ab5cee3c1e12e125a9c/lib/chroma/harmonies.rb#L106-L119 | train |
cookpad/barbeque | lib/barbeque/message_queue.rb | Barbeque.MessageQueue.dequeue | def dequeue
loop do
return nil if @stop
message = receive_message
if message
if message.valid?
return message
else
delete_message(message)
end
end
end
end | ruby | def dequeue
loop do
return nil if @stop
message = receive_message
if message
if message.valid?
return message
else
delete_message(message)
end
end
end
end | [
"def",
"dequeue",
"loop",
"do",
"return",
"nil",
"if",
"@stop",
"message",
"=",
"receive_message",
"if",
"message",
"if",
"message",
".",
"valid?",
"return",
"message",
"else",
"delete_message",
"(",
"message",
")",
"end",
"end",
"end",
"end"
] | Receive a message from SQS queue.
@return [Barbeque::Message::Base] | [
"Receive",
"a",
"message",
"from",
"SQS",
"queue",
"."
] | 2c719e278e3dc0b3f2f852e794ee71326a446696 | https://github.com/cookpad/barbeque/blob/2c719e278e3dc0b3f2f852e794ee71326a446696/lib/barbeque/message_queue.rb#L17-L29 | train |
rhomobile/rhodes | lib/framework/rho/rho.rb | Rho.RHO.init_sources | def init_sources()
return unless defined? Rho::RhoConfig::sources
@all_models_loaded = true
uniq_sources = Rho::RhoConfig::sources.values
puts 'init_sources: ' #+ uniq_sources.inspect
uniq_sources.each do |source|
source['str_associations'] = ""
end
uniq_sources.each do |source|
partition = source['partition']
@db_partitions[partition] = nil unless @db_partitions[partition]
if source['belongs_to']
source['belongs_to'].each do |hash_pair|
attrib = hash_pair.keys[0]
src_name = hash_pair.values[0]
associationsSrc = find_src_byname(uniq_sources, src_name)
if !associationsSrc
puts "Error: belongs_to '#{source['name']}' : source name '#{src_name}' does not exist."
next
end
str_associations = associationsSrc['str_associations']
str_associations = "" unless str_associations
str_associations += ',' if str_associations.length() > 0
str_associations += source['name'] + ',' + attrib
associationsSrc['str_associations'] = str_associations
end
end
end
#user partition should alwayse exist
@db_partitions['user'] = nil unless @db_partitions['user']
hash_migrate = {}
puts "@db_partitions : #{@db_partitions}"
@db_partitions.each do |partition, db|
db = Rhom::RhomDbAdapter.new(Rho::RhoFSConnector::get_db_fullpathname(partition), partition) unless db
db.start_transaction
begin
init_db_sources(db, uniq_sources, partition,hash_migrate)
#SyncEngine.update_blob_attribs(partition, -1 )
db.commit
rescue Exception => e
trace_msg = e.backtrace.join("\n")
puts "exception when init_db_sources: #{e}; Trace:" + trace_msg
db.rollback
end
@db_partitions[partition] = db
end
puts "Migrate schema sources: #{hash_migrate}"
::Rho::RHO.init_schema_sources(hash_migrate)
::Rho::RHO.check_sources_migration(uniq_sources)
#@db_partitions.each do |partition, db|
# SyncEngine.update_blob_attribs(partition, -1 )
#end
::Rho::RHO.init_sync_source_properties(uniq_sources)
end | ruby | def init_sources()
return unless defined? Rho::RhoConfig::sources
@all_models_loaded = true
uniq_sources = Rho::RhoConfig::sources.values
puts 'init_sources: ' #+ uniq_sources.inspect
uniq_sources.each do |source|
source['str_associations'] = ""
end
uniq_sources.each do |source|
partition = source['partition']
@db_partitions[partition] = nil unless @db_partitions[partition]
if source['belongs_to']
source['belongs_to'].each do |hash_pair|
attrib = hash_pair.keys[0]
src_name = hash_pair.values[0]
associationsSrc = find_src_byname(uniq_sources, src_name)
if !associationsSrc
puts "Error: belongs_to '#{source['name']}' : source name '#{src_name}' does not exist."
next
end
str_associations = associationsSrc['str_associations']
str_associations = "" unless str_associations
str_associations += ',' if str_associations.length() > 0
str_associations += source['name'] + ',' + attrib
associationsSrc['str_associations'] = str_associations
end
end
end
#user partition should alwayse exist
@db_partitions['user'] = nil unless @db_partitions['user']
hash_migrate = {}
puts "@db_partitions : #{@db_partitions}"
@db_partitions.each do |partition, db|
db = Rhom::RhomDbAdapter.new(Rho::RhoFSConnector::get_db_fullpathname(partition), partition) unless db
db.start_transaction
begin
init_db_sources(db, uniq_sources, partition,hash_migrate)
#SyncEngine.update_blob_attribs(partition, -1 )
db.commit
rescue Exception => e
trace_msg = e.backtrace.join("\n")
puts "exception when init_db_sources: #{e}; Trace:" + trace_msg
db.rollback
end
@db_partitions[partition] = db
end
puts "Migrate schema sources: #{hash_migrate}"
::Rho::RHO.init_schema_sources(hash_migrate)
::Rho::RHO.check_sources_migration(uniq_sources)
#@db_partitions.each do |partition, db|
# SyncEngine.update_blob_attribs(partition, -1 )
#end
::Rho::RHO.init_sync_source_properties(uniq_sources)
end | [
"def",
"init_sources",
"(",
")",
"return",
"unless",
"defined?",
"Rho",
"::",
"RhoConfig",
"::",
"sources",
"@all_models_loaded",
"=",
"true",
"uniq_sources",
"=",
"Rho",
"::",
"RhoConfig",
"::",
"sources",
".",
"values",
"puts",
"'init_sources: '",
"#+ uniq_sources.inspect",
"uniq_sources",
".",
"each",
"do",
"|",
"source",
"|",
"source",
"[",
"'str_associations'",
"]",
"=",
"\"\"",
"end",
"uniq_sources",
".",
"each",
"do",
"|",
"source",
"|",
"partition",
"=",
"source",
"[",
"'partition'",
"]",
"@db_partitions",
"[",
"partition",
"]",
"=",
"nil",
"unless",
"@db_partitions",
"[",
"partition",
"]",
"if",
"source",
"[",
"'belongs_to'",
"]",
"source",
"[",
"'belongs_to'",
"]",
".",
"each",
"do",
"|",
"hash_pair",
"|",
"attrib",
"=",
"hash_pair",
".",
"keys",
"[",
"0",
"]",
"src_name",
"=",
"hash_pair",
".",
"values",
"[",
"0",
"]",
"associationsSrc",
"=",
"find_src_byname",
"(",
"uniq_sources",
",",
"src_name",
")",
"if",
"!",
"associationsSrc",
"puts",
"\"Error: belongs_to '#{source['name']}' : source name '#{src_name}' does not exist.\"",
"next",
"end",
"str_associations",
"=",
"associationsSrc",
"[",
"'str_associations'",
"]",
"str_associations",
"=",
"\"\"",
"unless",
"str_associations",
"str_associations",
"+=",
"','",
"if",
"str_associations",
".",
"length",
"(",
")",
">",
"0",
"str_associations",
"+=",
"source",
"[",
"'name'",
"]",
"+",
"','",
"+",
"attrib",
"associationsSrc",
"[",
"'str_associations'",
"]",
"=",
"str_associations",
"end",
"end",
"end",
"#user partition should alwayse exist",
"@db_partitions",
"[",
"'user'",
"]",
"=",
"nil",
"unless",
"@db_partitions",
"[",
"'user'",
"]",
"hash_migrate",
"=",
"{",
"}",
"puts",
"\"@db_partitions : #{@db_partitions}\"",
"@db_partitions",
".",
"each",
"do",
"|",
"partition",
",",
"db",
"|",
"db",
"=",
"Rhom",
"::",
"RhomDbAdapter",
".",
"new",
"(",
"Rho",
"::",
"RhoFSConnector",
"::",
"get_db_fullpathname",
"(",
"partition",
")",
",",
"partition",
")",
"unless",
"db",
"db",
".",
"start_transaction",
"begin",
"init_db_sources",
"(",
"db",
",",
"uniq_sources",
",",
"partition",
",",
"hash_migrate",
")",
"#SyncEngine.update_blob_attribs(partition, -1 )",
"db",
".",
"commit",
"rescue",
"Exception",
"=>",
"e",
"trace_msg",
"=",
"e",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\"",
")",
"puts",
"\"exception when init_db_sources: #{e}; Trace:\"",
"+",
"trace_msg",
"db",
".",
"rollback",
"end",
"@db_partitions",
"[",
"partition",
"]",
"=",
"db",
"end",
"puts",
"\"Migrate schema sources: #{hash_migrate}\"",
"::",
"Rho",
"::",
"RHO",
".",
"init_schema_sources",
"(",
"hash_migrate",
")",
"::",
"Rho",
"::",
"RHO",
".",
"check_sources_migration",
"(",
"uniq_sources",
")",
"#@db_partitions.each do |partition, db|",
"# SyncEngine.update_blob_attribs(partition, -1 )",
"#end",
"::",
"Rho",
"::",
"RHO",
".",
"init_sync_source_properties",
"(",
"uniq_sources",
")",
"end"
] | setup the sources table and model attributes for all applications | [
"setup",
"the",
"sources",
"table",
"and",
"model",
"attributes",
"for",
"all",
"applications"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/framework/rho/rho.rb#L456-L524 | train |
rhomobile/rhodes | lib/extensions/uri/uri/generic.rb | URI.Generic.replace! | def replace!(oth)
if self.class != oth.class
raise ArgumentError, "expected #{self.class} object"
end
component.each do |c|
self.__send__("#{c}=", oth.__send__(c))
end
end | ruby | def replace!(oth)
if self.class != oth.class
raise ArgumentError, "expected #{self.class} object"
end
component.each do |c|
self.__send__("#{c}=", oth.__send__(c))
end
end | [
"def",
"replace!",
"(",
"oth",
")",
"if",
"self",
".",
"class",
"!=",
"oth",
".",
"class",
"raise",
"ArgumentError",
",",
"\"expected #{self.class} object\"",
"end",
"component",
".",
"each",
"do",
"|",
"c",
"|",
"self",
".",
"__send__",
"(",
"\"#{c}=\"",
",",
"oth",
".",
"__send__",
"(",
"c",
")",
")",
"end",
"end"
] | replace self by other URI object | [
"replace",
"self",
"by",
"other",
"URI",
"object"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/uri/uri/generic.rb#L225-L233 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/open-uri.rb | OpenURI.Meta.charset | def charset
type, *parameters = content_type_parse
if pair = parameters.assoc('charset')
pair.last.downcase
elsif block_given?
yield
elsif type && %r{\Atext/} =~ type &&
@base_uri && /\Ahttp\z/i =~ @base_uri.scheme
"iso-8859-1" # RFC2616 3.7.1
else
nil
end
end | ruby | def charset
type, *parameters = content_type_parse
if pair = parameters.assoc('charset')
pair.last.downcase
elsif block_given?
yield
elsif type && %r{\Atext/} =~ type &&
@base_uri && /\Ahttp\z/i =~ @base_uri.scheme
"iso-8859-1" # RFC2616 3.7.1
else
nil
end
end | [
"def",
"charset",
"type",
",",
"*",
"parameters",
"=",
"content_type_parse",
"if",
"pair",
"=",
"parameters",
".",
"assoc",
"(",
"'charset'",
")",
"pair",
".",
"last",
".",
"downcase",
"elsif",
"block_given?",
"yield",
"elsif",
"type",
"&&",
"%r{",
"\\A",
"}",
"=~",
"type",
"&&",
"@base_uri",
"&&",
"/",
"\\A",
"\\z",
"/i",
"=~",
"@base_uri",
".",
"scheme",
"\"iso-8859-1\"",
"# RFC2616 3.7.1",
"else",
"nil",
"end",
"end"
] | returns a charset parameter in Content-Type field.
It is downcased for canonicalization.
If charset parameter is not given but a block is given,
the block is called and its result is returned.
It can be used to guess charset.
If charset parameter and block is not given,
nil is returned except text type in HTTP.
In that case, "iso-8859-1" is returned as defined by RFC2616 3.7.1. | [
"returns",
"a",
"charset",
"parameter",
"in",
"Content",
"-",
"Type",
"field",
".",
"It",
"is",
"downcased",
"for",
"canonicalization",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/open-uri.rb#L523-L535 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/pop.rb | Net.POP3.delete_all | def delete_all # :yield: message
mails().each do |m|
yield m if block_given?
m.delete unless m.deleted?
end
end | ruby | def delete_all # :yield: message
mails().each do |m|
yield m if block_given?
m.delete unless m.deleted?
end
end | [
"def",
"delete_all",
"# :yield: message",
"mails",
"(",
")",
".",
"each",
"do",
"|",
"m",
"|",
"yield",
"m",
"if",
"block_given?",
"m",
".",
"delete",
"unless",
"m",
".",
"deleted?",
"end",
"end"
] | Deletes all messages on the server.
If called with a block, yields each message in turn before deleting it.
=== Example
n = 1
pop.delete_all do |m|
File.open("inbox/#{n}") do |f|
f.write m.pop
end
n += 1
end
This method raises a POPError if an error occurs. | [
"Deletes",
"all",
"messages",
"on",
"the",
"server",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/pop.rb#L686-L691 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/pop.rb | Net.POPMail.pop | def pop( dest = '', &block ) # :yield: message_chunk
if block_given?
@command.retr(@number, &block)
nil
else
@command.retr(@number) do |chunk|
dest << chunk
end
dest
end
end | ruby | def pop( dest = '', &block ) # :yield: message_chunk
if block_given?
@command.retr(@number, &block)
nil
else
@command.retr(@number) do |chunk|
dest << chunk
end
dest
end
end | [
"def",
"pop",
"(",
"dest",
"=",
"''",
",",
"&",
"block",
")",
"# :yield: message_chunk",
"if",
"block_given?",
"@command",
".",
"retr",
"(",
"@number",
",",
"block",
")",
"nil",
"else",
"@command",
".",
"retr",
"(",
"@number",
")",
"do",
"|",
"chunk",
"|",
"dest",
"<<",
"chunk",
"end",
"dest",
"end",
"end"
] | This method fetches the message. If called with a block, the
message is yielded to the block one chunk at a time. If called
without a block, the message is returned as a String. The optional
+dest+ argument will be prepended to the returned String; this
argument is essentially obsolete.
=== Example without block
POP3.start('pop.example.com', 110,
'YourAccount, 'YourPassword') do |pop|
n = 1
pop.mails.each do |popmail|
File.open("inbox/#{n}", 'w') do |f|
f.write popmail.pop
end
popmail.delete
n += 1
end
end
=== Example with block
POP3.start('pop.example.com', 110,
'YourAccount, 'YourPassword') do |pop|
n = 1
pop.mails.each do |popmail|
File.open("inbox/#{n}", 'w') do |f|
popmail.pop do |chunk|
f.write chunk
end
end
n += 1
end
end
This method raises a POPError if an error occurs. | [
"This",
"method",
"fetches",
"the",
"message",
".",
"If",
"called",
"with",
"a",
"block",
"the",
"message",
"is",
"yielded",
"to",
"the",
"block",
"one",
"chunk",
"at",
"a",
"time",
".",
"If",
"called",
"without",
"a",
"block",
"the",
"message",
"is",
"returned",
"as",
"a",
"String",
".",
"The",
"optional",
"+",
"dest",
"+",
"argument",
"will",
"be",
"prepended",
"to",
"the",
"returned",
"String",
";",
"this",
"argument",
"is",
"essentially",
"obsolete",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/pop.rb#L801-L811 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/dsl_definition.rb | Rake.DSL.directory | def directory(*args, &block)
result = file_create(*args, &block)
dir, _ = *Rake.application.resolve_args(args)
Rake.each_dir_parent(dir) do |d|
file_create d do |t|
mkdir_p t.name unless File.exist?(t.name)
end
end
result
end | ruby | def directory(*args, &block)
result = file_create(*args, &block)
dir, _ = *Rake.application.resolve_args(args)
Rake.each_dir_parent(dir) do |d|
file_create d do |t|
mkdir_p t.name unless File.exist?(t.name)
end
end
result
end | [
"def",
"directory",
"(",
"*",
"args",
",",
"&",
"block",
")",
"result",
"=",
"file_create",
"(",
"args",
",",
"block",
")",
"dir",
",",
"_",
"=",
"Rake",
".",
"application",
".",
"resolve_args",
"(",
"args",
")",
"Rake",
".",
"each_dir_parent",
"(",
"dir",
")",
"do",
"|",
"d",
"|",
"file_create",
"d",
"do",
"|",
"t",
"|",
"mkdir_p",
"t",
".",
"name",
"unless",
"File",
".",
"exist?",
"(",
"t",
".",
"name",
")",
"end",
"end",
"result",
"end"
] | Declare a set of files tasks to create the given directories on
demand.
Example:
directory "testdata/doc" | [
"Declare",
"a",
"set",
"of",
"files",
"tasks",
"to",
"create",
"the",
"given",
"directories",
"on",
"demand",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/dsl_definition.rb#L64-L73 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/dsl_definition.rb | Rake.DSL.namespace | def namespace(name=nil, &block)
name = name.to_s if name.kind_of?(Symbol)
name = name.to_str if name.respond_to?(:to_str)
unless name.kind_of?(String) || name.nil?
raise ArgumentError, "Expected a String or Symbol for a namespace name"
end
Rake.application.in_namespace(name, &block)
end | ruby | def namespace(name=nil, &block)
name = name.to_s if name.kind_of?(Symbol)
name = name.to_str if name.respond_to?(:to_str)
unless name.kind_of?(String) || name.nil?
raise ArgumentError, "Expected a String or Symbol for a namespace name"
end
Rake.application.in_namespace(name, &block)
end | [
"def",
"namespace",
"(",
"name",
"=",
"nil",
",",
"&",
"block",
")",
"name",
"=",
"name",
".",
"to_s",
"if",
"name",
".",
"kind_of?",
"(",
"Symbol",
")",
"name",
"=",
"name",
".",
"to_str",
"if",
"name",
".",
"respond_to?",
"(",
":to_str",
")",
"unless",
"name",
".",
"kind_of?",
"(",
"String",
")",
"||",
"name",
".",
"nil?",
"raise",
"ArgumentError",
",",
"\"Expected a String or Symbol for a namespace name\"",
"end",
"Rake",
".",
"application",
".",
"in_namespace",
"(",
"name",
",",
"block",
")",
"end"
] | Create a new rake namespace and use it for evaluating the given
block. Returns a NameSpace object that can be used to lookup
tasks defined in the namespace.
E.g.
ns = namespace "nested" do
task :run
end
task_run = ns[:run] # find :run in the given namespace. | [
"Create",
"a",
"new",
"rake",
"namespace",
"and",
"use",
"it",
"for",
"evaluating",
"the",
"given",
"block",
".",
"Returns",
"a",
"NameSpace",
"object",
"that",
"can",
"be",
"used",
"to",
"lookup",
"tasks",
"defined",
"in",
"the",
"namespace",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/rake/dsl_definition.rb#L98-L105 | train |
rhomobile/rhodes | lib/extensions/rexml/rexml/element.rb | REXML.Element.delete_namespace | def delete_namespace namespace="xmlns"
namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
attribute = attributes.get_attribute(namespace)
attribute.remove unless attribute.nil?
self
end | ruby | def delete_namespace namespace="xmlns"
namespace = "xmlns:#{namespace}" unless namespace == 'xmlns'
attribute = attributes.get_attribute(namespace)
attribute.remove unless attribute.nil?
self
end | [
"def",
"delete_namespace",
"namespace",
"=",
"\"xmlns\"",
"namespace",
"=",
"\"xmlns:#{namespace}\"",
"unless",
"namespace",
"==",
"'xmlns'",
"attribute",
"=",
"attributes",
".",
"get_attribute",
"(",
"namespace",
")",
"attribute",
".",
"remove",
"unless",
"attribute",
".",
"nil?",
"self",
"end"
] | Removes a namespace from this node. This only works if the namespace is
actually declared in this node. If no argument is passed, deletes the
default namespace.
Evaluates to: this element
doc = Document.new "<a xmlns:foo='bar' xmlns='twiddle'/>"
doc.root.delete_namespace
puts doc # -> <a xmlns:foo='bar'/>
doc.root.delete_namespace 'foo'
puts doc # -> <a/> | [
"Removes",
"a",
"namespace",
"from",
"this",
"node",
".",
"This",
"only",
"works",
"if",
"the",
"namespace",
"is",
"actually",
"declared",
"in",
"this",
"node",
".",
"If",
"no",
"argument",
"is",
"passed",
"deletes",
"the",
"default",
"namespace",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/element.rb#L270-L275 | train |
rhomobile/rhodes | lib/extensions/rexml/rexml/element.rb | REXML.Attributes.each_attribute | def each_attribute # :yields: attribute
each_value do |val|
if val.kind_of? Attribute
yield val
else
val.each_value { |atr| yield atr }
end
end
end | ruby | def each_attribute # :yields: attribute
each_value do |val|
if val.kind_of? Attribute
yield val
else
val.each_value { |atr| yield atr }
end
end
end | [
"def",
"each_attribute",
"# :yields: attribute",
"each_value",
"do",
"|",
"val",
"|",
"if",
"val",
".",
"kind_of?",
"Attribute",
"yield",
"val",
"else",
"val",
".",
"each_value",
"{",
"|",
"atr",
"|",
"yield",
"atr",
"}",
"end",
"end",
"end"
] | Iterates over the attributes of an Element. Yields actual Attribute
nodes, not String values.
doc = Document.new '<a x="1" y="2"/>'
doc.root.attributes.each_attribute {|attr|
p attr.expanded_name+" => "+attr.value
} | [
"Iterates",
"over",
"the",
"attributes",
"of",
"an",
"Element",
".",
"Yields",
"actual",
"Attribute",
"nodes",
"not",
"String",
"values",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/element.rb#L1014-L1022 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/rubygems.rb | Gem.Specification.sort_obj | def sort_obj
[@name, installation_path == File.join(defined?(Merb) && Merb.respond_to?(:root) ? Merb.root : Dir.pwd,"gems") ? 1 : -1, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
end | ruby | def sort_obj
[@name, installation_path == File.join(defined?(Merb) && Merb.respond_to?(:root) ? Merb.root : Dir.pwd,"gems") ? 1 : -1, @version.to_ints, @new_platform == Gem::Platform::RUBY ? -1 : 1]
end | [
"def",
"sort_obj",
"[",
"@name",
",",
"installation_path",
"==",
"File",
".",
"join",
"(",
"defined?",
"(",
"Merb",
")",
"&&",
"Merb",
".",
"respond_to?",
"(",
":root",
")",
"?",
"Merb",
".",
"root",
":",
"Dir",
".",
"pwd",
",",
"\"gems\"",
")",
"?",
"1",
":",
"-",
"1",
",",
"@version",
".",
"to_ints",
",",
"@new_platform",
"==",
"Gem",
"::",
"Platform",
"::",
"RUBY",
"?",
"-",
"1",
":",
"1",
"]",
"end"
] | Overwrite this so that gems in the gems directory get preferred over gems
from any other location. If there are two gems of different versions in
the gems directory, the later one will load as usual.
@return [Array<Array>] The object used for sorting gem specs. | [
"Overwrite",
"this",
"so",
"that",
"gems",
"in",
"the",
"gems",
"directory",
"get",
"preferred",
"over",
"gems",
"from",
"any",
"other",
"location",
".",
"If",
"there",
"are",
"two",
"gems",
"of",
"different",
"versions",
"in",
"the",
"gems",
"directory",
"the",
"later",
"one",
"will",
"load",
"as",
"usual",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/rubygems.rb#L34-L36 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/server.rb | WEBrick.GenericServer.shutdown | def shutdown
stop
@listeners.each{|s|
if @logger.debug?
addr = s.addr
@logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
end
begin
s.shutdown
rescue Errno::ENOTCONN
# when `Errno::ENOTCONN: Socket is not connected' on some platforms,
# call #close instead of #shutdown.
# (ignore @config[:ShutdownSocketWithoutClose])
s.close
else
unless @config[:ShutdownSocketWithoutClose]
s.close
end
end
}
@listeners.clear
end | ruby | def shutdown
stop
@listeners.each{|s|
if @logger.debug?
addr = s.addr
@logger.debug("close TCPSocket(#{addr[2]}, #{addr[1]})")
end
begin
s.shutdown
rescue Errno::ENOTCONN
# when `Errno::ENOTCONN: Socket is not connected' on some platforms,
# call #close instead of #shutdown.
# (ignore @config[:ShutdownSocketWithoutClose])
s.close
else
unless @config[:ShutdownSocketWithoutClose]
s.close
end
end
}
@listeners.clear
end | [
"def",
"shutdown",
"stop",
"@listeners",
".",
"each",
"{",
"|",
"s",
"|",
"if",
"@logger",
".",
"debug?",
"addr",
"=",
"s",
".",
"addr",
"@logger",
".",
"debug",
"(",
"\"close TCPSocket(#{addr[2]}, #{addr[1]})\"",
")",
"end",
"begin",
"s",
".",
"shutdown",
"rescue",
"Errno",
"::",
"ENOTCONN",
"# when `Errno::ENOTCONN: Socket is not connected' on some platforms,",
"# call #close instead of #shutdown.",
"# (ignore @config[:ShutdownSocketWithoutClose])",
"s",
".",
"close",
"else",
"unless",
"@config",
"[",
":ShutdownSocketWithoutClose",
"]",
"s",
".",
"close",
"end",
"end",
"}",
"@listeners",
".",
"clear",
"end"
] | Shuts down the server and all listening sockets. New listeners must be
provided to restart the server. | [
"Shuts",
"down",
"the",
"server",
"and",
"all",
"listening",
"sockets",
".",
"New",
"listeners",
"must",
"be",
"provided",
"to",
"restart",
"the",
"server",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/server.rb#L219-L240 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/log.rb | WEBrick.BasicLog.format | def format(arg)
if arg.is_a?(Exception)
"#{arg.class}: #{arg.message}\n\t" <<
arg.backtrace.join("\n\t") << "\n"
elsif arg.respond_to?(:to_str)
arg.to_str
else
arg.inspect
end
end | ruby | def format(arg)
if arg.is_a?(Exception)
"#{arg.class}: #{arg.message}\n\t" <<
arg.backtrace.join("\n\t") << "\n"
elsif arg.respond_to?(:to_str)
arg.to_str
else
arg.inspect
end
end | [
"def",
"format",
"(",
"arg",
")",
"if",
"arg",
".",
"is_a?",
"(",
"Exception",
")",
"\"#{arg.class}: #{arg.message}\\n\\t\"",
"<<",
"arg",
".",
"backtrace",
".",
"join",
"(",
"\"\\n\\t\"",
")",
"<<",
"\"\\n\"",
"elsif",
"arg",
".",
"respond_to?",
"(",
":to_str",
")",
"arg",
".",
"to_str",
"else",
"arg",
".",
"inspect",
"end",
"end"
] | Formats +arg+ for the logger
* If +arg+ is an Exception, it will format the error message and
the back trace.
* If +arg+ responds to #to_str, it will return it.
* Otherwise it will return +arg+.inspect. | [
"Formats",
"+",
"arg",
"+",
"for",
"the",
"logger"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/log.rb#L118-L127 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/request.rb | RestClient.Request.process_url_params | def process_url_params url, headers
url_params = {}
headers.delete_if do |key, value|
if 'params' == key.to_s.downcase && value.is_a?(Hash)
url_params.merge! value
true
else
false
end
end
unless url_params.empty?
query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
url + "?#{query_string}"
else
url
end
end | ruby | def process_url_params url, headers
url_params = {}
headers.delete_if do |key, value|
if 'params' == key.to_s.downcase && value.is_a?(Hash)
url_params.merge! value
true
else
false
end
end
unless url_params.empty?
query_string = url_params.collect { |k, v| "#{k.to_s}=#{CGI::escape(v.to_s)}" }.join('&')
url + "?#{query_string}"
else
url
end
end | [
"def",
"process_url_params",
"url",
",",
"headers",
"url_params",
"=",
"{",
"}",
"headers",
".",
"delete_if",
"do",
"|",
"key",
",",
"value",
"|",
"if",
"'params'",
"==",
"key",
".",
"to_s",
".",
"downcase",
"&&",
"value",
".",
"is_a?",
"(",
"Hash",
")",
"url_params",
".",
"merge!",
"value",
"true",
"else",
"false",
"end",
"end",
"unless",
"url_params",
".",
"empty?",
"query_string",
"=",
"url_params",
".",
"collect",
"{",
"|",
"k",
",",
"v",
"|",
"\"#{k.to_s}=#{CGI::escape(v.to_s)}\"",
"}",
".",
"join",
"(",
"'&'",
")",
"url",
"+",
"\"?#{query_string}\"",
"else",
"url",
"end",
"end"
] | Extract the query parameters and append them to the url | [
"Extract",
"the",
"query",
"parameters",
"and",
"append",
"them",
"to",
"the",
"url"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/request.rb#L192-L208 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/request.rb | RestClient.Request.stringify_headers | def stringify_headers headers
headers.inject({}) do |result, (key, value)|
if key.is_a? Symbol
key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
end
if 'CONTENT-TYPE' == key.upcase
target_value = value.to_s
result[key] = MIME::Types.type_for_extension target_value
elsif 'ACCEPT' == key.upcase
# Accept can be composed of several comma-separated values
if value.is_a? Array
target_values = value
else
target_values = value.to_s.split ','
end
result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
else
result[key] = value.to_s
end
result
end
end | ruby | def stringify_headers headers
headers.inject({}) do |result, (key, value)|
if key.is_a? Symbol
key = key.to_s.split(/_/).map { |w| w.capitalize }.join('-')
end
if 'CONTENT-TYPE' == key.upcase
target_value = value.to_s
result[key] = MIME::Types.type_for_extension target_value
elsif 'ACCEPT' == key.upcase
# Accept can be composed of several comma-separated values
if value.is_a? Array
target_values = value
else
target_values = value.to_s.split ','
end
result[key] = target_values.map { |ext| MIME::Types.type_for_extension(ext.to_s.strip) }.join(', ')
else
result[key] = value.to_s
end
result
end
end | [
"def",
"stringify_headers",
"headers",
"headers",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"result",
",",
"(",
"key",
",",
"value",
")",
"|",
"if",
"key",
".",
"is_a?",
"Symbol",
"key",
"=",
"key",
".",
"to_s",
".",
"split",
"(",
"/",
"/",
")",
".",
"map",
"{",
"|",
"w",
"|",
"w",
".",
"capitalize",
"}",
".",
"join",
"(",
"'-'",
")",
"end",
"if",
"'CONTENT-TYPE'",
"==",
"key",
".",
"upcase",
"target_value",
"=",
"value",
".",
"to_s",
"result",
"[",
"key",
"]",
"=",
"MIME",
"::",
"Types",
".",
"type_for_extension",
"target_value",
"elsif",
"'ACCEPT'",
"==",
"key",
".",
"upcase",
"# Accept can be composed of several comma-separated values",
"if",
"value",
".",
"is_a?",
"Array",
"target_values",
"=",
"value",
"else",
"target_values",
"=",
"value",
".",
"to_s",
".",
"split",
"','",
"end",
"result",
"[",
"key",
"]",
"=",
"target_values",
".",
"map",
"{",
"|",
"ext",
"|",
"MIME",
"::",
"Types",
".",
"type_for_extension",
"(",
"ext",
".",
"to_s",
".",
"strip",
")",
"}",
".",
"join",
"(",
"', '",
")",
"else",
"result",
"[",
"key",
"]",
"=",
"value",
".",
"to_s",
"end",
"result",
"end",
"end"
] | Return a hash of headers whose keys are capitalized strings | [
"Return",
"a",
"hash",
"of",
"headers",
"whose",
"keys",
"are",
"capitalized",
"strings"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/rest-client-1.7.2/lib/restclient/request.rb#L541-L562 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/simple_set.rb | Extlib.SimpleSet.merge | def merge(arr)
super(arr.inject({}) {|s,x| s[x] = true; s })
end | ruby | def merge(arr)
super(arr.inject({}) {|s,x| s[x] = true; s })
end | [
"def",
"merge",
"(",
"arr",
")",
"super",
"(",
"arr",
".",
"inject",
"(",
"{",
"}",
")",
"{",
"|",
"s",
",",
"x",
"|",
"s",
"[",
"x",
"]",
"=",
"true",
";",
"s",
"}",
")",
"end"
] | Merge _arr_ with receiver, producing the union of receiver & _arr_
s = Extlib::SimpleSet.new([:a, :b, :c])
s.merge([:c, :d, :e, f]) #=> #<SimpleSet: {:e, :c, :f, :a, :d, :b}>
@param [Array] arr Values to merge with set.
@return [SimpleSet] The set after the Array was merged in.
@api public | [
"Merge",
"_arr_",
"with",
"receiver",
"producing",
"the",
"union",
"of",
"receiver",
"&",
"_arr_"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/extlib-0.9.16/lib/extlib/simple_set.rb#L45-L47 | train |
rhomobile/rhodes | lib/build/development/live_update_task.rb | RhoDevelopment.LiveUpdateTask.execute | def execute
puts "Executing #{self.class.taskName} at #{Time::now}".primary
begin
self.action
rescue => e
puts "Executing #{self.class.taskName} failed".warning
puts e.inspect.to_s.info
puts e.backtrace.to_s.info
end
end | ruby | def execute
puts "Executing #{self.class.taskName} at #{Time::now}".primary
begin
self.action
rescue => e
puts "Executing #{self.class.taskName} failed".warning
puts e.inspect.to_s.info
puts e.backtrace.to_s.info
end
end | [
"def",
"execute",
"puts",
"\"Executing #{self.class.taskName} at #{Time::now}\"",
".",
"primary",
"begin",
"self",
".",
"action",
"rescue",
"=>",
"e",
"puts",
"\"Executing #{self.class.taskName} failed\"",
".",
"warning",
"puts",
"e",
".",
"inspect",
".",
"to_s",
".",
"info",
"puts",
"e",
".",
"backtrace",
".",
"to_s",
".",
"info",
"end",
"end"
] | Execute specific task action | [
"Execute",
"specific",
"task",
"action"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/build/development/live_update_task.rb#L26-L35 | train |
rhomobile/rhodes | lib/build/development/live_update_task.rb | RhoDevelopment.PlatformPartialUpdateBuildingTask.dispatchToUrl | def dispatchToUrl(anUri)
uri = URI.join(anUri, 'tasks/new')
Net::HTTP.post_form(uri, {'taskName' => self.class.taskName, 'platform' => @platform, 'filename' => @filename})
end | ruby | def dispatchToUrl(anUri)
uri = URI.join(anUri, 'tasks/new')
Net::HTTP.post_form(uri, {'taskName' => self.class.taskName, 'platform' => @platform, 'filename' => @filename})
end | [
"def",
"dispatchToUrl",
"(",
"anUri",
")",
"uri",
"=",
"URI",
".",
"join",
"(",
"anUri",
",",
"'tasks/new'",
")",
"Net",
"::",
"HTTP",
".",
"post_form",
"(",
"uri",
",",
"{",
"'taskName'",
"=>",
"self",
".",
"class",
".",
"taskName",
",",
"'platform'",
"=>",
"@platform",
",",
"'filename'",
"=>",
"@filename",
"}",
")",
"end"
] | Method serializes itself to a hash and sends post request with the hash to specified URI
@param anUri [URI] URI for post request | [
"Method",
"serializes",
"itself",
"to",
"a",
"hash",
"and",
"sends",
"post",
"request",
"with",
"the",
"hash",
"to",
"specified",
"URI"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/build/development/live_update_task.rb#L167-L170 | train |
rhomobile/rhodes | lib/build/development/live_update_task.rb | RhoDevelopment.PartialUpdateTask.action | def action
updated_list_filename = File.join(Configuration::application_root, 'upgrade_package_add_files.txt')
removed_list_filename = File.join(Configuration::application_root, 'upgrade_package_remove_files.txt')
mkdir_p Configuration::development_directory
Configuration::enabled_subscriber_platforms.each { |each|
RhoDevelopment.setup(Configuration::development_directory, each)
puts "Check changes for #{each}".warning
changed = RhoDevelopment.check_changes_from_last_build(updated_list_filename, removed_list_filename)
if changed
puts "Source code for platform #{each} was changed".primary
WebServer.dispatch_task(PlatformPartialUpdateBuildingTask.new(each, @filename));
Configuration::enabled_subscribers_by_platform(each).each { |subscriber|
WebServer.dispatch_task(SubscriberPartialUpdateNotifyingTask.new(subscriber, @filename));
}
else
puts "Source code for platform #{each} wasn't changed".primary
end
}
end | ruby | def action
updated_list_filename = File.join(Configuration::application_root, 'upgrade_package_add_files.txt')
removed_list_filename = File.join(Configuration::application_root, 'upgrade_package_remove_files.txt')
mkdir_p Configuration::development_directory
Configuration::enabled_subscriber_platforms.each { |each|
RhoDevelopment.setup(Configuration::development_directory, each)
puts "Check changes for #{each}".warning
changed = RhoDevelopment.check_changes_from_last_build(updated_list_filename, removed_list_filename)
if changed
puts "Source code for platform #{each} was changed".primary
WebServer.dispatch_task(PlatformPartialUpdateBuildingTask.new(each, @filename));
Configuration::enabled_subscribers_by_platform(each).each { |subscriber|
WebServer.dispatch_task(SubscriberPartialUpdateNotifyingTask.new(subscriber, @filename));
}
else
puts "Source code for platform #{each} wasn't changed".primary
end
}
end | [
"def",
"action",
"updated_list_filename",
"=",
"File",
".",
"join",
"(",
"Configuration",
"::",
"application_root",
",",
"'upgrade_package_add_files.txt'",
")",
"removed_list_filename",
"=",
"File",
".",
"join",
"(",
"Configuration",
"::",
"application_root",
",",
"'upgrade_package_remove_files.txt'",
")",
"mkdir_p",
"Configuration",
"::",
"development_directory",
"Configuration",
"::",
"enabled_subscriber_platforms",
".",
"each",
"{",
"|",
"each",
"|",
"RhoDevelopment",
".",
"setup",
"(",
"Configuration",
"::",
"development_directory",
",",
"each",
")",
"puts",
"\"Check changes for #{each}\"",
".",
"warning",
"changed",
"=",
"RhoDevelopment",
".",
"check_changes_from_last_build",
"(",
"updated_list_filename",
",",
"removed_list_filename",
")",
"if",
"changed",
"puts",
"\"Source code for platform #{each} was changed\"",
".",
"primary",
"WebServer",
".",
"dispatch_task",
"(",
"PlatformPartialUpdateBuildingTask",
".",
"new",
"(",
"each",
",",
"@filename",
")",
")",
";",
"Configuration",
"::",
"enabled_subscribers_by_platform",
"(",
"each",
")",
".",
"each",
"{",
"|",
"subscriber",
"|",
"WebServer",
".",
"dispatch_task",
"(",
"SubscriberPartialUpdateNotifyingTask",
".",
"new",
"(",
"subscriber",
",",
"@filename",
")",
")",
";",
"}",
"else",
"puts",
"\"Source code for platform #{each} wasn't changed\"",
".",
"primary",
"end",
"}",
"end"
] | Checks has source code changes for each platform | [
"Checks",
"has",
"source",
"code",
"changes",
"for",
"each",
"platform"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/build/development/live_update_task.rb#L328-L346 | train |
rhomobile/rhodes | lib/extensions/rhoxml/rexml/xpath_parser.rb | REXML.XPathParser.descendant_or_self | def descendant_or_self( path_stack, nodeset )
rs = []
#puts "#"*80
#puts "PATH_STACK = #{path_stack.inspect}"
#puts "NODESET = #{nodeset.collect{|n|n.inspect}.inspect}"
d_o_s( path_stack, nodeset, rs )
#puts "RS = #{rs.collect{|n|n.inspect}.inspect}"
document_order(rs.flatten.compact)
#rs.flatten.compact
end | ruby | def descendant_or_self( path_stack, nodeset )
rs = []
#puts "#"*80
#puts "PATH_STACK = #{path_stack.inspect}"
#puts "NODESET = #{nodeset.collect{|n|n.inspect}.inspect}"
d_o_s( path_stack, nodeset, rs )
#puts "RS = #{rs.collect{|n|n.inspect}.inspect}"
document_order(rs.flatten.compact)
#rs.flatten.compact
end | [
"def",
"descendant_or_self",
"(",
"path_stack",
",",
"nodeset",
")",
"rs",
"=",
"[",
"]",
"#puts \"#\"*80",
"#puts \"PATH_STACK = #{path_stack.inspect}\"",
"#puts \"NODESET = #{nodeset.collect{|n|n.inspect}.inspect}\"",
"d_o_s",
"(",
"path_stack",
",",
"nodeset",
",",
"rs",
")",
"#puts \"RS = #{rs.collect{|n|n.inspect}.inspect}\"",
"document_order",
"(",
"rs",
".",
"flatten",
".",
"compact",
")",
"#rs.flatten.compact",
"end"
] | FIXME
The next two methods are BAD MOJO!
This is my achilles heel. If anybody thinks of a better
way of doing this, be my guest. This really sucks, but
it is a wonder it works at all. | [
"FIXME",
"The",
"next",
"two",
"methods",
"are",
"BAD",
"MOJO!",
"This",
"is",
"my",
"achilles",
"heel",
".",
"If",
"anybody",
"thinks",
"of",
"a",
"better",
"way",
"of",
"doing",
"this",
"be",
"my",
"guest",
".",
"This",
"really",
"sucks",
"but",
"it",
"is",
"a",
"wonder",
"it",
"works",
"at",
"all",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rhoxml/rexml/xpath_parser.rb#L540-L549 | train |
rhomobile/rhodes | lib/extensions/rhoxml/rexml/xpath_parser.rb | REXML.XPathParser.document_order | def document_order( array_of_nodes )
new_arry = []
array_of_nodes.each { |node|
node_idx = []
np = node.node_type == :attribute ? node.element : node
while np.parent and np.parent.node_type == :element
node_idx << np.parent.index( np )
np = np.parent
end
new_arry << [ node_idx.reverse, node ]
}
#puts "new_arry = #{new_arry.inspect}"
new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
end | ruby | def document_order( array_of_nodes )
new_arry = []
array_of_nodes.each { |node|
node_idx = []
np = node.node_type == :attribute ? node.element : node
while np.parent and np.parent.node_type == :element
node_idx << np.parent.index( np )
np = np.parent
end
new_arry << [ node_idx.reverse, node ]
}
#puts "new_arry = #{new_arry.inspect}"
new_arry.sort{ |s1, s2| s1[0] <=> s2[0] }.collect{ |s| s[1] }
end | [
"def",
"document_order",
"(",
"array_of_nodes",
")",
"new_arry",
"=",
"[",
"]",
"array_of_nodes",
".",
"each",
"{",
"|",
"node",
"|",
"node_idx",
"=",
"[",
"]",
"np",
"=",
"node",
".",
"node_type",
"==",
":attribute",
"?",
"node",
".",
"element",
":",
"node",
"while",
"np",
".",
"parent",
"and",
"np",
".",
"parent",
".",
"node_type",
"==",
":element",
"node_idx",
"<<",
"np",
".",
"parent",
".",
"index",
"(",
"np",
")",
"np",
"=",
"np",
".",
"parent",
"end",
"new_arry",
"<<",
"[",
"node_idx",
".",
"reverse",
",",
"node",
"]",
"}",
"#puts \"new_arry = #{new_arry.inspect}\"",
"new_arry",
".",
"sort",
"{",
"|",
"s1",
",",
"s2",
"|",
"s1",
"[",
"0",
"]",
"<=>",
"s2",
"[",
"0",
"]",
"}",
".",
"collect",
"{",
"|",
"s",
"|",
"s",
"[",
"1",
"]",
"}",
"end"
] | Reorders an array of nodes so that they are in document order
It tries to do this efficiently.
FIXME: I need to get rid of this, but the issue is that most of the XPath
interpreter functions as a filter, which means that we lose context going
in and out of function calls. If I knew what the index of the nodes was,
I wouldn't have to do this. Maybe add a document IDX for each node?
Problems with mutable documents. Or, rewrite everything. | [
"Reorders",
"an",
"array",
"of",
"nodes",
"so",
"that",
"they",
"are",
"in",
"document",
"order",
"It",
"tries",
"to",
"do",
"this",
"efficiently",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rhoxml/rexml/xpath_parser.rb#L573-L586 | train |
rhomobile/rhodes | spec/framework_spec/app/spec/language/fixtures/break.rb | BreakSpecs.Lambda.break_in_defining_scope | def break_in_defining_scope(value=true)
note :a
note lambda {
note :b
if value
break :break
else
break
end
note :c
}.call
note :d
end | ruby | def break_in_defining_scope(value=true)
note :a
note lambda {
note :b
if value
break :break
else
break
end
note :c
}.call
note :d
end | [
"def",
"break_in_defining_scope",
"(",
"value",
"=",
"true",
")",
"note",
":a",
"note",
"lambda",
"{",
"note",
":b",
"if",
"value",
"break",
":break",
"else",
"break",
"end",
"note",
":c",
"}",
".",
"call",
"note",
":d",
"end"
] | Cases for the invocation of the scope defining the lambda still active
on the call stack when the lambda is invoked. | [
"Cases",
"for",
"the",
"invocation",
"of",
"the",
"scope",
"defining",
"the",
"lambda",
"still",
"active",
"on",
"the",
"call",
"stack",
"when",
"the",
"lambda",
"is",
"invoked",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/spec/framework_spec/app/spec/language/fixtures/break.rb#L113-L125 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/smtp.rb | Net.SMTP.start | def start(helo = 'localhost',
user = nil, secret = nil, authtype = nil) # :yield: smtp
if block_given?
begin
do_start helo, user, secret, authtype
return yield(self)
ensure
do_finish
end
else
do_start helo, user, secret, authtype
return self
end
end | ruby | def start(helo = 'localhost',
user = nil, secret = nil, authtype = nil) # :yield: smtp
if block_given?
begin
do_start helo, user, secret, authtype
return yield(self)
ensure
do_finish
end
else
do_start helo, user, secret, authtype
return self
end
end | [
"def",
"start",
"(",
"helo",
"=",
"'localhost'",
",",
"user",
"=",
"nil",
",",
"secret",
"=",
"nil",
",",
"authtype",
"=",
"nil",
")",
"# :yield: smtp",
"if",
"block_given?",
"begin",
"do_start",
"helo",
",",
"user",
",",
"secret",
",",
"authtype",
"return",
"yield",
"(",
"self",
")",
"ensure",
"do_finish",
"end",
"else",
"do_start",
"helo",
",",
"user",
",",
"secret",
",",
"authtype",
"return",
"self",
"end",
"end"
] | Opens a TCP connection and starts the SMTP session.
=== Parameters
+helo+ is the _HELO_ _domain_ that you'll dispatch mails from; see
the discussion in the overview notes.
If both of +user+ and +secret+ are given, SMTP authentication
will be attempted using the AUTH command. +authtype+ specifies
the type of authentication to attempt; it must be one of
:login, :plain, and :cram_md5. See the notes on SMTP Authentication
in the overview.
=== Block Usage
When this methods is called with a block, the newly-started SMTP
object is yielded to the block, and automatically closed after
the block call finishes. Otherwise, it is the caller's
responsibility to close the session when finished.
=== Example
This is very similar to the class method SMTP.start.
require 'net/smtp'
smtp = Net::SMTP.new('smtp.mail.server', 25)
smtp.start(helo_domain, account, password, authtype) do |smtp|
smtp.send_message msgstr, '[email protected]', ['[email protected]']
end
The primary use of this method (as opposed to SMTP.start)
is probably to set debugging (#set_debug_output) or ESMTP
(#esmtp=), which must be done before the session is
started.
=== Errors
If session has already been started, an IOError will be raised.
This method may raise:
* Net::SMTPAuthenticationError
* Net::SMTPServerBusy
* Net::SMTPSyntaxError
* Net::SMTPFatalError
* Net::SMTPUnknownError
* Net::OpenTimeout
* Net::ReadTimeout
* IOError | [
"Opens",
"a",
"TCP",
"connection",
"and",
"starts",
"the",
"SMTP",
"session",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/smtp.rb#L516-L529 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/smtp.rb | Net.SMTP.data | def data(msgstr = nil, &block) #:yield: stream
if msgstr and block
raise ArgumentError, "message and block are exclusive"
end
unless msgstr or block
raise ArgumentError, "message or block is required"
end
res = critical {
check_continue get_response('DATA')
if msgstr
@socket.write_message msgstr
else
@socket.write_message_by_block(&block)
end
recv_response()
}
check_response res
res
end | ruby | def data(msgstr = nil, &block) #:yield: stream
if msgstr and block
raise ArgumentError, "message and block are exclusive"
end
unless msgstr or block
raise ArgumentError, "message or block is required"
end
res = critical {
check_continue get_response('DATA')
if msgstr
@socket.write_message msgstr
else
@socket.write_message_by_block(&block)
end
recv_response()
}
check_response res
res
end | [
"def",
"data",
"(",
"msgstr",
"=",
"nil",
",",
"&",
"block",
")",
"#:yield: stream",
"if",
"msgstr",
"and",
"block",
"raise",
"ArgumentError",
",",
"\"message and block are exclusive\"",
"end",
"unless",
"msgstr",
"or",
"block",
"raise",
"ArgumentError",
",",
"\"message or block is required\"",
"end",
"res",
"=",
"critical",
"{",
"check_continue",
"get_response",
"(",
"'DATA'",
")",
"if",
"msgstr",
"@socket",
".",
"write_message",
"msgstr",
"else",
"@socket",
".",
"write_message_by_block",
"(",
"block",
")",
"end",
"recv_response",
"(",
")",
"}",
"check_response",
"res",
"res",
"end"
] | This method sends a message.
If +msgstr+ is given, sends it as a message.
If block is given, yield a message writer stream.
You must write message before the block is closed.
# Example 1 (by string)
smtp.data(<<EndMessage)
From: [email protected]
To: [email protected]
Subject: I found a bug
Check vm.c:58879.
EndMessage
# Example 2 (by block)
smtp.data {|f|
f.puts "From: [email protected]"
f.puts "To: [email protected]"
f.puts "Subject: I found a bug"
f.puts ""
f.puts "Check vm.c:58879."
} | [
"This",
"method",
"sends",
"a",
"message",
".",
"If",
"+",
"msgstr",
"+",
"is",
"given",
"sends",
"it",
"as",
"a",
"message",
".",
"If",
"block",
"is",
"given",
"yield",
"a",
"message",
"writer",
"stream",
".",
"You",
"must",
"write",
"message",
"before",
"the",
"block",
"is",
"closed",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/smtp.rb#L895-L913 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/discovery.rb | Templater.Discovery.discover! | def discover!(scope)
@scopes = {}
generator_files.each do |file|
load file
end
@scopes[scope].each { |block| block.call } if @scopes[scope]
end | ruby | def discover!(scope)
@scopes = {}
generator_files.each do |file|
load file
end
@scopes[scope].each { |block| block.call } if @scopes[scope]
end | [
"def",
"discover!",
"(",
"scope",
")",
"@scopes",
"=",
"{",
"}",
"generator_files",
".",
"each",
"do",
"|",
"file",
"|",
"load",
"file",
"end",
"@scopes",
"[",
"scope",
"]",
".",
"each",
"{",
"|",
"block",
"|",
"block",
".",
"call",
"}",
"if",
"@scopes",
"[",
"scope",
"]",
"end"
] | Searches installed gems for Generators files and loads all code blocks in them that match
the given scope.
=== Parameters
scope<String>:: The name of the scope to search for | [
"Searches",
"installed",
"gems",
"for",
"Generators",
"files",
"and",
"loads",
"all",
"code",
"blocks",
"in",
"them",
"that",
"match",
"the",
"given",
"scope",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/gems/2.1.0/gems/templater-1.0.0/lib/templater/discovery.rb#L46-L52 | train |
rhomobile/rhodes | lib/extensions/rexml/rexml/node.rb | REXML.Node.each_recursive | def each_recursive(&block) # :yields: node
self.elements.each {|node|
block.call(node)
node.each_recursive(&block)
}
end | ruby | def each_recursive(&block) # :yields: node
self.elements.each {|node|
block.call(node)
node.each_recursive(&block)
}
end | [
"def",
"each_recursive",
"(",
"&",
"block",
")",
"# :yields: node",
"self",
".",
"elements",
".",
"each",
"{",
"|",
"node",
"|",
"block",
".",
"call",
"(",
"node",
")",
"node",
".",
"each_recursive",
"(",
"block",
")",
"}",
"end"
] | Visit all subnodes of +self+ recursively | [
"Visit",
"all",
"subnodes",
"of",
"+",
"self",
"+",
"recursively"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/rexml/rexml/node.rb#L53-L58 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/cookie.rb | WEBrick.Cookie.to_s | def to_s
ret = ""
ret << @name << "=" << @value
ret << "; " << "Version=" << @version.to_s if @version > 0
ret << "; " << "Domain=" << @domain if @domain
ret << "; " << "Expires=" << @expires if @expires
ret << "; " << "Max-Age=" << @max_age.to_s if @max_age
ret << "; " << "Comment=" << @comment if @comment
ret << "; " << "Path=" << @path if @path
ret << "; " << "Secure" if @secure
ret
end | ruby | def to_s
ret = ""
ret << @name << "=" << @value
ret << "; " << "Version=" << @version.to_s if @version > 0
ret << "; " << "Domain=" << @domain if @domain
ret << "; " << "Expires=" << @expires if @expires
ret << "; " << "Max-Age=" << @max_age.to_s if @max_age
ret << "; " << "Comment=" << @comment if @comment
ret << "; " << "Path=" << @path if @path
ret << "; " << "Secure" if @secure
ret
end | [
"def",
"to_s",
"ret",
"=",
"\"\"",
"ret",
"<<",
"@name",
"<<",
"\"=\"",
"<<",
"@value",
"ret",
"<<",
"\"; \"",
"<<",
"\"Version=\"",
"<<",
"@version",
".",
"to_s",
"if",
"@version",
">",
"0",
"ret",
"<<",
"\"; \"",
"<<",
"\"Domain=\"",
"<<",
"@domain",
"if",
"@domain",
"ret",
"<<",
"\"; \"",
"<<",
"\"Expires=\"",
"<<",
"@expires",
"if",
"@expires",
"ret",
"<<",
"\"; \"",
"<<",
"\"Max-Age=\"",
"<<",
"@max_age",
".",
"to_s",
"if",
"@max_age",
"ret",
"<<",
"\"; \"",
"<<",
"\"Comment=\"",
"<<",
"@comment",
"if",
"@comment",
"ret",
"<<",
"\"; \"",
"<<",
"\"Path=\"",
"<<",
"@path",
"if",
"@path",
"ret",
"<<",
"\"; \"",
"<<",
"\"Secure\"",
"if",
"@secure",
"ret",
"end"
] | The cookie string suitable for use in an HTTP header | [
"The",
"cookie",
"string",
"suitable",
"for",
"use",
"in",
"an",
"HTTP",
"header"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/webrick/cookie.rb#L93-L104 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb | Net.IMAP.disconnect | def disconnect
begin
begin
# try to call SSL::SSLSocket#io.
@sock.io.shutdown
rescue NoMethodError
# @sock is not an SSL::SSLSocket.
@sock.shutdown
end
rescue Errno::ENOTCONN
# ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
rescue Exception => e
@receiver_thread.raise(e)
end
@receiver_thread.join
synchronize do
unless @sock.closed?
@sock.close
end
end
raise e if e
end | ruby | def disconnect
begin
begin
# try to call SSL::SSLSocket#io.
@sock.io.shutdown
rescue NoMethodError
# @sock is not an SSL::SSLSocket.
@sock.shutdown
end
rescue Errno::ENOTCONN
# ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.
rescue Exception => e
@receiver_thread.raise(e)
end
@receiver_thread.join
synchronize do
unless @sock.closed?
@sock.close
end
end
raise e if e
end | [
"def",
"disconnect",
"begin",
"begin",
"# try to call SSL::SSLSocket#io.",
"@sock",
".",
"io",
".",
"shutdown",
"rescue",
"NoMethodError",
"# @sock is not an SSL::SSLSocket.",
"@sock",
".",
"shutdown",
"end",
"rescue",
"Errno",
"::",
"ENOTCONN",
"# ignore `Errno::ENOTCONN: Socket is not connected' on some platforms.",
"rescue",
"Exception",
"=>",
"e",
"@receiver_thread",
".",
"raise",
"(",
"e",
")",
"end",
"@receiver_thread",
".",
"join",
"synchronize",
"do",
"unless",
"@sock",
".",
"closed?",
"@sock",
".",
"close",
"end",
"end",
"raise",
"e",
"if",
"e",
"end"
] | Disconnects from the server. | [
"Disconnects",
"from",
"the",
"server",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb#L315-L336 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb | Net.IMAP.starttls | def starttls(options = {}, verify = true)
send_command("STARTTLS") do |resp|
if resp.kind_of?(TaggedResponse) && resp.name == "OK"
begin
# for backward compatibility
certs = options.to_str
options = create_ssl_params(certs, verify)
rescue NoMethodError
end
start_tls_session(options)
end
end
end | ruby | def starttls(options = {}, verify = true)
send_command("STARTTLS") do |resp|
if resp.kind_of?(TaggedResponse) && resp.name == "OK"
begin
# for backward compatibility
certs = options.to_str
options = create_ssl_params(certs, verify)
rescue NoMethodError
end
start_tls_session(options)
end
end
end | [
"def",
"starttls",
"(",
"options",
"=",
"{",
"}",
",",
"verify",
"=",
"true",
")",
"send_command",
"(",
"\"STARTTLS\"",
")",
"do",
"|",
"resp",
"|",
"if",
"resp",
".",
"kind_of?",
"(",
"TaggedResponse",
")",
"&&",
"resp",
".",
"name",
"==",
"\"OK\"",
"begin",
"# for backward compatibility",
"certs",
"=",
"options",
".",
"to_str",
"options",
"=",
"create_ssl_params",
"(",
"certs",
",",
"verify",
")",
"rescue",
"NoMethodError",
"end",
"start_tls_session",
"(",
"options",
")",
"end",
"end",
"end"
] | Sends a STARTTLS command to start TLS session. | [
"Sends",
"a",
"STARTTLS",
"command",
"to",
"start",
"TLS",
"session",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb#L372-L384 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb | Net.IMAP.idle | def idle(&response_handler)
raise LocalJumpError, "no block given" unless response_handler
response = nil
synchronize do
tag = Thread.current[:net_imap_tag] = generate_tag
put_string("#{tag} IDLE#{CRLF}")
begin
add_response_handler(response_handler)
@idle_done_cond = new_cond
@idle_done_cond.wait
@idle_done_cond = nil
if @receiver_thread_terminating
raise Net::IMAP::Error, "connection closed"
end
ensure
unless @receiver_thread_terminating
remove_response_handler(response_handler)
put_string("DONE#{CRLF}")
response = get_tagged_response(tag, "IDLE")
end
end
end
return response
end | ruby | def idle(&response_handler)
raise LocalJumpError, "no block given" unless response_handler
response = nil
synchronize do
tag = Thread.current[:net_imap_tag] = generate_tag
put_string("#{tag} IDLE#{CRLF}")
begin
add_response_handler(response_handler)
@idle_done_cond = new_cond
@idle_done_cond.wait
@idle_done_cond = nil
if @receiver_thread_terminating
raise Net::IMAP::Error, "connection closed"
end
ensure
unless @receiver_thread_terminating
remove_response_handler(response_handler)
put_string("DONE#{CRLF}")
response = get_tagged_response(tag, "IDLE")
end
end
end
return response
end | [
"def",
"idle",
"(",
"&",
"response_handler",
")",
"raise",
"LocalJumpError",
",",
"\"no block given\"",
"unless",
"response_handler",
"response",
"=",
"nil",
"synchronize",
"do",
"tag",
"=",
"Thread",
".",
"current",
"[",
":net_imap_tag",
"]",
"=",
"generate_tag",
"put_string",
"(",
"\"#{tag} IDLE#{CRLF}\"",
")",
"begin",
"add_response_handler",
"(",
"response_handler",
")",
"@idle_done_cond",
"=",
"new_cond",
"@idle_done_cond",
".",
"wait",
"@idle_done_cond",
"=",
"nil",
"if",
"@receiver_thread_terminating",
"raise",
"Net",
"::",
"IMAP",
"::",
"Error",
",",
"\"connection closed\"",
"end",
"ensure",
"unless",
"@receiver_thread_terminating",
"remove_response_handler",
"(",
"response_handler",
")",
"put_string",
"(",
"\"DONE#{CRLF}\"",
")",
"response",
"=",
"get_tagged_response",
"(",
"tag",
",",
"\"IDLE\"",
")",
"end",
"end",
"end",
"return",
"response",
"end"
] | Sends an IDLE command that waits for notifications of new or expunged
messages. Yields responses from the server during the IDLE.
Use #idle_done() to leave IDLE. | [
"Sends",
"an",
"IDLE",
"command",
"that",
"waits",
"for",
"notifications",
"of",
"new",
"or",
"expunged",
"messages",
".",
"Yields",
"responses",
"from",
"the",
"server",
"during",
"the",
"IDLE",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/imap.rb#L910-L937 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.get | def get(path, initheader = {}, dest = nil, &block) # :yield: +body_segment+
res = nil
request(Get.new(path, initheader)) {|r|
r.read_body dest, &block
res = r
}
res
end | ruby | def get(path, initheader = {}, dest = nil, &block) # :yield: +body_segment+
res = nil
request(Get.new(path, initheader)) {|r|
r.read_body dest, &block
res = r
}
res
end | [
"def",
"get",
"(",
"path",
",",
"initheader",
"=",
"{",
"}",
",",
"dest",
"=",
"nil",
",",
"&",
"block",
")",
"# :yield: +body_segment+",
"res",
"=",
"nil",
"request",
"(",
"Get",
".",
"new",
"(",
"path",
",",
"initheader",
")",
")",
"{",
"|",
"r",
"|",
"r",
".",
"read_body",
"dest",
",",
"block",
"res",
"=",
"r",
"}",
"res",
"end"
] | Retrieves data from +path+ on the connected-to host which may be an
absolute path String or a URI to extract the path from.
+initheader+ must be a Hash like { 'Accept' => '*/*', ... },
and it defaults to an empty hash.
If +initheader+ doesn't have the key 'accept-encoding', then
a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
so that gzip compression is used in preference to deflate
compression, which is used in preference to no compression.
Ruby doesn't have libraries to support the compress (Lempel-Ziv)
compression, so that is not supported. The intent of this is
to reduce bandwidth by default. If this routine sets up
compression, then it does the decompression also, removing
the header as well to prevent confusion. Otherwise
it leaves the body as it found it.
This method returns a Net::HTTPResponse object.
If called with a block, yields each fragment of the
entity body in turn as a string as it is read from
the socket. Note that in this case, the returned response
object will *not* contain a (meaningful) body.
+dest+ argument is obsolete.
It still works but you must not use it.
This method never raises an exception.
response = http.get('/index.html')
# using block
File.open('result.txt', 'w') {|f|
http.get('/~foo/') do |str|
f.write str
end
} | [
"Retrieves",
"data",
"from",
"+",
"path",
"+",
"on",
"the",
"connected",
"-",
"to",
"host",
"which",
"may",
"be",
"an",
"absolute",
"path",
"String",
"or",
"a",
"URI",
"to",
"extract",
"the",
"path",
"from",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1126-L1133 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.patch | def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Patch, &block)
end | ruby | def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
send_entity(path, data, initheader, dest, Patch, &block)
end | [
"def",
"patch",
"(",
"path",
",",
"data",
",",
"initheader",
"=",
"nil",
",",
"dest",
"=",
"nil",
",",
"&",
"block",
")",
"# :yield: +body_segment+",
"send_entity",
"(",
"path",
",",
"data",
",",
"initheader",
",",
"dest",
",",
"Patch",
",",
"block",
")",
"end"
] | Sends a PATCH request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"PATCH",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1186-L1188 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.proppatch | def proppatch(path, body, initheader = nil)
request(Proppatch.new(path, initheader), body)
end | ruby | def proppatch(path, body, initheader = nil)
request(Proppatch.new(path, initheader), body)
end | [
"def",
"proppatch",
"(",
"path",
",",
"body",
",",
"initheader",
"=",
"nil",
")",
"request",
"(",
"Proppatch",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"body",
")",
"end"
] | Sends a PROPPATCH request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"PROPPATCH",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1196-L1198 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.lock | def lock(path, body, initheader = nil)
request(Lock.new(path, initheader), body)
end | ruby | def lock(path, body, initheader = nil)
request(Lock.new(path, initheader), body)
end | [
"def",
"lock",
"(",
"path",
",",
"body",
",",
"initheader",
"=",
"nil",
")",
"request",
"(",
"Lock",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"body",
")",
"end"
] | Sends a LOCK request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"LOCK",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1202-L1204 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.unlock | def unlock(path, body, initheader = nil)
request(Unlock.new(path, initheader), body)
end | ruby | def unlock(path, body, initheader = nil)
request(Unlock.new(path, initheader), body)
end | [
"def",
"unlock",
"(",
"path",
",",
"body",
",",
"initheader",
"=",
"nil",
")",
"request",
"(",
"Unlock",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"body",
")",
"end"
] | Sends a UNLOCK request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"UNLOCK",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1208-L1210 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.propfind | def propfind(path, body = nil, initheader = {'Depth' => '0'})
request(Propfind.new(path, initheader), body)
end | ruby | def propfind(path, body = nil, initheader = {'Depth' => '0'})
request(Propfind.new(path, initheader), body)
end | [
"def",
"propfind",
"(",
"path",
",",
"body",
"=",
"nil",
",",
"initheader",
"=",
"{",
"'Depth'",
"=>",
"'0'",
"}",
")",
"request",
"(",
"Propfind",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"body",
")",
"end"
] | Sends a PROPFIND request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"PROPFIND",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1220-L1222 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.mkcol | def mkcol(path, body = nil, initheader = nil)
request(Mkcol.new(path, initheader), body)
end | ruby | def mkcol(path, body = nil, initheader = nil)
request(Mkcol.new(path, initheader), body)
end | [
"def",
"mkcol",
"(",
"path",
",",
"body",
"=",
"nil",
",",
"initheader",
"=",
"nil",
")",
"request",
"(",
"Mkcol",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"body",
")",
"end"
] | Sends a MKCOL request to the +path+ and gets a response,
as an HTTPResponse object. | [
"Sends",
"a",
"MKCOL",
"request",
"to",
"the",
"+",
"path",
"+",
"and",
"gets",
"a",
"response",
"as",
"an",
"HTTPResponse",
"object",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1244-L1246 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.request_post | def request_post(path, data, initheader = nil, &block) # :yield: +response+
request Post.new(path, initheader), data, &block
end | ruby | def request_post(path, data, initheader = nil, &block) # :yield: +response+
request Post.new(path, initheader), data, &block
end | [
"def",
"request_post",
"(",
"path",
",",
"data",
",",
"initheader",
"=",
"nil",
",",
"&",
"block",
")",
"# :yield: +response+",
"request",
"Post",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"data",
",",
"block",
"end"
] | Sends a POST request to the +path+.
Returns the response as a Net::HTTPResponse object.
When called with a block, the block is passed an HTTPResponse
object. The body of that response will not have been read yet;
the block can process it using HTTPResponse#read_body, if desired.
Returns the response.
This method never raises Net::* exceptions.
# example
response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
p response.status
puts response.body # body is already read in this case
# using block
http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
p response.status
p response['content-type']
response.read_body do |str| # read body now
print str
end
} | [
"Sends",
"a",
"POST",
"request",
"to",
"the",
"+",
"path",
"+",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1323-L1325 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.request | def request(req, body = nil, &block) # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end
if proxy_user()
req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
end
req.set_body_internal body
res = transport_request(req, &block)
if sspi_auth?(res)
sspi_auth(req)
res = transport_request(req, &block)
end
res
end | ruby | def request(req, body = nil, &block) # :yield: +response+
unless started?
start {
req['connection'] ||= 'close'
return request(req, body, &block)
}
end
if proxy_user()
req.proxy_basic_auth proxy_user(), proxy_pass() unless use_ssl?
end
req.set_body_internal body
res = transport_request(req, &block)
if sspi_auth?(res)
sspi_auth(req)
res = transport_request(req, &block)
end
res
end | [
"def",
"request",
"(",
"req",
",",
"body",
"=",
"nil",
",",
"&",
"block",
")",
"# :yield: +response+",
"unless",
"started?",
"start",
"{",
"req",
"[",
"'connection'",
"]",
"||=",
"'close'",
"return",
"request",
"(",
"req",
",",
"body",
",",
"block",
")",
"}",
"end",
"if",
"proxy_user",
"(",
")",
"req",
".",
"proxy_basic_auth",
"proxy_user",
"(",
")",
",",
"proxy_pass",
"(",
")",
"unless",
"use_ssl?",
"end",
"req",
".",
"set_body_internal",
"body",
"res",
"=",
"transport_request",
"(",
"req",
",",
"block",
")",
"if",
"sspi_auth?",
"(",
"res",
")",
"sspi_auth",
"(",
"req",
")",
"res",
"=",
"transport_request",
"(",
"req",
",",
"block",
")",
"end",
"res",
"end"
] | Sends an HTTPRequest object +req+ to the HTTP server.
If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
data, the data is also sent. Providing data for a Net::HTTP::Head or
Net::HTTP::Get request results in an ArgumentError.
Returns an HTTPResponse object.
When called with a block, passes an HTTPResponse object to the block.
The body of the response will not have been read yet;
the block can process it using HTTPResponse#read_body,
if desired.
This method never raises Net::* exceptions. | [
"Sends",
"an",
"HTTPRequest",
"object",
"+",
"req",
"+",
"to",
"the",
"HTTP",
"server",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1367-L1384 | train |
rhomobile/rhodes | res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb | Net.HTTP.send_entity | def send_entity(path, data, initheader, dest, type, &block)
res = nil
request(type.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
res
end | ruby | def send_entity(path, data, initheader, dest, type, &block)
res = nil
request(type.new(path, initheader), data) {|r|
r.read_body dest, &block
res = r
}
res
end | [
"def",
"send_entity",
"(",
"path",
",",
"data",
",",
"initheader",
",",
"dest",
",",
"type",
",",
"&",
"block",
")",
"res",
"=",
"nil",
"request",
"(",
"type",
".",
"new",
"(",
"path",
",",
"initheader",
")",
",",
"data",
")",
"{",
"|",
"r",
"|",
"r",
".",
"read_body",
"dest",
",",
"block",
"res",
"=",
"r",
"}",
"res",
"end"
] | Executes a request which uses a representation
and returns its body. | [
"Executes",
"a",
"request",
"which",
"uses",
"a",
"representation",
"and",
"returns",
"its",
"body",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/res/build-tools/ruby-standalone/212/usr/local/lib/ruby/2.1.0/net/http.rb#L1390-L1397 | train |
rhomobile/rhodes | lib/extensions/openssl/openssl/config.rb | OpenSSL.Config.get_value | def get_value(section, key)
if section.nil?
raise TypeError.new('nil not allowed')
end
section = 'default' if section.empty?
get_key_string(section, key)
end | ruby | def get_value(section, key)
if section.nil?
raise TypeError.new('nil not allowed')
end
section = 'default' if section.empty?
get_key_string(section, key)
end | [
"def",
"get_value",
"(",
"section",
",",
"key",
")",
"if",
"section",
".",
"nil?",
"raise",
"TypeError",
".",
"new",
"(",
"'nil not allowed'",
")",
"end",
"section",
"=",
"'default'",
"if",
"section",
".",
"empty?",
"get_key_string",
"(",
"section",
",",
"key",
")",
"end"
] | Creates an instance of OpenSSL's configuration class.
This can be used in contexts like OpenSSL::X509::ExtensionFactory.config=
If the optional +filename+ parameter is provided, then it is read in and
parsed via #parse_config.
This can raise IO exceptions based on the access, or availability of the
file. A ConfigError exception may be raised depending on the validity of
the data being configured.
Gets the value of +key+ from the given +section+
Given the following configurating file being loaded:
config = OpenSSL::Config.load('foo.cnf')
#=> #<OpenSSL::Config sections=["default"]>
puts config.to_s
#=> [ default ]
# foo=bar
You can get a specific value from the config if you know the +section+
and +key+ like so:
config.get_value('default','foo')
#=> "bar" | [
"Creates",
"an",
"instance",
"of",
"OpenSSL",
"s",
"configuration",
"class",
"."
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/openssl/openssl/config.rb#L274-L280 | train |
rhomobile/rhodes | lib/extensions/openssl/openssl/config.rb | OpenSSL.Config.[]= | def []=(section, pairs)
check_modify
@data[section] ||= {}
pairs.each do |key, value|
self.add_value(section, key, value)
end
end | ruby | def []=(section, pairs)
check_modify
@data[section] ||= {}
pairs.each do |key, value|
self.add_value(section, key, value)
end
end | [
"def",
"[]=",
"(",
"section",
",",
"pairs",
")",
"check_modify",
"@data",
"[",
"section",
"]",
"||=",
"{",
"}",
"pairs",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"self",
".",
"add_value",
"(",
"section",
",",
"key",
",",
"value",
")",
"end",
"end"
] | Sets a specific +section+ name with a Hash +pairs+
Given the following configuration being created:
config = OpenSSL::Config.new
#=> #<OpenSSL::Config sections=[]>
config['default'] = {"foo"=>"bar","baz"=>"buz"}
#=> {"foo"=>"bar", "baz"=>"buz"}
puts config.to_s
#=> [ default ]
# foo=bar
# baz=buz
It's important to note that this will essentially merge any of the keys
in +pairs+ with the existing +section+. For example:
config['default']
#=> {"foo"=>"bar", "baz"=>"buz"}
config['default'] = {"foo" => "changed"}
#=> {"foo"=>"changed"}
config['default']
#=> {"foo"=>"changed", "baz"=>"buz"} | [
"Sets",
"a",
"specific",
"+",
"section",
"+",
"name",
"with",
"a",
"Hash",
"+",
"pairs",
"+"
] | 3c5f87b1a44f0ba2865ca0e1dd780dd202f64872 | https://github.com/rhomobile/rhodes/blob/3c5f87b1a44f0ba2865ca0e1dd780dd202f64872/lib/extensions/openssl/openssl/config.rb#L377-L383 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.