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 |
---|---|---|---|---|---|---|---|---|---|---|---|
cldwalker/hirb | lib/hirb/util.rb | Hirb.Util.find_home | def find_home
['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] }
return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH']
File.expand_path("~")
rescue
File::ALT_SEPARATOR ? "C:/" : "/"
end | ruby | def find_home
['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] }
return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH']
File.expand_path("~")
rescue
File::ALT_SEPARATOR ? "C:/" : "/"
end | [
"def",
"find_home",
"[",
"'HOME'",
",",
"'USERPROFILE'",
"]",
".",
"each",
"{",
"|",
"e",
"|",
"return",
"ENV",
"[",
"e",
"]",
"if",
"ENV",
"[",
"e",
"]",
"}",
"return",
"\"#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}\"",
"if",
"ENV",
"[",
"'HOMEDRIVE'",
"]",
"&&",
"ENV",
"[",
"'HOMEPATH'",
"]",
"File",
".",
"expand_path",
"(",
"\"~\"",
")",
"rescue",
"File",
"::",
"ALT_SEPARATOR",
"?",
"\"C:/\"",
":",
"\"/\"",
"end"
] | From Rubygems, determine a user's home. | [
"From",
"Rubygems",
"determine",
"a",
"user",
"s",
"home",
"."
] | 264f72c7c0f0966001e802414a5b0641036c7860 | https://github.com/cldwalker/hirb/blob/264f72c7c0f0966001e802414a5b0641036c7860/lib/hirb/util.rb#L88-L94 | train |
sendgrid/ruby-http-client | lib/ruby_http_client.rb | SendGrid.Client.build_args | def build_args(args)
args.each do |arg|
arg.each do |key, value|
case key.to_s
when 'query_params'
@query_params = value
when 'request_headers'
update_headers(value)
when 'request_body'
@request_body = value
end
end
end
end | ruby | def build_args(args)
args.each do |arg|
arg.each do |key, value|
case key.to_s
when 'query_params'
@query_params = value
when 'request_headers'
update_headers(value)
when 'request_body'
@request_body = value
end
end
end
end | [
"def",
"build_args",
"(",
"args",
")",
"args",
".",
"each",
"do",
"|",
"arg",
"|",
"arg",
".",
"each",
"do",
"|",
"key",
",",
"value",
"|",
"case",
"key",
".",
"to_s",
"when",
"'query_params'",
"@query_params",
"=",
"value",
"when",
"'request_headers'",
"update_headers",
"(",
"value",
")",
"when",
"'request_body'",
"@request_body",
"=",
"value",
"end",
"end",
"end",
"end"
] | Set the query params, request headers and request body
* *Args* :
- +args+ -> array of args obtained from method_missing | [
"Set",
"the",
"query",
"params",
"request",
"headers",
"and",
"request",
"body"
] | 37fb6943258dd8dec0cd7fc5e7d54704471b97cc | https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L106-L119 | train |
sendgrid/ruby-http-client | lib/ruby_http_client.rb | SendGrid.Client.build_url | def build_url(query_params: nil)
url = [add_version(''), *@url_path].join('/')
url = build_query_params(url, query_params) if query_params
URI.parse("#{@host}#{url}")
end | ruby | def build_url(query_params: nil)
url = [add_version(''), *@url_path].join('/')
url = build_query_params(url, query_params) if query_params
URI.parse("#{@host}#{url}")
end | [
"def",
"build_url",
"(",
"query_params",
":",
"nil",
")",
"url",
"=",
"[",
"add_version",
"(",
"''",
")",
",",
"@url_path",
"]",
".",
"join",
"(",
"'/'",
")",
"url",
"=",
"build_query_params",
"(",
"url",
",",
"query_params",
")",
"if",
"query_params",
"URI",
".",
"parse",
"(",
"\"#{@host}#{url}\"",
")",
"end"
] | Build the final url
* *Args* :
- +query_params+ -> A hash of query parameters
* *Returns* :
- The final url string | [
"Build",
"the",
"final",
"url"
] | 37fb6943258dd8dec0cd7fc5e7d54704471b97cc | https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L128-L132 | train |
sendgrid/ruby-http-client | lib/ruby_http_client.rb | SendGrid.Client.make_request | def make_request(http, request)
response = http.request(request)
Response.new(response)
end | ruby | def make_request(http, request)
response = http.request(request)
Response.new(response)
end | [
"def",
"make_request",
"(",
"http",
",",
"request",
")",
"response",
"=",
"http",
".",
"request",
"(",
"request",
")",
"Response",
".",
"new",
"(",
"response",
")",
"end"
] | Make the API call and return the response. This is separated into
it's own function, so we can mock it easily for testing.
* *Args* :
- +http+ -> NET:HTTP request object
- +request+ -> NET::HTTP request object
* *Returns* :
- Response object | [
"Make",
"the",
"API",
"call",
"and",
"return",
"the",
"response",
".",
"This",
"is",
"separated",
"into",
"it",
"s",
"own",
"function",
"so",
"we",
"can",
"mock",
"it",
"easily",
"for",
"testing",
"."
] | 37fb6943258dd8dec0cd7fc5e7d54704471b97cc | https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L174-L177 | train |
sendgrid/ruby-http-client | lib/ruby_http_client.rb | SendGrid.Client.build_http | def build_http(host, port)
params = [host, port]
params += @proxy_options.values_at(:host, :port, :user, :pass) unless @proxy_options.empty?
add_ssl(Net::HTTP.new(*params))
end | ruby | def build_http(host, port)
params = [host, port]
params += @proxy_options.values_at(:host, :port, :user, :pass) unless @proxy_options.empty?
add_ssl(Net::HTTP.new(*params))
end | [
"def",
"build_http",
"(",
"host",
",",
"port",
")",
"params",
"=",
"[",
"host",
",",
"port",
"]",
"params",
"+=",
"@proxy_options",
".",
"values_at",
"(",
":host",
",",
":port",
",",
":user",
",",
":pass",
")",
"unless",
"@proxy_options",
".",
"empty?",
"add_ssl",
"(",
"Net",
"::",
"HTTP",
".",
"new",
"(",
"params",
")",
")",
"end"
] | Build HTTP request object
* *Returns* :
- Request object | [
"Build",
"HTTP",
"request",
"object"
] | 37fb6943258dd8dec0cd7fc5e7d54704471b97cc | https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L183-L187 | train |
sendgrid/ruby-http-client | lib/ruby_http_client.rb | SendGrid.Client.add_ssl | def add_ssl(http)
if host.start_with?('https')
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
http
end | ruby | def add_ssl(http)
if host.start_with?('https')
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
http
end | [
"def",
"add_ssl",
"(",
"http",
")",
"if",
"host",
".",
"start_with?",
"(",
"'https'",
")",
"http",
".",
"use_ssl",
"=",
"true",
"http",
".",
"verify_mode",
"=",
"OpenSSL",
"::",
"SSL",
"::",
"VERIFY_PEER",
"end",
"http",
"end"
] | Allow for https calls
* *Args* :
- +http+ -> HTTP::NET object
* *Returns* :
- HTTP::NET object | [
"Allow",
"for",
"https",
"calls"
] | 37fb6943258dd8dec0cd7fc5e7d54704471b97cc | https://github.com/sendgrid/ruby-http-client/blob/37fb6943258dd8dec0cd7fc5e7d54704471b97cc/lib/ruby_http_client.rb#L196-L202 | train |
soveran/ohm | lib/ohm.rb | Ohm.Collection.fetch | def fetch(ids)
data = nil
model.synchronize do
ids.each do |id|
redis.queue("HGETALL", namespace[id])
end
data = redis.commit
end
return [] if data.nil?
[].tap do |result|
data.each_with_index do |atts, idx|
result << model.new(Utils.dict(atts).update(:id => ids[idx]))
end
end
end | ruby | def fetch(ids)
data = nil
model.synchronize do
ids.each do |id|
redis.queue("HGETALL", namespace[id])
end
data = redis.commit
end
return [] if data.nil?
[].tap do |result|
data.each_with_index do |atts, idx|
result << model.new(Utils.dict(atts).update(:id => ids[idx]))
end
end
end | [
"def",
"fetch",
"(",
"ids",
")",
"data",
"=",
"nil",
"model",
".",
"synchronize",
"do",
"ids",
".",
"each",
"do",
"|",
"id",
"|",
"redis",
".",
"queue",
"(",
"\"HGETALL\"",
",",
"namespace",
"[",
"id",
"]",
")",
"end",
"data",
"=",
"redis",
".",
"commit",
"end",
"return",
"[",
"]",
"if",
"data",
".",
"nil?",
"[",
"]",
".",
"tap",
"do",
"|",
"result",
"|",
"data",
".",
"each_with_index",
"do",
"|",
"atts",
",",
"idx",
"|",
"result",
"<<",
"model",
".",
"new",
"(",
"Utils",
".",
"dict",
"(",
"atts",
")",
".",
"update",
"(",
":id",
"=>",
"ids",
"[",
"idx",
"]",
")",
")",
"end",
"end",
"end"
] | Wraps the whole pipelining functionality. | [
"Wraps",
"the",
"whole",
"pipelining",
"functionality",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L140-L158 | train |
soveran/ohm | lib/ohm.rb | Ohm.Set.sort | def sort(options = {})
if options.has_key?(:get)
options[:get] = to_key(options[:get])
Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)])
else
fetch(Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)]))
end
end | ruby | def sort(options = {})
if options.has_key?(:get)
options[:get] = to_key(options[:get])
Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)])
else
fetch(Stal.solve(redis, ["SORT", key, *Utils.sort_options(options)]))
end
end | [
"def",
"sort",
"(",
"options",
"=",
"{",
"}",
")",
"if",
"options",
".",
"has_key?",
"(",
":get",
")",
"options",
"[",
":get",
"]",
"=",
"to_key",
"(",
"options",
"[",
":get",
"]",
")",
"Stal",
".",
"solve",
"(",
"redis",
",",
"[",
"\"SORT\"",
",",
"key",
",",
"Utils",
".",
"sort_options",
"(",
"options",
")",
"]",
")",
"else",
"fetch",
"(",
"Stal",
".",
"solve",
"(",
"redis",
",",
"[",
"\"SORT\"",
",",
"key",
",",
"Utils",
".",
"sort_options",
"(",
"options",
")",
"]",
")",
")",
"end",
"end"
] | Allows you to sort your models using their IDs. This is much
faster than `sort_by`. If you simply want to get records in
ascending or descending order, then this is the best method to
do that.
Example:
class User < Ohm::Model
attribute :name
end
User.create(:name => "John")
User.create(:name => "Jane")
User.all.sort.map(&:id) == ["1", "2"]
# => true
User.all.sort(:order => "ASC").map(&:id) == ["1", "2"]
# => true
User.all.sort(:order => "DESC").map(&:id) == ["2", "1"]
# => true | [
"Allows",
"you",
"to",
"sort",
"your",
"models",
"using",
"their",
"IDs",
".",
"This",
"is",
"much",
"faster",
"than",
"sort_by",
".",
"If",
"you",
"simply",
"want",
"to",
"get",
"records",
"in",
"ascending",
"or",
"descending",
"order",
"then",
"this",
"is",
"the",
"best",
"method",
"to",
"do",
"that",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L451-L459 | train |
soveran/ohm | lib/ohm.rb | Ohm.Set.find | def find(dict)
Ohm::Set.new(
model, namespace, [:SINTER, key, *model.filters(dict)]
)
end | ruby | def find(dict)
Ohm::Set.new(
model, namespace, [:SINTER, key, *model.filters(dict)]
)
end | [
"def",
"find",
"(",
"dict",
")",
"Ohm",
"::",
"Set",
".",
"new",
"(",
"model",
",",
"namespace",
",",
"[",
":SINTER",
",",
"key",
",",
"model",
".",
"filters",
"(",
"dict",
")",
"]",
")",
"end"
] | Chain new fiters on an existing set.
Example:
set = User.find(:name => "John")
set.find(:age => 30) | [
"Chain",
"new",
"fiters",
"on",
"an",
"existing",
"set",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L521-L525 | train |
soveran/ohm | lib/ohm.rb | Ohm.MutableSet.replace | def replace(models)
ids = models.map(&:id)
model.synchronize do
redis.queue("MULTI")
redis.queue("DEL", key)
ids.each { |id| redis.queue("SADD", key, id) }
redis.queue("EXEC")
redis.commit
end
end | ruby | def replace(models)
ids = models.map(&:id)
model.synchronize do
redis.queue("MULTI")
redis.queue("DEL", key)
ids.each { |id| redis.queue("SADD", key, id) }
redis.queue("EXEC")
redis.commit
end
end | [
"def",
"replace",
"(",
"models",
")",
"ids",
"=",
"models",
".",
"map",
"(",
":id",
")",
"model",
".",
"synchronize",
"do",
"redis",
".",
"queue",
"(",
"\"MULTI\"",
")",
"redis",
".",
"queue",
"(",
"\"DEL\"",
",",
"key",
")",
"ids",
".",
"each",
"{",
"|",
"id",
"|",
"redis",
".",
"queue",
"(",
"\"SADD\"",
",",
"key",
",",
"id",
")",
"}",
"redis",
".",
"queue",
"(",
"\"EXEC\"",
")",
"redis",
".",
"commit",
"end",
"end"
] | Replace all the existing elements of a set with a different
collection of models. This happens atomically in a MULTI-EXEC
block.
Example:
user = User.create
p1 = Post.create
user.posts.add(p1)
p2, p3 = Post.create, Post.create
user.posts.replace([p2, p3])
user.posts.include?(p1)
# => false | [
"Replace",
"all",
"the",
"existing",
"elements",
"of",
"a",
"set",
"with",
"a",
"different",
"collection",
"of",
"models",
".",
"This",
"happens",
"atomically",
"in",
"a",
"MULTI",
"-",
"EXEC",
"block",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L636-L646 | train |
soveran/ohm | lib/ohm.rb | Ohm.Model.set | def set(att, val)
if val.to_s.empty?
key.call("HDEL", att)
else
key.call("HSET", att, val)
end
@attributes[att] = val
end | ruby | def set(att, val)
if val.to_s.empty?
key.call("HDEL", att)
else
key.call("HSET", att, val)
end
@attributes[att] = val
end | [
"def",
"set",
"(",
"att",
",",
"val",
")",
"if",
"val",
".",
"to_s",
".",
"empty?",
"key",
".",
"call",
"(",
"\"HDEL\"",
",",
"att",
")",
"else",
"key",
".",
"call",
"(",
"\"HSET\"",
",",
"att",
",",
"val",
")",
"end",
"@attributes",
"[",
"att",
"]",
"=",
"val",
"end"
] | Update an attribute value atomically. The best usecase for this
is when you simply want to update one value.
Note: This method is dangerous because it doesn't update indices
and uniques. Use it wisely. The safe equivalent is `update`. | [
"Update",
"an",
"attribute",
"value",
"atomically",
".",
"The",
"best",
"usecase",
"for",
"this",
"is",
"when",
"you",
"simply",
"want",
"to",
"update",
"one",
"value",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L1181-L1189 | train |
soveran/ohm | lib/ohm.rb | Ohm.Model.save | def save
indices = {}
model.indices.each do |field|
next unless (value = send(field))
indices[field] = Array(value).map(&:to_s)
end
uniques = {}
model.uniques.each do |field|
next unless (value = send(field))
uniques[field] = value.to_s
end
features = {
"name" => model.name
}
if defined?(@id)
features["id"] = @id
end
@id = script(LUA_SAVE, 0,
features.to_json,
_sanitized_attributes.to_json,
indices.to_json,
uniques.to_json
)
return self
end | ruby | def save
indices = {}
model.indices.each do |field|
next unless (value = send(field))
indices[field] = Array(value).map(&:to_s)
end
uniques = {}
model.uniques.each do |field|
next unless (value = send(field))
uniques[field] = value.to_s
end
features = {
"name" => model.name
}
if defined?(@id)
features["id"] = @id
end
@id = script(LUA_SAVE, 0,
features.to_json,
_sanitized_attributes.to_json,
indices.to_json,
uniques.to_json
)
return self
end | [
"def",
"save",
"indices",
"=",
"{",
"}",
"model",
".",
"indices",
".",
"each",
"do",
"|",
"field",
"|",
"next",
"unless",
"(",
"value",
"=",
"send",
"(",
"field",
")",
")",
"indices",
"[",
"field",
"]",
"=",
"Array",
"(",
"value",
")",
".",
"map",
"(",
":to_s",
")",
"end",
"uniques",
"=",
"{",
"}",
"model",
".",
"uniques",
".",
"each",
"do",
"|",
"field",
"|",
"next",
"unless",
"(",
"value",
"=",
"send",
"(",
"field",
")",
")",
"uniques",
"[",
"field",
"]",
"=",
"value",
".",
"to_s",
"end",
"features",
"=",
"{",
"\"name\"",
"=>",
"model",
".",
"name",
"}",
"if",
"defined?",
"(",
"@id",
")",
"features",
"[",
"\"id\"",
"]",
"=",
"@id",
"end",
"@id",
"=",
"script",
"(",
"LUA_SAVE",
",",
"0",
",",
"features",
".",
"to_json",
",",
"_sanitized_attributes",
".",
"to_json",
",",
"indices",
".",
"to_json",
",",
"uniques",
".",
"to_json",
")",
"return",
"self",
"end"
] | Persist the model attributes and update indices and unique
indices. The `counter`s and `set`s are not touched during save.
Example:
class User < Ohm::Model
attribute :name
end
u = User.new(:name => "John").save
u.kind_of?(User)
# => true | [
"Persist",
"the",
"model",
"attributes",
"and",
"update",
"indices",
"and",
"unique",
"indices",
".",
"The",
"counter",
"s",
"and",
"set",
"s",
"are",
"not",
"touched",
"during",
"save",
"."
] | 122407ee8fb2e8223bfa2cd10feea50e42dc49ae | https://github.com/soveran/ohm/blob/122407ee8fb2e8223bfa2cd10feea50e42dc49ae/lib/ohm.rb#L1365-L1394 | train |
robwierzbowski/jekyll-picture-tag | lib/jekyll-picture-tag/source_image.rb | PictureTag.SourceImage.grab_file | def grab_file(source_file)
source_name = File.join(PictureTag.config.source_dir, source_file)
unless File.exist? source_name
raise "Jekyll Picture Tag could not find #{source_name}."
end
source_name
end | ruby | def grab_file(source_file)
source_name = File.join(PictureTag.config.source_dir, source_file)
unless File.exist? source_name
raise "Jekyll Picture Tag could not find #{source_name}."
end
source_name
end | [
"def",
"grab_file",
"(",
"source_file",
")",
"source_name",
"=",
"File",
".",
"join",
"(",
"PictureTag",
".",
"config",
".",
"source_dir",
",",
"source_file",
")",
"unless",
"File",
".",
"exist?",
"source_name",
"raise",
"\"Jekyll Picture Tag could not find #{source_name}.\"",
"end",
"source_name",
"end"
] | Turn a relative filename into an absolute one, and make sure it exists. | [
"Turn",
"a",
"relative",
"filename",
"into",
"an",
"absolute",
"one",
"and",
"make",
"sure",
"it",
"exists",
"."
] | e63cf4e024d413880f6a252ab7d7a167c96b01af | https://github.com/robwierzbowski/jekyll-picture-tag/blob/e63cf4e024d413880f6a252ab7d7a167c96b01af/lib/jekyll-picture-tag/source_image.rb#L52-L60 | train |
Mange/roadie | lib/roadie/document.rb | Roadie.Document.transform | def transform
dom = Nokogiri::HTML.parse html
callback before_transformation, dom
improve dom
inline dom, keep_uninlinable_in: :head
rewrite_urls dom
callback after_transformation, dom
remove_ignore_markers dom
serialize_document dom
end | ruby | def transform
dom = Nokogiri::HTML.parse html
callback before_transformation, dom
improve dom
inline dom, keep_uninlinable_in: :head
rewrite_urls dom
callback after_transformation, dom
remove_ignore_markers dom
serialize_document dom
end | [
"def",
"transform",
"dom",
"=",
"Nokogiri",
"::",
"HTML",
".",
"parse",
"html",
"callback",
"before_transformation",
",",
"dom",
"improve",
"dom",
"inline",
"dom",
",",
"keep_uninlinable_in",
":",
":head",
"rewrite_urls",
"dom",
"callback",
"after_transformation",
",",
"dom",
"remove_ignore_markers",
"dom",
"serialize_document",
"dom",
"end"
] | Transform the input HTML as a full document and returns the processed
HTML.
Before the transformation begins, the {#before_transformation} callback
will be called with the parsed HTML tree and the {Document} instance, and
after all work is complete the {#after_transformation} callback will be
invoked in the same way.
Most of the work is delegated to other classes. A list of them can be
seen below.
@see MarkupImprover MarkupImprover (improves the markup of the DOM)
@see Inliner Inliner (inlines the stylesheets)
@see UrlRewriter UrlRewriter (rewrites URLs and makes them absolute)
@see #transform_partial Transforms partial documents (fragments)
@return [String] the transformed HTML | [
"Transform",
"the",
"input",
"HTML",
"as",
"a",
"full",
"document",
"and",
"returns",
"the",
"processed",
"HTML",
"."
] | afda57d66b7653a0978604f1d81cccd93e8748c9 | https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/document.rb#L80-L93 | train |
Mange/roadie | lib/roadie/asset_scanner.rb | Roadie.AssetScanner.extract_css | def extract_css
stylesheets = @dom.css(STYLE_ELEMENT_QUERY).map { |element|
stylesheet = read_stylesheet(element)
element.remove if stylesheet
stylesheet
}.compact
stylesheets
end | ruby | def extract_css
stylesheets = @dom.css(STYLE_ELEMENT_QUERY).map { |element|
stylesheet = read_stylesheet(element)
element.remove if stylesheet
stylesheet
}.compact
stylesheets
end | [
"def",
"extract_css",
"stylesheets",
"=",
"@dom",
".",
"css",
"(",
"STYLE_ELEMENT_QUERY",
")",
".",
"map",
"{",
"|",
"element",
"|",
"stylesheet",
"=",
"read_stylesheet",
"(",
"element",
")",
"element",
".",
"remove",
"if",
"stylesheet",
"stylesheet",
"}",
".",
"compact",
"stylesheets",
"end"
] | Looks for all non-ignored stylesheets, removes their references from the
DOM and then returns them.
This will mutate the DOM tree.
The order of the array corresponds with the document order in the DOM.
@see #find_css
@return [Enumerable<Stylesheet>] every extracted stylesheet | [
"Looks",
"for",
"all",
"non",
"-",
"ignored",
"stylesheets",
"removes",
"their",
"references",
"from",
"the",
"DOM",
"and",
"then",
"returns",
"them",
"."
] | afda57d66b7653a0978604f1d81cccd93e8748c9 | https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/asset_scanner.rb#L43-L50 | train |
Mange/roadie | lib/roadie/url_generator.rb | Roadie.UrlGenerator.generate_url | def generate_url(path, base = "/")
return root_uri.to_s if path.nil? or path.empty?
return path if path_is_anchor?(path)
return add_scheme(path) if path_is_schemeless?(path)
return path if Utils.path_is_absolute?(path)
combine_segments(root_uri, base, path).to_s
end | ruby | def generate_url(path, base = "/")
return root_uri.to_s if path.nil? or path.empty?
return path if path_is_anchor?(path)
return add_scheme(path) if path_is_schemeless?(path)
return path if Utils.path_is_absolute?(path)
combine_segments(root_uri, base, path).to_s
end | [
"def",
"generate_url",
"(",
"path",
",",
"base",
"=",
"\"/\"",
")",
"return",
"root_uri",
".",
"to_s",
"if",
"path",
".",
"nil?",
"or",
"path",
".",
"empty?",
"return",
"path",
"if",
"path_is_anchor?",
"(",
"path",
")",
"return",
"add_scheme",
"(",
"path",
")",
"if",
"path_is_schemeless?",
"(",
"path",
")",
"return",
"path",
"if",
"Utils",
".",
"path_is_absolute?",
"(",
"path",
")",
"combine_segments",
"(",
"root_uri",
",",
"base",
",",
"path",
")",
".",
"to_s",
"end"
] | Create a new instance with the given URL options.
Initializing without a host setting raises an error, as do unknown keys.
@param [Hash] url_options
@option url_options [String] :host (required)
@option url_options [String, Integer] :port
@option url_options [String] :path root path
@option url_options [String] :scheme URL scheme ("http" is default)
@option url_options [String] :protocol alias for :scheme
Generate an absolute URL from a relative URL.
If the passed path is already an absolute URL or just an anchor
reference, it will be returned as-is.
If passed a blank path, the "root URL" will be returned. The root URL is
the URL that the {#url_options} would generate by themselves.
An optional base can be specified. The base is another relative path from
the root that specifies an "offset" from which the path was found in. A
common use-case is to convert a relative path found in a stylesheet which
resides in a subdirectory.
@example Normal conversions
generator = Roadie::UrlGenerator.new host: "foo.com", scheme: "https"
generator.generate_url("bar.html") # => "https://foo.com/bar.html"
generator.generate_url("/bar.html") # => "https://foo.com/bar.html"
generator.generate_url("") # => "https://foo.com"
@example Conversions with a base
generator = Roadie::UrlGenerator.new host: "foo.com", scheme: "https"
generator.generate_url("../images/logo.png", "/css") # => "https://foo.com/images/logo.png"
generator.generate_url("../images/logo.png", "/assets/css") # => "https://foo.com/assets/images/logo.png"
@param [String] base The base which the relative path comes from
@return [String] an absolute URL | [
"Create",
"a",
"new",
"instance",
"with",
"the",
"given",
"URL",
"options",
"."
] | afda57d66b7653a0978604f1d81cccd93e8748c9 | https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/url_generator.rb#L58-L65 | train |
Mange/roadie | lib/roadie/inliner.rb | Roadie.Inliner.add_uninlinable_styles | def add_uninlinable_styles(parent, blocks, merge_media_queries)
return if blocks.empty?
parent_node =
case parent
when :head
find_head
when :root
dom
else
raise ArgumentError, "Parent must be either :head or :root. Was #{parent.inspect}"
end
create_style_element(blocks, parent_node, merge_media_queries)
end | ruby | def add_uninlinable_styles(parent, blocks, merge_media_queries)
return if blocks.empty?
parent_node =
case parent
when :head
find_head
when :root
dom
else
raise ArgumentError, "Parent must be either :head or :root. Was #{parent.inspect}"
end
create_style_element(blocks, parent_node, merge_media_queries)
end | [
"def",
"add_uninlinable_styles",
"(",
"parent",
",",
"blocks",
",",
"merge_media_queries",
")",
"return",
"if",
"blocks",
".",
"empty?",
"parent_node",
"=",
"case",
"parent",
"when",
":head",
"find_head",
"when",
":root",
"dom",
"else",
"raise",
"ArgumentError",
",",
"\"Parent must be either :head or :root. Was #{parent.inspect}\"",
"end",
"create_style_element",
"(",
"blocks",
",",
"parent_node",
",",
"merge_media_queries",
")",
"end"
] | Adds unlineable styles in the specified part of the document
either the head or in the document
@param [Symbol] parent Where to put the styles
@param [Array<StyleBlock>] blocks Non-inlineable style blocks
@param [Boolean] merge_media_queries Whether to group media queries | [
"Adds",
"unlineable",
"styles",
"in",
"the",
"specified",
"part",
"of",
"the",
"document",
"either",
"the",
"head",
"or",
"in",
"the",
"document"
] | afda57d66b7653a0978604f1d81cccd93e8748c9 | https://github.com/Mange/roadie/blob/afda57d66b7653a0978604f1d81cccd93e8748c9/lib/roadie/inliner.rb#L106-L120 | train |
geminabox/geminabox | lib/geminabox/gem_version_collection.rb | Geminabox.GemVersionCollection.by_name | def by_name(&block)
@grouped ||= @gems.group_by(&:name).map{|name, collection|
[name, Geminabox::GemVersionCollection.new(collection)]
}.sort_by{|name, collection|
name.downcase
}
if block_given?
@grouped.each(&block)
else
@grouped
end
end | ruby | def by_name(&block)
@grouped ||= @gems.group_by(&:name).map{|name, collection|
[name, Geminabox::GemVersionCollection.new(collection)]
}.sort_by{|name, collection|
name.downcase
}
if block_given?
@grouped.each(&block)
else
@grouped
end
end | [
"def",
"by_name",
"(",
"&",
"block",
")",
"@grouped",
"||=",
"@gems",
".",
"group_by",
"(",
":name",
")",
".",
"map",
"{",
"|",
"name",
",",
"collection",
"|",
"[",
"name",
",",
"Geminabox",
"::",
"GemVersionCollection",
".",
"new",
"(",
"collection",
")",
"]",
"}",
".",
"sort_by",
"{",
"|",
"name",
",",
"collection",
"|",
"name",
".",
"downcase",
"}",
"if",
"block_given?",
"@grouped",
".",
"each",
"(",
"block",
")",
"else",
"@grouped",
"end",
"end"
] | The collection can contain gems of different names, this method groups them
by name, and then sorts the different version of each name by version and
platform.
yields 'foo_gem', version_collection | [
"The",
"collection",
"can",
"contain",
"gems",
"of",
"different",
"names",
"this",
"method",
"groups",
"them",
"by",
"name",
"and",
"then",
"sorts",
"the",
"different",
"version",
"of",
"each",
"name",
"by",
"version",
"and",
"platform",
"."
] | 13ce5955f4794f2f1272ada66b4d786b81fd0850 | https://github.com/geminabox/geminabox/blob/13ce5955f4794f2f1272ada66b4d786b81fd0850/lib/geminabox/gem_version_collection.rb#L41-L53 | train |
chef/knife-azure | lib/azure/service_management/certificate.rb | Azure.Certificate.create_ssl_certificate | def create_ssl_certificate(cert_params)
file_path = cert_params[:output_file].sub(/\.(\w+)$/, "")
path = prompt_for_file_path
file_path = File.join(path, file_path) unless path.empty?
cert_params[:domain] = prompt_for_domain
rsa_key = generate_keypair cert_params[:key_length]
cert = generate_certificate(rsa_key, cert_params)
write_certificate_to_file cert, file_path, rsa_key, cert_params
puts "*" * 70
puts "Generated Certificates:"
puts "- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server."
puts "- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API."
puts "- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server."
puts "Certificate Thumbprint: #{@thumbprint.to_s.upcase}"
puts "*" * 70
Chef::Config[:knife][:ca_trust_file] = file_path + ".pem" if Chef::Config[:knife][:ca_trust_file].nil?
cert_data = File.read (file_path + ".b64")
add_certificate cert_data, @winrm_cert_passphrase, "pfx", cert_params[:azure_dns_name]
@thumbprint
end | ruby | def create_ssl_certificate(cert_params)
file_path = cert_params[:output_file].sub(/\.(\w+)$/, "")
path = prompt_for_file_path
file_path = File.join(path, file_path) unless path.empty?
cert_params[:domain] = prompt_for_domain
rsa_key = generate_keypair cert_params[:key_length]
cert = generate_certificate(rsa_key, cert_params)
write_certificate_to_file cert, file_path, rsa_key, cert_params
puts "*" * 70
puts "Generated Certificates:"
puts "- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server."
puts "- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API."
puts "- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server."
puts "Certificate Thumbprint: #{@thumbprint.to_s.upcase}"
puts "*" * 70
Chef::Config[:knife][:ca_trust_file] = file_path + ".pem" if Chef::Config[:knife][:ca_trust_file].nil?
cert_data = File.read (file_path + ".b64")
add_certificate cert_data, @winrm_cert_passphrase, "pfx", cert_params[:azure_dns_name]
@thumbprint
end | [
"def",
"create_ssl_certificate",
"(",
"cert_params",
")",
"file_path",
"=",
"cert_params",
"[",
":output_file",
"]",
".",
"sub",
"(",
"/",
"\\.",
"\\w",
"/",
",",
"\"\"",
")",
"path",
"=",
"prompt_for_file_path",
"file_path",
"=",
"File",
".",
"join",
"(",
"path",
",",
"file_path",
")",
"unless",
"path",
".",
"empty?",
"cert_params",
"[",
":domain",
"]",
"=",
"prompt_for_domain",
"rsa_key",
"=",
"generate_keypair",
"cert_params",
"[",
":key_length",
"]",
"cert",
"=",
"generate_certificate",
"(",
"rsa_key",
",",
"cert_params",
")",
"write_certificate_to_file",
"cert",
",",
"file_path",
",",
"rsa_key",
",",
"cert_params",
"puts",
"\"*\"",
"*",
"70",
"puts",
"\"Generated Certificates:\"",
"puts",
"\"- #{file_path}.pfx - PKCS12 format keypair. Contains both the public and private keys, usually used on the server.\"",
"puts",
"\"- #{file_path}.b64 - Base64 encoded PKCS12 keypair. Contains both the public and private keys, for upload to the Azure REST API.\"",
"puts",
"\"- #{file_path}.pem - Base64 encoded public certificate only. Required by the client to connect to the server.\"",
"puts",
"\"Certificate Thumbprint: #{@thumbprint.to_s.upcase}\"",
"puts",
"\"*\"",
"*",
"70",
"Chef",
"::",
"Config",
"[",
":knife",
"]",
"[",
":ca_trust_file",
"]",
"=",
"file_path",
"+",
"\".pem\"",
"if",
"Chef",
"::",
"Config",
"[",
":knife",
"]",
"[",
":ca_trust_file",
"]",
".",
"nil?",
"cert_data",
"=",
"File",
".",
"read",
"(",
"file_path",
"+",
"\".b64\"",
")",
"add_certificate",
"cert_data",
",",
"@winrm_cert_passphrase",
",",
"\"pfx\"",
",",
"cert_params",
"[",
":azure_dns_name",
"]",
"@thumbprint",
"end"
] | SSL certificate generation for knife-azure ssl bootstrap | [
"SSL",
"certificate",
"generation",
"for",
"knife",
"-",
"azure",
"ssl",
"bootstrap"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/certificate.rb#L128-L149 | train |
chef/knife-azure | lib/azure/service_management/image.rb | Azure.Images.get_images | def get_images(img_type)
images = Hash.new
if img_type == "OSImage"
response = @connection.query_azure("images")
elsif img_type == "VMImage"
response = @connection.query_azure("vmimages")
end
unless response.to_s.empty?
osimages = response.css(img_type)
osimages.each do |image|
item = Image.new(image)
images[item.name] = item
end
end
images
end | ruby | def get_images(img_type)
images = Hash.new
if img_type == "OSImage"
response = @connection.query_azure("images")
elsif img_type == "VMImage"
response = @connection.query_azure("vmimages")
end
unless response.to_s.empty?
osimages = response.css(img_type)
osimages.each do |image|
item = Image.new(image)
images[item.name] = item
end
end
images
end | [
"def",
"get_images",
"(",
"img_type",
")",
"images",
"=",
"Hash",
".",
"new",
"if",
"img_type",
"==",
"\"OSImage\"",
"response",
"=",
"@connection",
".",
"query_azure",
"(",
"\"images\"",
")",
"elsif",
"img_type",
"==",
"\"VMImage\"",
"response",
"=",
"@connection",
".",
"query_azure",
"(",
"\"vmimages\"",
")",
"end",
"unless",
"response",
".",
"to_s",
".",
"empty?",
"osimages",
"=",
"response",
".",
"css",
"(",
"img_type",
")",
"osimages",
".",
"each",
"do",
"|",
"image",
"|",
"item",
"=",
"Image",
".",
"new",
"(",
"image",
")",
"images",
"[",
"item",
".",
"name",
"]",
"=",
"item",
"end",
"end",
"images",
"end"
] | img_type = OSImages or VMImage | [
"img_type",
"=",
"OSImages",
"or",
"VMImage"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/image.rb#L39-L58 | train |
chef/knife-azure | lib/azure/service_management/storageaccount.rb | Azure.StorageAccounts.exists_on_cloud? | def exists_on_cloud?(name)
ret_val = @connection.query_azure("storageservices/#{name}")
error_code, error_message = error_from_response_xml(ret_val) if ret_val
if ret_val.nil? || error_code.length > 0
Chef::Log.warn "Unable to find storage account:" + error_message + " : " + error_message if ret_val
false
else
true
end
end | ruby | def exists_on_cloud?(name)
ret_val = @connection.query_azure("storageservices/#{name}")
error_code, error_message = error_from_response_xml(ret_val) if ret_val
if ret_val.nil? || error_code.length > 0
Chef::Log.warn "Unable to find storage account:" + error_message + " : " + error_message if ret_val
false
else
true
end
end | [
"def",
"exists_on_cloud?",
"(",
"name",
")",
"ret_val",
"=",
"@connection",
".",
"query_azure",
"(",
"\"storageservices/#{name}\"",
")",
"error_code",
",",
"error_message",
"=",
"error_from_response_xml",
"(",
"ret_val",
")",
"if",
"ret_val",
"if",
"ret_val",
".",
"nil?",
"||",
"error_code",
".",
"length",
">",
"0",
"Chef",
"::",
"Log",
".",
"warn",
"\"Unable to find storage account:\"",
"+",
"error_message",
"+",
"\" : \"",
"+",
"error_message",
"if",
"ret_val",
"false",
"else",
"true",
"end",
"end"
] | Look up on cloud and not local cache | [
"Look",
"up",
"on",
"cloud",
"and",
"not",
"local",
"cache"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/storageaccount.rb#L55-L64 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.subnets_list_for_specific_address_space | def subnets_list_for_specific_address_space(address_prefix, subnets_list)
list = []
address_space = IPAddress(address_prefix)
subnets_list.each do |sbn|
subnet_address_prefix = IPAddress(sbn.address_prefix)
## check if the subnet belongs to this address space or not ##
list << sbn if address_space.include? subnet_address_prefix
end
list
end | ruby | def subnets_list_for_specific_address_space(address_prefix, subnets_list)
list = []
address_space = IPAddress(address_prefix)
subnets_list.each do |sbn|
subnet_address_prefix = IPAddress(sbn.address_prefix)
## check if the subnet belongs to this address space or not ##
list << sbn if address_space.include? subnet_address_prefix
end
list
end | [
"def",
"subnets_list_for_specific_address_space",
"(",
"address_prefix",
",",
"subnets_list",
")",
"list",
"=",
"[",
"]",
"address_space",
"=",
"IPAddress",
"(",
"address_prefix",
")",
"subnets_list",
".",
"each",
"do",
"|",
"sbn",
"|",
"subnet_address_prefix",
"=",
"IPAddress",
"(",
"sbn",
".",
"address_prefix",
")",
"## check if the subnet belongs to this address space or not ##",
"list",
"<<",
"sbn",
"if",
"address_space",
".",
"include?",
"subnet_address_prefix",
"end",
"list",
"end"
] | lists subnets of only a specific virtual network address space | [
"lists",
"subnets",
"of",
"only",
"a",
"specific",
"virtual",
"network",
"address",
"space"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L26-L37 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.subnets_list | def subnets_list(resource_group_name, vnet_name, address_prefix = nil)
list = network_resource_client.subnets.list(resource_group_name, vnet_name)
!address_prefix.nil? && !list.empty? ? subnets_list_for_specific_address_space(address_prefix, list) : list
end | ruby | def subnets_list(resource_group_name, vnet_name, address_prefix = nil)
list = network_resource_client.subnets.list(resource_group_name, vnet_name)
!address_prefix.nil? && !list.empty? ? subnets_list_for_specific_address_space(address_prefix, list) : list
end | [
"def",
"subnets_list",
"(",
"resource_group_name",
",",
"vnet_name",
",",
"address_prefix",
"=",
"nil",
")",
"list",
"=",
"network_resource_client",
".",
"subnets",
".",
"list",
"(",
"resource_group_name",
",",
"vnet_name",
")",
"!",
"address_prefix",
".",
"nil?",
"&&",
"!",
"list",
".",
"empty?",
"?",
"subnets_list_for_specific_address_space",
"(",
"address_prefix",
",",
"list",
")",
":",
"list",
"end"
] | lists all subnets under a virtual network or lists subnets of only a particular address space | [
"lists",
"all",
"subnets",
"under",
"a",
"virtual",
"network",
"or",
"lists",
"subnets",
"of",
"only",
"a",
"particular",
"address",
"space"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L53-L56 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.sort_available_networks | def sort_available_networks(available_networks)
available_networks.sort_by { |nwrk| nwrk.network.address.split(".").map(&:to_i) }
end | ruby | def sort_available_networks(available_networks)
available_networks.sort_by { |nwrk| nwrk.network.address.split(".").map(&:to_i) }
end | [
"def",
"sort_available_networks",
"(",
"available_networks",
")",
"available_networks",
".",
"sort_by",
"{",
"|",
"nwrk",
"|",
"nwrk",
".",
"network",
".",
"address",
".",
"split",
"(",
"\".\"",
")",
".",
"map",
"(",
":to_i",
")",
"}",
"end"
] | sort available networks pool in ascending order based on the network's
IP address to allocate the network for the new subnet to be added in the
existing virtual network | [
"sort",
"available",
"networks",
"pool",
"in",
"ascending",
"order",
"based",
"on",
"the",
"network",
"s",
"IP",
"address",
"to",
"allocate",
"the",
"network",
"for",
"the",
"new",
"subnet",
"to",
"be",
"added",
"in",
"the",
"existing",
"virtual",
"network"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L81-L83 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.sort_subnets_by_cidr_prefix | def sort_subnets_by_cidr_prefix(subnets)
subnets.sort_by.with_index { |sbn, i| [subnet_address_prefix(sbn).split("/")[1].to_i, i] }
end | ruby | def sort_subnets_by_cidr_prefix(subnets)
subnets.sort_by.with_index { |sbn, i| [subnet_address_prefix(sbn).split("/")[1].to_i, i] }
end | [
"def",
"sort_subnets_by_cidr_prefix",
"(",
"subnets",
")",
"subnets",
".",
"sort_by",
".",
"with_index",
"{",
"|",
"sbn",
",",
"i",
"|",
"[",
"subnet_address_prefix",
"(",
"sbn",
")",
".",
"split",
"(",
"\"/\"",
")",
"[",
"1",
"]",
".",
"to_i",
",",
"i",
"]",
"}",
"end"
] | sort existing subnets in ascending order based on their cidr prefix or
netmask to have subnets with larger networks on the top | [
"sort",
"existing",
"subnets",
"in",
"ascending",
"order",
"based",
"on",
"their",
"cidr",
"prefix",
"or",
"netmask",
"to",
"have",
"subnets",
"with",
"larger",
"networks",
"on",
"the",
"top"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L87-L89 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.sort_used_networks_by_hosts_size | def sort_used_networks_by_hosts_size(used_network)
used_network.sort_by.with_index { |nwrk, i| [-nwrk.hosts.size, i] }
end | ruby | def sort_used_networks_by_hosts_size(used_network)
used_network.sort_by.with_index { |nwrk, i| [-nwrk.hosts.size, i] }
end | [
"def",
"sort_used_networks_by_hosts_size",
"(",
"used_network",
")",
"used_network",
".",
"sort_by",
".",
"with_index",
"{",
"|",
"nwrk",
",",
"i",
"|",
"[",
"-",
"nwrk",
".",
"hosts",
".",
"size",
",",
"i",
"]",
"}",
"end"
] | sort used networks pool in descending order based on the number of hosts
it contains, this helps to keep larger networks on top thereby eliminating
more number of entries in available_networks_pool at a faster pace | [
"sort",
"used",
"networks",
"pool",
"in",
"descending",
"order",
"based",
"on",
"the",
"number",
"of",
"hosts",
"it",
"contains",
"this",
"helps",
"to",
"keep",
"larger",
"networks",
"on",
"top",
"thereby",
"eliminating",
"more",
"number",
"of",
"entries",
"in",
"available_networks_pool",
"at",
"a",
"faster",
"pace"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L94-L96 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.divide_network | def divide_network(address_prefix)
network_address = IPAddress(address_prefix)
prefix = nil
case network_address.count
when 4097..65536
prefix = "20"
when 256..4096
prefix = "24"
end
## if the given network is small then do not divide it else divide using
## the prefix value calculated above ##
prefix.nil? ? address_prefix : network_address.network.address.concat("/" + prefix)
end | ruby | def divide_network(address_prefix)
network_address = IPAddress(address_prefix)
prefix = nil
case network_address.count
when 4097..65536
prefix = "20"
when 256..4096
prefix = "24"
end
## if the given network is small then do not divide it else divide using
## the prefix value calculated above ##
prefix.nil? ? address_prefix : network_address.network.address.concat("/" + prefix)
end | [
"def",
"divide_network",
"(",
"address_prefix",
")",
"network_address",
"=",
"IPAddress",
"(",
"address_prefix",
")",
"prefix",
"=",
"nil",
"case",
"network_address",
".",
"count",
"when",
"4097",
"..",
"65536",
"prefix",
"=",
"\"20\"",
"when",
"256",
"..",
"4096",
"prefix",
"=",
"\"24\"",
"end",
"## if the given network is small then do not divide it else divide using",
"## the prefix value calculated above ##",
"prefix",
".",
"nil?",
"?",
"address_prefix",
":",
"network_address",
".",
"network",
".",
"address",
".",
"concat",
"(",
"\"/\"",
"+",
"prefix",
")",
"end"
] | when a address space in an existing virtual network is not used at all
then divide the space into the number of subnets based on the total
number of hosts that network supports | [
"when",
"a",
"address",
"space",
"in",
"an",
"existing",
"virtual",
"network",
"is",
"not",
"used",
"at",
"all",
"then",
"divide",
"the",
"space",
"into",
"the",
"number",
"of",
"subnets",
"based",
"on",
"the",
"total",
"number",
"of",
"hosts",
"that",
"network",
"supports"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L111-L125 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.new_subnet_address_prefix | def new_subnet_address_prefix(vnet_address_prefix, subnets)
if subnets.empty? ## no subnets exist in the given address space of the virtual network, so divide the network into smaller subnets (based on the network size) and allocate space for the new subnet to be added ##
divide_network(vnet_address_prefix)
else ## subnets exist in vnet, calculate new address_prefix for the new subnet based on the space taken by these existing subnets under the given address space of the virtual network ##
vnet_network_address = IPAddress(vnet_address_prefix)
subnets = sort_subnets_by_cidr_prefix(subnets)
available_networks_pool = Array.new
used_networks_pool = Array.new
subnets.each do |subnet|
## in case the larger network is not divided into smaller subnets but
## divided into only 1 largest subnet of the complete network size ##
if vnet_network_address.prefix == subnet_cidr_prefix(subnet)
break
end
## add all the possible subnets (calculated using the current subnet's
## cidr prefix value) into the available_networks_pool ##
available_networks_pool.push(
vnet_network_address.subnet(subnet_cidr_prefix(subnet))
).flatten!.uniq! { |nwrk| [ nwrk.network.address, nwrk.prefix ].join(":") }
## add current subnet into the used_networks_pool ##
used_networks_pool.push(
IPAddress(subnet_address_prefix(subnet))
)
## sort both the network pools before trimming the available_networks_pool ##
available_networks_pool, used_networks_pool = sort_pools(
available_networks_pool, used_networks_pool)
## trim the available_networks_pool based on the networks already
## allocated to the existing subnets ##
used_networks_pool.each do |subnet_network|
available_networks_pool.delete_if do |available_network|
in_use_network?(subnet_network, available_network)
end
end
## sort both the network pools after trimming the available_networks_pool ##
available_networks_pool, used_networks_pool = sort_pools(
available_networks_pool, used_networks_pool)
end
## space available in the vnet_address_prefix network for the new subnet ##
if !available_networks_pool.empty? && available_networks_pool.first.network?
available_networks_pool.first.network.address.concat("/" + available_networks_pool.first.prefix.to_s)
else ## space not available in the vnet_address_prefix network for the new subnet ##
nil
end
end
end | ruby | def new_subnet_address_prefix(vnet_address_prefix, subnets)
if subnets.empty? ## no subnets exist in the given address space of the virtual network, so divide the network into smaller subnets (based on the network size) and allocate space for the new subnet to be added ##
divide_network(vnet_address_prefix)
else ## subnets exist in vnet, calculate new address_prefix for the new subnet based on the space taken by these existing subnets under the given address space of the virtual network ##
vnet_network_address = IPAddress(vnet_address_prefix)
subnets = sort_subnets_by_cidr_prefix(subnets)
available_networks_pool = Array.new
used_networks_pool = Array.new
subnets.each do |subnet|
## in case the larger network is not divided into smaller subnets but
## divided into only 1 largest subnet of the complete network size ##
if vnet_network_address.prefix == subnet_cidr_prefix(subnet)
break
end
## add all the possible subnets (calculated using the current subnet's
## cidr prefix value) into the available_networks_pool ##
available_networks_pool.push(
vnet_network_address.subnet(subnet_cidr_prefix(subnet))
).flatten!.uniq! { |nwrk| [ nwrk.network.address, nwrk.prefix ].join(":") }
## add current subnet into the used_networks_pool ##
used_networks_pool.push(
IPAddress(subnet_address_prefix(subnet))
)
## sort both the network pools before trimming the available_networks_pool ##
available_networks_pool, used_networks_pool = sort_pools(
available_networks_pool, used_networks_pool)
## trim the available_networks_pool based on the networks already
## allocated to the existing subnets ##
used_networks_pool.each do |subnet_network|
available_networks_pool.delete_if do |available_network|
in_use_network?(subnet_network, available_network)
end
end
## sort both the network pools after trimming the available_networks_pool ##
available_networks_pool, used_networks_pool = sort_pools(
available_networks_pool, used_networks_pool)
end
## space available in the vnet_address_prefix network for the new subnet ##
if !available_networks_pool.empty? && available_networks_pool.first.network?
available_networks_pool.first.network.address.concat("/" + available_networks_pool.first.prefix.to_s)
else ## space not available in the vnet_address_prefix network for the new subnet ##
nil
end
end
end | [
"def",
"new_subnet_address_prefix",
"(",
"vnet_address_prefix",
",",
"subnets",
")",
"if",
"subnets",
".",
"empty?",
"## no subnets exist in the given address space of the virtual network, so divide the network into smaller subnets (based on the network size) and allocate space for the new subnet to be added ##",
"divide_network",
"(",
"vnet_address_prefix",
")",
"else",
"## subnets exist in vnet, calculate new address_prefix for the new subnet based on the space taken by these existing subnets under the given address space of the virtual network ##",
"vnet_network_address",
"=",
"IPAddress",
"(",
"vnet_address_prefix",
")",
"subnets",
"=",
"sort_subnets_by_cidr_prefix",
"(",
"subnets",
")",
"available_networks_pool",
"=",
"Array",
".",
"new",
"used_networks_pool",
"=",
"Array",
".",
"new",
"subnets",
".",
"each",
"do",
"|",
"subnet",
"|",
"## in case the larger network is not divided into smaller subnets but",
"## divided into only 1 largest subnet of the complete network size ##",
"if",
"vnet_network_address",
".",
"prefix",
"==",
"subnet_cidr_prefix",
"(",
"subnet",
")",
"break",
"end",
"## add all the possible subnets (calculated using the current subnet's",
"## cidr prefix value) into the available_networks_pool ##",
"available_networks_pool",
".",
"push",
"(",
"vnet_network_address",
".",
"subnet",
"(",
"subnet_cidr_prefix",
"(",
"subnet",
")",
")",
")",
".",
"flatten!",
".",
"uniq!",
"{",
"|",
"nwrk",
"|",
"[",
"nwrk",
".",
"network",
".",
"address",
",",
"nwrk",
".",
"prefix",
"]",
".",
"join",
"(",
"\":\"",
")",
"}",
"## add current subnet into the used_networks_pool ##",
"used_networks_pool",
".",
"push",
"(",
"IPAddress",
"(",
"subnet_address_prefix",
"(",
"subnet",
")",
")",
")",
"## sort both the network pools before trimming the available_networks_pool ##",
"available_networks_pool",
",",
"used_networks_pool",
"=",
"sort_pools",
"(",
"available_networks_pool",
",",
"used_networks_pool",
")",
"## trim the available_networks_pool based on the networks already",
"## allocated to the existing subnets ##",
"used_networks_pool",
".",
"each",
"do",
"|",
"subnet_network",
"|",
"available_networks_pool",
".",
"delete_if",
"do",
"|",
"available_network",
"|",
"in_use_network?",
"(",
"subnet_network",
",",
"available_network",
")",
"end",
"end",
"## sort both the network pools after trimming the available_networks_pool ##",
"available_networks_pool",
",",
"used_networks_pool",
"=",
"sort_pools",
"(",
"available_networks_pool",
",",
"used_networks_pool",
")",
"end",
"## space available in the vnet_address_prefix network for the new subnet ##",
"if",
"!",
"available_networks_pool",
".",
"empty?",
"&&",
"available_networks_pool",
".",
"first",
".",
"network?",
"available_networks_pool",
".",
"first",
".",
"network",
".",
"address",
".",
"concat",
"(",
"\"/\"",
"+",
"available_networks_pool",
".",
"first",
".",
"prefix",
".",
"to_s",
")",
"else",
"## space not available in the vnet_address_prefix network for the new subnet ##",
"nil",
"end",
"end",
"end"
] | calculate and return address_prefix for the new subnet to be added in the
existing virtual network | [
"calculate",
"and",
"return",
"address_prefix",
"for",
"the",
"new",
"subnet",
"to",
"be",
"added",
"in",
"the",
"existing",
"virtual",
"network"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L135-L185 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.add_subnet | def add_subnet(subnet_name, vnet_config, subnets)
new_subnet_prefix = nil
vnet_address_prefix_count = 0
vnet_address_space = vnet_config[:addressPrefixes]
## search for space in all the address prefixes of the virtual network ##
while new_subnet_prefix.nil? && vnet_address_space.length > vnet_address_prefix_count
new_subnet_prefix = new_subnet_address_prefix(
vnet_address_space[vnet_address_prefix_count],
subnets_list_for_specific_address_space(
vnet_address_space[vnet_address_prefix_count], subnets
)
)
vnet_address_prefix_count += 1
end
if new_subnet_prefix ## found space for new subnet ##
vnet_config[:subnets].push(
subnet(subnet_name, new_subnet_prefix)
)
else ## no space available in the virtual network for the new subnet ##
raise "Unable to add subnet #{subnet_name} into the virtual network #{vnet_config[:virtualNetworkName]}, no address space available !!!"
end
vnet_config
end | ruby | def add_subnet(subnet_name, vnet_config, subnets)
new_subnet_prefix = nil
vnet_address_prefix_count = 0
vnet_address_space = vnet_config[:addressPrefixes]
## search for space in all the address prefixes of the virtual network ##
while new_subnet_prefix.nil? && vnet_address_space.length > vnet_address_prefix_count
new_subnet_prefix = new_subnet_address_prefix(
vnet_address_space[vnet_address_prefix_count],
subnets_list_for_specific_address_space(
vnet_address_space[vnet_address_prefix_count], subnets
)
)
vnet_address_prefix_count += 1
end
if new_subnet_prefix ## found space for new subnet ##
vnet_config[:subnets].push(
subnet(subnet_name, new_subnet_prefix)
)
else ## no space available in the virtual network for the new subnet ##
raise "Unable to add subnet #{subnet_name} into the virtual network #{vnet_config[:virtualNetworkName]}, no address space available !!!"
end
vnet_config
end | [
"def",
"add_subnet",
"(",
"subnet_name",
",",
"vnet_config",
",",
"subnets",
")",
"new_subnet_prefix",
"=",
"nil",
"vnet_address_prefix_count",
"=",
"0",
"vnet_address_space",
"=",
"vnet_config",
"[",
":addressPrefixes",
"]",
"## search for space in all the address prefixes of the virtual network ##",
"while",
"new_subnet_prefix",
".",
"nil?",
"&&",
"vnet_address_space",
".",
"length",
">",
"vnet_address_prefix_count",
"new_subnet_prefix",
"=",
"new_subnet_address_prefix",
"(",
"vnet_address_space",
"[",
"vnet_address_prefix_count",
"]",
",",
"subnets_list_for_specific_address_space",
"(",
"vnet_address_space",
"[",
"vnet_address_prefix_count",
"]",
",",
"subnets",
")",
")",
"vnet_address_prefix_count",
"+=",
"1",
"end",
"if",
"new_subnet_prefix",
"## found space for new subnet ##",
"vnet_config",
"[",
":subnets",
"]",
".",
"push",
"(",
"subnet",
"(",
"subnet_name",
",",
"new_subnet_prefix",
")",
")",
"else",
"## no space available in the virtual network for the new subnet ##",
"raise",
"\"Unable to add subnet #{subnet_name} into the virtual network #{vnet_config[:virtualNetworkName]}, no address space available !!!\"",
"end",
"vnet_config",
"end"
] | add new subnet into the existing virtual network | [
"add",
"new",
"subnet",
"into",
"the",
"existing",
"virtual",
"network"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L188-L213 | train |
chef/knife-azure | lib/azure/resource_management/vnet_config.rb | Azure::ARM.VnetConfig.create_vnet_config | def create_vnet_config(resource_group_name, vnet_name, vnet_subnet_name)
raise ArgumentError, "GatewaySubnet cannot be used as the name for --azure-vnet-subnet-name option. GatewaySubnet can only be used for virtual network gateways." if vnet_subnet_name == "GatewaySubnet"
vnet_config = {}
subnets = nil
flag = true
## check whether user passed or default named virtual network exist or not ##
vnet = get_vnet(resource_group_name, vnet_name)
vnet_config[:virtualNetworkName] = vnet_name
if vnet ## handle resources in the existing virtual network ##
vnet_config[:addressPrefixes] = vnet_address_spaces(vnet)
vnet_config[:subnets] = Array.new
subnets = subnets_list(resource_group_name, vnet_name)
if subnets
subnets.each do |subnet|
flag = false if subnet.name == vnet_subnet_name ## given subnet already exist in the virtual network ##
## preserve the existing subnet resources ##
vnet_config[:subnets].push(
subnet(subnet.name, subnet_address_prefix(subnet))
)
end
end
else ## create config for new vnet ##
vnet_config[:addressPrefixes] = [ "10.0.0.0/16" ]
vnet_config[:subnets] = Array.new
vnet_config[:subnets].push(
subnet(vnet_subnet_name, "10.0.0.0/24")
)
flag = false
end
## given subnet does not exist, so create new one in the virtual network ##
vnet_config = add_subnet(vnet_subnet_name, vnet_config, subnets) if flag
vnet_config
end | ruby | def create_vnet_config(resource_group_name, vnet_name, vnet_subnet_name)
raise ArgumentError, "GatewaySubnet cannot be used as the name for --azure-vnet-subnet-name option. GatewaySubnet can only be used for virtual network gateways." if vnet_subnet_name == "GatewaySubnet"
vnet_config = {}
subnets = nil
flag = true
## check whether user passed or default named virtual network exist or not ##
vnet = get_vnet(resource_group_name, vnet_name)
vnet_config[:virtualNetworkName] = vnet_name
if vnet ## handle resources in the existing virtual network ##
vnet_config[:addressPrefixes] = vnet_address_spaces(vnet)
vnet_config[:subnets] = Array.new
subnets = subnets_list(resource_group_name, vnet_name)
if subnets
subnets.each do |subnet|
flag = false if subnet.name == vnet_subnet_name ## given subnet already exist in the virtual network ##
## preserve the existing subnet resources ##
vnet_config[:subnets].push(
subnet(subnet.name, subnet_address_prefix(subnet))
)
end
end
else ## create config for new vnet ##
vnet_config[:addressPrefixes] = [ "10.0.0.0/16" ]
vnet_config[:subnets] = Array.new
vnet_config[:subnets].push(
subnet(vnet_subnet_name, "10.0.0.0/24")
)
flag = false
end
## given subnet does not exist, so create new one in the virtual network ##
vnet_config = add_subnet(vnet_subnet_name, vnet_config, subnets) if flag
vnet_config
end | [
"def",
"create_vnet_config",
"(",
"resource_group_name",
",",
"vnet_name",
",",
"vnet_subnet_name",
")",
"raise",
"ArgumentError",
",",
"\"GatewaySubnet cannot be used as the name for --azure-vnet-subnet-name option. GatewaySubnet can only be used for virtual network gateways.\"",
"if",
"vnet_subnet_name",
"==",
"\"GatewaySubnet\"",
"vnet_config",
"=",
"{",
"}",
"subnets",
"=",
"nil",
"flag",
"=",
"true",
"## check whether user passed or default named virtual network exist or not ##",
"vnet",
"=",
"get_vnet",
"(",
"resource_group_name",
",",
"vnet_name",
")",
"vnet_config",
"[",
":virtualNetworkName",
"]",
"=",
"vnet_name",
"if",
"vnet",
"## handle resources in the existing virtual network ##",
"vnet_config",
"[",
":addressPrefixes",
"]",
"=",
"vnet_address_spaces",
"(",
"vnet",
")",
"vnet_config",
"[",
":subnets",
"]",
"=",
"Array",
".",
"new",
"subnets",
"=",
"subnets_list",
"(",
"resource_group_name",
",",
"vnet_name",
")",
"if",
"subnets",
"subnets",
".",
"each",
"do",
"|",
"subnet",
"|",
"flag",
"=",
"false",
"if",
"subnet",
".",
"name",
"==",
"vnet_subnet_name",
"## given subnet already exist in the virtual network ##",
"## preserve the existing subnet resources ##",
"vnet_config",
"[",
":subnets",
"]",
".",
"push",
"(",
"subnet",
"(",
"subnet",
".",
"name",
",",
"subnet_address_prefix",
"(",
"subnet",
")",
")",
")",
"end",
"end",
"else",
"## create config for new vnet ##",
"vnet_config",
"[",
":addressPrefixes",
"]",
"=",
"[",
"\"10.0.0.0/16\"",
"]",
"vnet_config",
"[",
":subnets",
"]",
"=",
"Array",
".",
"new",
"vnet_config",
"[",
":subnets",
"]",
".",
"push",
"(",
"subnet",
"(",
"vnet_subnet_name",
",",
"\"10.0.0.0/24\"",
")",
")",
"flag",
"=",
"false",
"end",
"## given subnet does not exist, so create new one in the virtual network ##",
"vnet_config",
"=",
"add_subnet",
"(",
"vnet_subnet_name",
",",
"vnet_config",
",",
"subnets",
")",
"if",
"flag",
"vnet_config",
"end"
] | virtual network configuration creation for the new vnet creation or to
handle existing vnet | [
"virtual",
"network",
"configuration",
"creation",
"for",
"the",
"new",
"vnet",
"creation",
"or",
"to",
"handle",
"existing",
"vnet"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/resource_management/vnet_config.rb#L217-L252 | train |
chef/knife-azure | lib/azure/service_management/host.rb | Azure.Hosts.fetch_from_cloud | def fetch_from_cloud(name)
ret_val = @connection.query_azure("hostedservices/#{name}")
error_code, error_message = error_from_response_xml(ret_val) if ret_val
if ret_val.nil? || error_code.length > 0
Chef::Log.warn("Unable to find hosted(cloud) service:" + error_code + " : " + error_message) if ret_val
nil
else
Host.new(@connection).parse(ret_val)
end
end | ruby | def fetch_from_cloud(name)
ret_val = @connection.query_azure("hostedservices/#{name}")
error_code, error_message = error_from_response_xml(ret_val) if ret_val
if ret_val.nil? || error_code.length > 0
Chef::Log.warn("Unable to find hosted(cloud) service:" + error_code + " : " + error_message) if ret_val
nil
else
Host.new(@connection).parse(ret_val)
end
end | [
"def",
"fetch_from_cloud",
"(",
"name",
")",
"ret_val",
"=",
"@connection",
".",
"query_azure",
"(",
"\"hostedservices/#{name}\"",
")",
"error_code",
",",
"error_message",
"=",
"error_from_response_xml",
"(",
"ret_val",
")",
"if",
"ret_val",
"if",
"ret_val",
".",
"nil?",
"||",
"error_code",
".",
"length",
">",
"0",
"Chef",
"::",
"Log",
".",
"warn",
"(",
"\"Unable to find hosted(cloud) service:\"",
"+",
"error_code",
"+",
"\" : \"",
"+",
"error_message",
")",
"if",
"ret_val",
"nil",
"else",
"Host",
".",
"new",
"(",
"@connection",
")",
".",
"parse",
"(",
"ret_val",
")",
"end",
"end"
] | Look up hosted service on cloud and not local cache | [
"Look",
"up",
"hosted",
"service",
"on",
"cloud",
"and",
"not",
"local",
"cache"
] | 2cf998b286cd169478ba547057e6c5ca57217604 | https://github.com/chef/knife-azure/blob/2cf998b286cd169478ba547057e6c5ca57217604/lib/azure/service_management/host.rb#L73-L82 | train |
weppos/publicsuffix-ruby | lib/public_suffix/list.rb | PublicSuffix.List.each | def each(&block)
Enumerator.new do |y|
@rules.each do |key, node|
y << entry_to_rule(node, key)
end
end.each(&block)
end | ruby | def each(&block)
Enumerator.new do |y|
@rules.each do |key, node|
y << entry_to_rule(node, key)
end
end.each(&block)
end | [
"def",
"each",
"(",
"&",
"block",
")",
"Enumerator",
".",
"new",
"do",
"|",
"y",
"|",
"@rules",
".",
"each",
"do",
"|",
"key",
",",
"node",
"|",
"y",
"<<",
"entry_to_rule",
"(",
"node",
",",
"key",
")",
"end",
"end",
".",
"each",
"(",
"block",
")",
"end"
] | Iterates each rule in the list. | [
"Iterates",
"each",
"rule",
"in",
"the",
"list",
"."
] | 2803479f5a1eceec0f1416ea538aa0ca301b64e9 | https://github.com/weppos/publicsuffix-ruby/blob/2803479f5a1eceec0f1416ea538aa0ca301b64e9/lib/public_suffix/list.rb#L126-L132 | train |
weppos/publicsuffix-ruby | lib/public_suffix/list.rb | PublicSuffix.List.find | def find(name, default: default_rule, **options)
rule = select(name, **options).inject do |l, r|
return r if r.class == Rule::Exception
l.length > r.length ? l : r
end
rule || default
end | ruby | def find(name, default: default_rule, **options)
rule = select(name, **options).inject do |l, r|
return r if r.class == Rule::Exception
l.length > r.length ? l : r
end
rule || default
end | [
"def",
"find",
"(",
"name",
",",
"default",
":",
"default_rule",
",",
"**",
"options",
")",
"rule",
"=",
"select",
"(",
"name",
",",
"**",
"options",
")",
".",
"inject",
"do",
"|",
"l",
",",
"r",
"|",
"return",
"r",
"if",
"r",
".",
"class",
"==",
"Rule",
"::",
"Exception",
"l",
".",
"length",
">",
"r",
".",
"length",
"?",
"l",
":",
"r",
"end",
"rule",
"||",
"default",
"end"
] | Finds and returns the rule corresponding to the longest public suffix for the hostname.
@param name [#to_s] the hostname
@param default [PublicSuffix::Rule::*] the default rule to return in case no rule matches
@return [PublicSuffix::Rule::*] | [
"Finds",
"and",
"returns",
"the",
"rule",
"corresponding",
"to",
"the",
"longest",
"public",
"suffix",
"for",
"the",
"hostname",
"."
] | 2803479f5a1eceec0f1416ea538aa0ca301b64e9 | https://github.com/weppos/publicsuffix-ruby/blob/2803479f5a1eceec0f1416ea538aa0ca301b64e9/lib/public_suffix/list.rb#L172-L179 | train |
weppos/publicsuffix-ruby | lib/public_suffix/list.rb | PublicSuffix.List.select | def select(name, ignore_private: false)
name = name.to_s
parts = name.split(DOT).reverse!
index = 0
query = parts[index]
rules = []
loop do
match = @rules[query]
rules << entry_to_rule(match, query) if !match.nil? && (ignore_private == false || match.private == false)
index += 1
break if index >= parts.size
query = parts[index] + DOT + query
end
rules
end | ruby | def select(name, ignore_private: false)
name = name.to_s
parts = name.split(DOT).reverse!
index = 0
query = parts[index]
rules = []
loop do
match = @rules[query]
rules << entry_to_rule(match, query) if !match.nil? && (ignore_private == false || match.private == false)
index += 1
break if index >= parts.size
query = parts[index] + DOT + query
end
rules
end | [
"def",
"select",
"(",
"name",
",",
"ignore_private",
":",
"false",
")",
"name",
"=",
"name",
".",
"to_s",
"parts",
"=",
"name",
".",
"split",
"(",
"DOT",
")",
".",
"reverse!",
"index",
"=",
"0",
"query",
"=",
"parts",
"[",
"index",
"]",
"rules",
"=",
"[",
"]",
"loop",
"do",
"match",
"=",
"@rules",
"[",
"query",
"]",
"rules",
"<<",
"entry_to_rule",
"(",
"match",
",",
"query",
")",
"if",
"!",
"match",
".",
"nil?",
"&&",
"(",
"ignore_private",
"==",
"false",
"||",
"match",
".",
"private",
"==",
"false",
")",
"index",
"+=",
"1",
"break",
"if",
"index",
">=",
"parts",
".",
"size",
"query",
"=",
"parts",
"[",
"index",
"]",
"+",
"DOT",
"+",
"query",
"end",
"rules",
"end"
] | Selects all the rules matching given hostame.
If `ignore_private` is set to true, the algorithm will skip the rules that are flagged as
private domain. Note that the rules will still be part of the loop.
If you frequently need to access lists ignoring the private domains,
you should create a list that doesn't include these domains setting the
`private_domains: false` option when calling {.parse}.
Note that this method is currently private, as you should not rely on it. Instead,
the public interface is {#find}. The current internal algorithm allows to return all
matching rules, but different data structures may not be able to do it, and instead would
return only the match. For this reason, you should rely on {#find}.
@param name [#to_s] the hostname
@param ignore_private [Boolean]
@return [Array<PublicSuffix::Rule::*>] | [
"Selects",
"all",
"the",
"rules",
"matching",
"given",
"hostame",
"."
] | 2803479f5a1eceec0f1416ea538aa0ca301b64e9 | https://github.com/weppos/publicsuffix-ruby/blob/2803479f5a1eceec0f1416ea538aa0ca301b64e9/lib/public_suffix/list.rb#L197-L216 | train |
jamesrwhite/minicron | server/lib/minicron/monitor.rb | Minicron.Monitor.start! | def start!
# Activate the monitor
@active = true
# Connect to the database
Minicron.establish_db_connection(
Minicron.config['server']['database'],
Minicron.config['verbose']
)
# Set the start time of the monitir
@start_time = Time.now.utc
# Start a thread for the monitor
@thread = Thread.new do
# While the monitor is active run it in a loop ~every minute
while @active
# Get all the schedules
schedules = Minicron::Hub::Model::Schedule.all
# Loop every schedule we know about
schedules.each do |schedule|
begin
# TODO: is it possible to monitor on boot schedules some other way?
monitor(schedule) unless schedule.special == '@reboot'
rescue Exception => e
if Minicron.config['debug']
puts e.message
puts e.backtrace
end
end
end
sleep 59
end
end
end | ruby | def start!
# Activate the monitor
@active = true
# Connect to the database
Minicron.establish_db_connection(
Minicron.config['server']['database'],
Minicron.config['verbose']
)
# Set the start time of the monitir
@start_time = Time.now.utc
# Start a thread for the monitor
@thread = Thread.new do
# While the monitor is active run it in a loop ~every minute
while @active
# Get all the schedules
schedules = Minicron::Hub::Model::Schedule.all
# Loop every schedule we know about
schedules.each do |schedule|
begin
# TODO: is it possible to monitor on boot schedules some other way?
monitor(schedule) unless schedule.special == '@reboot'
rescue Exception => e
if Minicron.config['debug']
puts e.message
puts e.backtrace
end
end
end
sleep 59
end
end
end | [
"def",
"start!",
"# Activate the monitor",
"@active",
"=",
"true",
"# Connect to the database",
"Minicron",
".",
"establish_db_connection",
"(",
"Minicron",
".",
"config",
"[",
"'server'",
"]",
"[",
"'database'",
"]",
",",
"Minicron",
".",
"config",
"[",
"'verbose'",
"]",
")",
"# Set the start time of the monitir",
"@start_time",
"=",
"Time",
".",
"now",
".",
"utc",
"# Start a thread for the monitor",
"@thread",
"=",
"Thread",
".",
"new",
"do",
"# While the monitor is active run it in a loop ~every minute",
"while",
"@active",
"# Get all the schedules",
"schedules",
"=",
"Minicron",
"::",
"Hub",
"::",
"Model",
"::",
"Schedule",
".",
"all",
"# Loop every schedule we know about",
"schedules",
".",
"each",
"do",
"|",
"schedule",
"|",
"begin",
"# TODO: is it possible to monitor on boot schedules some other way?",
"monitor",
"(",
"schedule",
")",
"unless",
"schedule",
".",
"special",
"==",
"'@reboot'",
"rescue",
"Exception",
"=>",
"e",
"if",
"Minicron",
".",
"config",
"[",
"'debug'",
"]",
"puts",
"e",
".",
"message",
"puts",
"e",
".",
"backtrace",
"end",
"end",
"end",
"sleep",
"59",
"end",
"end",
"end"
] | Starts the execution monitor in a new thread | [
"Starts",
"the",
"execution",
"monitor",
"in",
"a",
"new",
"thread"
] | 6b0a1330522a8aaabeb390d3530cab2fde5028b3 | https://github.com/jamesrwhite/minicron/blob/6b0a1330522a8aaabeb390d3530cab2fde5028b3/server/lib/minicron/monitor.rb#L16-L52 | train |
jamesrwhite/minicron | server/lib/minicron/monitor.rb | Minicron.Monitor.monitor | def monitor(schedule)
# Parse the cron expression
cron = CronParser.new(schedule.formatted)
# Find the time the cron was last expected to run with a 30 second pre buffer
# and a 30 second post buffer (in addition to the 60 already in place) incase
# jobs run early/late to allow for clock sync differences between client/hub
expected_at = cron.last(Time.now.utc) - 30
expected_by = expected_at + 30 + 60 + 30 # pre buffer + minute wait + post buffer
# We only need to check jobs that are expected after the monitor start time
# and jobs that have passed their expected by time and the time the schedule
# was last updated isn't before when it was expected, i.e we aren't checking for something
# that should have happened earlier in the day.
if expected_at > @start_time && Time.now.utc > expected_by && expected_by > schedule.updated_at
# Check if this execution was created inside a minute window
# starting when it was expected to run
check = Minicron::Hub::Model::Execution.exists?(
created_at: expected_at..expected_by,
job_id: schedule.job_id
)
# If the check failed
unless check
Minicron::Alert.send_all(
user_id: schedule.user_id,
kind: 'miss',
schedule_id: schedule.id,
expected_at: expected_at,
job_id: schedule.job_id
)
end
end
end | ruby | def monitor(schedule)
# Parse the cron expression
cron = CronParser.new(schedule.formatted)
# Find the time the cron was last expected to run with a 30 second pre buffer
# and a 30 second post buffer (in addition to the 60 already in place) incase
# jobs run early/late to allow for clock sync differences between client/hub
expected_at = cron.last(Time.now.utc) - 30
expected_by = expected_at + 30 + 60 + 30 # pre buffer + minute wait + post buffer
# We only need to check jobs that are expected after the monitor start time
# and jobs that have passed their expected by time and the time the schedule
# was last updated isn't before when it was expected, i.e we aren't checking for something
# that should have happened earlier in the day.
if expected_at > @start_time && Time.now.utc > expected_by && expected_by > schedule.updated_at
# Check if this execution was created inside a minute window
# starting when it was expected to run
check = Minicron::Hub::Model::Execution.exists?(
created_at: expected_at..expected_by,
job_id: schedule.job_id
)
# If the check failed
unless check
Minicron::Alert.send_all(
user_id: schedule.user_id,
kind: 'miss',
schedule_id: schedule.id,
expected_at: expected_at,
job_id: schedule.job_id
)
end
end
end | [
"def",
"monitor",
"(",
"schedule",
")",
"# Parse the cron expression",
"cron",
"=",
"CronParser",
".",
"new",
"(",
"schedule",
".",
"formatted",
")",
"# Find the time the cron was last expected to run with a 30 second pre buffer",
"# and a 30 second post buffer (in addition to the 60 already in place) incase",
"# jobs run early/late to allow for clock sync differences between client/hub",
"expected_at",
"=",
"cron",
".",
"last",
"(",
"Time",
".",
"now",
".",
"utc",
")",
"-",
"30",
"expected_by",
"=",
"expected_at",
"+",
"30",
"+",
"60",
"+",
"30",
"# pre buffer + minute wait + post buffer",
"# We only need to check jobs that are expected after the monitor start time",
"# and jobs that have passed their expected by time and the time the schedule",
"# was last updated isn't before when it was expected, i.e we aren't checking for something",
"# that should have happened earlier in the day.",
"if",
"expected_at",
">",
"@start_time",
"&&",
"Time",
".",
"now",
".",
"utc",
">",
"expected_by",
"&&",
"expected_by",
">",
"schedule",
".",
"updated_at",
"# Check if this execution was created inside a minute window",
"# starting when it was expected to run",
"check",
"=",
"Minicron",
"::",
"Hub",
"::",
"Model",
"::",
"Execution",
".",
"exists?",
"(",
"created_at",
":",
"expected_at",
"..",
"expected_by",
",",
"job_id",
":",
"schedule",
".",
"job_id",
")",
"# If the check failed",
"unless",
"check",
"Minicron",
"::",
"Alert",
".",
"send_all",
"(",
"user_id",
":",
"schedule",
".",
"user_id",
",",
"kind",
":",
"'miss'",
",",
"schedule_id",
":",
"schedule",
".",
"id",
",",
"expected_at",
":",
"expected_at",
",",
"job_id",
":",
"schedule",
".",
"job_id",
")",
"end",
"end",
"end"
] | Handle the monitoring of a cron schedule
@param schedule [Minicron::Hub::Model::Schedule] | [
"Handle",
"the",
"monitoring",
"of",
"a",
"cron",
"schedule"
] | 6b0a1330522a8aaabeb390d3530cab2fde5028b3 | https://github.com/jamesrwhite/minicron/blob/6b0a1330522a8aaabeb390d3530cab2fde5028b3/server/lib/minicron/monitor.rb#L70-L103 | train |
jamesrwhite/minicron | server/lib/minicron/cron.rb | Minicron.Cron.build_crontab | def build_crontab(host)
# You have been warned..
crontab = "#\n"
crontab += "# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\n"
crontab += "#\n\n"
# Set the path to something sensible by default, eventually this should be configurable
crontab += "# ENV variables\n"
crontab += "PATH=#{PATH}\n"
crontab += "MAILTO=\"\"\n"
crontab += "\n"
# Add an entry to the crontab for each job schedule
unless host.nil?
host.jobs.each do |job|
crontab += "# ID: #{job.id}\n"
crontab += "# Name: #{job.name}\n"
crontab += "# Status: #{job.status}\n"
if !job.schedules.empty?
job.schedules.each do |schedule|
crontab += "\t"
crontab += '# ' unless job.enabled # comment out schedule if job isn't enabled
crontab += "#{build_minicron_command(schedule.formatted, job.command)}\n"
end
else
crontab += "\t# No schedules exist for this job\n"
end
crontab += "\n"
end
end
crontab
end | ruby | def build_crontab(host)
# You have been warned..
crontab = "#\n"
crontab += "# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\n"
crontab += "#\n\n"
# Set the path to something sensible by default, eventually this should be configurable
crontab += "# ENV variables\n"
crontab += "PATH=#{PATH}\n"
crontab += "MAILTO=\"\"\n"
crontab += "\n"
# Add an entry to the crontab for each job schedule
unless host.nil?
host.jobs.each do |job|
crontab += "# ID: #{job.id}\n"
crontab += "# Name: #{job.name}\n"
crontab += "# Status: #{job.status}\n"
if !job.schedules.empty?
job.schedules.each do |schedule|
crontab += "\t"
crontab += '# ' unless job.enabled # comment out schedule if job isn't enabled
crontab += "#{build_minicron_command(schedule.formatted, job.command)}\n"
end
else
crontab += "\t# No schedules exist for this job\n"
end
crontab += "\n"
end
end
crontab
end | [
"def",
"build_crontab",
"(",
"host",
")",
"# You have been warned..",
"crontab",
"=",
"\"#\\n\"",
"crontab",
"+=",
"\"# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\\n\"",
"crontab",
"+=",
"\"#\\n\\n\"",
"# Set the path to something sensible by default, eventually this should be configurable",
"crontab",
"+=",
"\"# ENV variables\\n\"",
"crontab",
"+=",
"\"PATH=#{PATH}\\n\"",
"crontab",
"+=",
"\"MAILTO=\\\"\\\"\\n\"",
"crontab",
"+=",
"\"\\n\"",
"# Add an entry to the crontab for each job schedule",
"unless",
"host",
".",
"nil?",
"host",
".",
"jobs",
".",
"each",
"do",
"|",
"job",
"|",
"crontab",
"+=",
"\"# ID: #{job.id}\\n\"",
"crontab",
"+=",
"\"# Name: #{job.name}\\n\"",
"crontab",
"+=",
"\"# Status: #{job.status}\\n\"",
"if",
"!",
"job",
".",
"schedules",
".",
"empty?",
"job",
".",
"schedules",
".",
"each",
"do",
"|",
"schedule",
"|",
"crontab",
"+=",
"\"\\t\"",
"crontab",
"+=",
"'# '",
"unless",
"job",
".",
"enabled",
"# comment out schedule if job isn't enabled",
"crontab",
"+=",
"\"#{build_minicron_command(schedule.formatted, job.command)}\\n\"",
"end",
"else",
"crontab",
"+=",
"\"\\t# No schedules exist for this job\\n\"",
"end",
"crontab",
"+=",
"\"\\n\"",
"end",
"end",
"crontab",
"end"
] | Build the crontab multiline string that includes all the given jobs
@param host [Minicron::Hub::Model::Host] a host instance with it's jobs and job schedules
@return [String] | [
"Build",
"the",
"crontab",
"multiline",
"string",
"that",
"includes",
"all",
"the",
"given",
"jobs"
] | 6b0a1330522a8aaabeb390d3530cab2fde5028b3 | https://github.com/jamesrwhite/minicron/blob/6b0a1330522a8aaabeb390d3530cab2fde5028b3/server/lib/minicron/cron.rb#L21-L55 | train |
jaimeiniesta/metainspector | lib/meta_inspector/url.rb | MetaInspector.URL.with_default_scheme | def with_default_scheme(url)
parsed(url) && parsed(url).scheme.nil? ? 'http://' + url : url
end | ruby | def with_default_scheme(url)
parsed(url) && parsed(url).scheme.nil? ? 'http://' + url : url
end | [
"def",
"with_default_scheme",
"(",
"url",
")",
"parsed",
"(",
"url",
")",
"&&",
"parsed",
"(",
"url",
")",
".",
"scheme",
".",
"nil?",
"?",
"'http://'",
"+",
"url",
":",
"url",
"end"
] | Adds 'http' as default scheme, if there is none | [
"Adds",
"http",
"as",
"default",
"scheme",
"if",
"there",
"is",
"none"
] | 540e2ee07ee697634d2a096dd1f010da79613313 | https://github.com/jaimeiniesta/metainspector/blob/540e2ee07ee697634d2a096dd1f010da79613313/lib/meta_inspector/url.rb#L78-L80 | train |
jaimeiniesta/metainspector | lib/meta_inspector/url.rb | MetaInspector.URL.normalized | def normalized(url)
Addressable::URI.parse(url).normalize.to_s
rescue Addressable::URI::InvalidURIError => e
raise MetaInspector::ParserError.new(e)
end | ruby | def normalized(url)
Addressable::URI.parse(url).normalize.to_s
rescue Addressable::URI::InvalidURIError => e
raise MetaInspector::ParserError.new(e)
end | [
"def",
"normalized",
"(",
"url",
")",
"Addressable",
"::",
"URI",
".",
"parse",
"(",
"url",
")",
".",
"normalize",
".",
"to_s",
"rescue",
"Addressable",
"::",
"URI",
"::",
"InvalidURIError",
"=>",
"e",
"raise",
"MetaInspector",
"::",
"ParserError",
".",
"new",
"(",
"e",
")",
"end"
] | Normalize url to deal with characters that should be encoded,
add trailing slash, convert to downcase... | [
"Normalize",
"url",
"to",
"deal",
"with",
"characters",
"that",
"should",
"be",
"encoded",
"add",
"trailing",
"slash",
"convert",
"to",
"downcase",
"..."
] | 540e2ee07ee697634d2a096dd1f010da79613313 | https://github.com/jaimeiniesta/metainspector/blob/540e2ee07ee697634d2a096dd1f010da79613313/lib/meta_inspector/url.rb#L84-L88 | train |
jaimeiniesta/metainspector | lib/meta_inspector/document.rb | MetaInspector.Document.to_hash | def to_hash
{
'url' => url,
'scheme' => scheme,
'host' => host,
'root_url' => root_url,
'title' => title,
'best_title' => best_title,
'author' => author,
'best_author' => best_author,
'description' => description,
'best_description' => best_description,
'links' => links.to_hash,
'images' => images.to_a,
'charset' => charset,
'feed' => feed,
'content_type' => content_type,
'meta_tags' => meta_tags,
'favicon' => images.favicon,
'response' => { 'status' => response.status,
'headers' => response.headers }
}
end | ruby | def to_hash
{
'url' => url,
'scheme' => scheme,
'host' => host,
'root_url' => root_url,
'title' => title,
'best_title' => best_title,
'author' => author,
'best_author' => best_author,
'description' => description,
'best_description' => best_description,
'links' => links.to_hash,
'images' => images.to_a,
'charset' => charset,
'feed' => feed,
'content_type' => content_type,
'meta_tags' => meta_tags,
'favicon' => images.favicon,
'response' => { 'status' => response.status,
'headers' => response.headers }
}
end | [
"def",
"to_hash",
"{",
"'url'",
"=>",
"url",
",",
"'scheme'",
"=>",
"scheme",
",",
"'host'",
"=>",
"host",
",",
"'root_url'",
"=>",
"root_url",
",",
"'title'",
"=>",
"title",
",",
"'best_title'",
"=>",
"best_title",
",",
"'author'",
"=>",
"author",
",",
"'best_author'",
"=>",
"best_author",
",",
"'description'",
"=>",
"description",
",",
"'best_description'",
"=>",
"best_description",
",",
"'links'",
"=>",
"links",
".",
"to_hash",
",",
"'images'",
"=>",
"images",
".",
"to_a",
",",
"'charset'",
"=>",
"charset",
",",
"'feed'",
"=>",
"feed",
",",
"'content_type'",
"=>",
"content_type",
",",
"'meta_tags'",
"=>",
"meta_tags",
",",
"'favicon'",
"=>",
"images",
".",
"favicon",
",",
"'response'",
"=>",
"{",
"'status'",
"=>",
"response",
".",
"status",
",",
"'headers'",
"=>",
"response",
".",
"headers",
"}",
"}",
"end"
] | Returns all document data as a nested Hash | [
"Returns",
"all",
"document",
"data",
"as",
"a",
"nested",
"Hash"
] | 540e2ee07ee697634d2a096dd1f010da79613313 | https://github.com/jaimeiniesta/metainspector/blob/540e2ee07ee697634d2a096dd1f010da79613313/lib/meta_inspector/document.rb#L57-L79 | train |
davetron5000/gli | lib/gli/command.rb | GLI.Command.has_option? | def has_option?(option) #:nodoc:
option = option.gsub(/^\-+/,'')
((flags.values.map { |_| [_.name,_.aliases] }) +
(switches.values.map { |_| [_.name,_.aliases] })).flatten.map(&:to_s).include?(option)
end | ruby | def has_option?(option) #:nodoc:
option = option.gsub(/^\-+/,'')
((flags.values.map { |_| [_.name,_.aliases] }) +
(switches.values.map { |_| [_.name,_.aliases] })).flatten.map(&:to_s).include?(option)
end | [
"def",
"has_option?",
"(",
"option",
")",
"#:nodoc:",
"option",
"=",
"option",
".",
"gsub",
"(",
"/",
"\\-",
"/",
",",
"''",
")",
"(",
"(",
"flags",
".",
"values",
".",
"map",
"{",
"|",
"_",
"|",
"[",
"_",
".",
"name",
",",
"_",
".",
"aliases",
"]",
"}",
")",
"+",
"(",
"switches",
".",
"values",
".",
"map",
"{",
"|",
"_",
"|",
"[",
"_",
".",
"name",
",",
"_",
".",
"aliases",
"]",
"}",
")",
")",
".",
"flatten",
".",
"map",
"(",
":to_s",
")",
".",
"include?",
"(",
"option",
")",
"end"
] | Returns true if this command has the given option defined | [
"Returns",
"true",
"if",
"this",
"command",
"has",
"the",
"given",
"option",
"defined"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/command.rb#L165-L169 | train |
davetron5000/gli | lib/gli/command.rb | GLI.Command.name_for_help | def name_for_help
name_array = [name.to_s]
command_parent = parent
while(command_parent.is_a?(GLI::Command)) do
name_array.unshift(command_parent.name.to_s)
command_parent = command_parent.parent
end
name_array
end | ruby | def name_for_help
name_array = [name.to_s]
command_parent = parent
while(command_parent.is_a?(GLI::Command)) do
name_array.unshift(command_parent.name.to_s)
command_parent = command_parent.parent
end
name_array
end | [
"def",
"name_for_help",
"name_array",
"=",
"[",
"name",
".",
"to_s",
"]",
"command_parent",
"=",
"parent",
"while",
"(",
"command_parent",
".",
"is_a?",
"(",
"GLI",
"::",
"Command",
")",
")",
"do",
"name_array",
".",
"unshift",
"(",
"command_parent",
".",
"name",
".",
"to_s",
")",
"command_parent",
"=",
"command_parent",
".",
"parent",
"end",
"name_array",
"end"
] | Returns full name for help command including parents
Example
command :remote do |t|
t.command :add do |global,options,args|
end
end
@add_command.name_for_help # => ["remote", "add"] | [
"Returns",
"full",
"name",
"for",
"help",
"command",
"including",
"parents"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/command.rb#L182-L190 | train |
davetron5000/gli | lib/gli/app.rb | GLI.App.commands_from | def commands_from(path)
if Pathname.new(path).absolute? and File.exist?(path)
load_commands(path)
else
$LOAD_PATH.each do |load_path|
commands_path = File.join(load_path,path)
load_commands(commands_path)
end
end
end | ruby | def commands_from(path)
if Pathname.new(path).absolute? and File.exist?(path)
load_commands(path)
else
$LOAD_PATH.each do |load_path|
commands_path = File.join(load_path,path)
load_commands(commands_path)
end
end
end | [
"def",
"commands_from",
"(",
"path",
")",
"if",
"Pathname",
".",
"new",
"(",
"path",
")",
".",
"absolute?",
"and",
"File",
".",
"exist?",
"(",
"path",
")",
"load_commands",
"(",
"path",
")",
"else",
"$LOAD_PATH",
".",
"each",
"do",
"|",
"load_path",
"|",
"commands_path",
"=",
"File",
".",
"join",
"(",
"load_path",
",",
"path",
")",
"load_commands",
"(",
"commands_path",
")",
"end",
"end",
"end"
] | Loads ruby files in the load path that start with
+path+, which are presumed to be commands for your executable.
This is useful for decomposing your bin file into different classes, but
can also be used as a plugin mechanism, allowing users to provide additional
commands for your app at runtime. All that being said, it's basically
a glorified +require+.
path:: a path from which to load <code>.rb</code> files that, presumably, contain commands. If this is an absolute path,
any files in that path are loaded. If not, it is interpretted as relative to somewhere
in the <code>LOAD_PATH</code>.
== Example:
# loads *.rb from your app's install - great for decomposing your bin file
commands_from "my_app/commands"
# loads *.rb files from the user's home dir - great and an extension/plugin mechanism
commands_from File.join(ENV["HOME"],".my_app","plugins") | [
"Loads",
"ruby",
"files",
"in",
"the",
"load",
"path",
"that",
"start",
"with",
"+",
"path",
"+",
"which",
"are",
"presumed",
"to",
"be",
"commands",
"for",
"your",
"executable",
".",
"This",
"is",
"useful",
"for",
"decomposing",
"your",
"bin",
"file",
"into",
"different",
"classes",
"but",
"can",
"also",
"be",
"used",
"as",
"a",
"plugin",
"mechanism",
"allowing",
"users",
"to",
"provide",
"additional",
"commands",
"for",
"your",
"app",
"at",
"runtime",
".",
"All",
"that",
"being",
"said",
"it",
"s",
"basically",
"a",
"glorified",
"+",
"require",
"+",
"."
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app.rb#L32-L41 | train |
davetron5000/gli | lib/gli/app.rb | GLI.App.config_file | def config_file(filename)
if filename =~ /^\//
@config_file = filename
else
@config_file = File.join(File.expand_path(ENV['HOME']),filename)
end
commands[:initconfig] = InitConfig.new(@config_file,commands,flags,switches)
@commands_declaration_order << commands[:initconfig]
@config_file
end | ruby | def config_file(filename)
if filename =~ /^\//
@config_file = filename
else
@config_file = File.join(File.expand_path(ENV['HOME']),filename)
end
commands[:initconfig] = InitConfig.new(@config_file,commands,flags,switches)
@commands_declaration_order << commands[:initconfig]
@config_file
end | [
"def",
"config_file",
"(",
"filename",
")",
"if",
"filename",
"=~",
"/",
"\\/",
"/",
"@config_file",
"=",
"filename",
"else",
"@config_file",
"=",
"File",
".",
"join",
"(",
"File",
".",
"expand_path",
"(",
"ENV",
"[",
"'HOME'",
"]",
")",
",",
"filename",
")",
"end",
"commands",
"[",
":initconfig",
"]",
"=",
"InitConfig",
".",
"new",
"(",
"@config_file",
",",
"commands",
",",
"flags",
",",
"switches",
")",
"@commands_declaration_order",
"<<",
"commands",
"[",
":initconfig",
"]",
"@config_file",
"end"
] | Sets that this app uses a config file as well as the name of the config file.
+filename+:: A String representing the path to the file to use for the config file. If it's an absolute
path, this is treated as the path to the file. If it's *not*, it's treated as relative to the user's home
directory as produced by <code>File.expand_path('~')</code>. | [
"Sets",
"that",
"this",
"app",
"uses",
"a",
"config",
"file",
"as",
"well",
"as",
"the",
"name",
"of",
"the",
"config",
"file",
"."
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app.rb#L102-L111 | train |
davetron5000/gli | lib/gli/app_support.rb | GLI.AppSupport.reset | def reset # :nodoc:
switches.clear
flags.clear
@commands = nil
@commands_declaration_order = []
@flags_declaration_order = []
@switches_declaration_order = []
@version = nil
@config_file = nil
@use_openstruct = false
@prog_desc = nil
@error_block = false
@pre_block = false
@post_block = false
@default_command = :help
@autocomplete = false
@around_block = nil
@subcommand_option_handling_strategy = :legacy
@argument_handling_strategy = :loose
clear_nexts
end | ruby | def reset # :nodoc:
switches.clear
flags.clear
@commands = nil
@commands_declaration_order = []
@flags_declaration_order = []
@switches_declaration_order = []
@version = nil
@config_file = nil
@use_openstruct = false
@prog_desc = nil
@error_block = false
@pre_block = false
@post_block = false
@default_command = :help
@autocomplete = false
@around_block = nil
@subcommand_option_handling_strategy = :legacy
@argument_handling_strategy = :loose
clear_nexts
end | [
"def",
"reset",
"# :nodoc:",
"switches",
".",
"clear",
"flags",
".",
"clear",
"@commands",
"=",
"nil",
"@commands_declaration_order",
"=",
"[",
"]",
"@flags_declaration_order",
"=",
"[",
"]",
"@switches_declaration_order",
"=",
"[",
"]",
"@version",
"=",
"nil",
"@config_file",
"=",
"nil",
"@use_openstruct",
"=",
"false",
"@prog_desc",
"=",
"nil",
"@error_block",
"=",
"false",
"@pre_block",
"=",
"false",
"@post_block",
"=",
"false",
"@default_command",
"=",
":help",
"@autocomplete",
"=",
"false",
"@around_block",
"=",
"nil",
"@subcommand_option_handling_strategy",
"=",
":legacy",
"@argument_handling_strategy",
"=",
":loose",
"clear_nexts",
"end"
] | Reset the GLI module internal data structures; mostly useful for testing | [
"Reset",
"the",
"GLI",
"module",
"internal",
"data",
"structures",
";",
"mostly",
"useful",
"for",
"testing"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app_support.rb#L14-L34 | train |
davetron5000/gli | lib/gli/app_support.rb | GLI.AppSupport.run | def run(args) #:nodoc:
args = args.dup if @preserve_argv
the_command = nil
begin
override_defaults_based_on_config(parse_config)
add_help_switch_if_needed(self)
gli_option_parser = GLIOptionParser.new(commands,
flags,
switches,
accepts,
:default_command => @default_command,
:autocomplete => autocomplete,
:subcommand_option_handling_strategy => subcommand_option_handling_strategy,
:argument_handling_strategy => argument_handling_strategy)
parsing_result = gli_option_parser.parse_options(args)
parsing_result.convert_to_openstruct! if @use_openstruct
the_command = parsing_result.command
if proceed?(parsing_result)
call_command(parsing_result)
0
else
raise PreconditionFailed, "preconditions failed"
end
rescue Exception => ex
if the_command.nil? && ex.respond_to?(:command_in_context)
the_command = ex.command_in_context
end
handle_exception(ex,the_command)
end
end | ruby | def run(args) #:nodoc:
args = args.dup if @preserve_argv
the_command = nil
begin
override_defaults_based_on_config(parse_config)
add_help_switch_if_needed(self)
gli_option_parser = GLIOptionParser.new(commands,
flags,
switches,
accepts,
:default_command => @default_command,
:autocomplete => autocomplete,
:subcommand_option_handling_strategy => subcommand_option_handling_strategy,
:argument_handling_strategy => argument_handling_strategy)
parsing_result = gli_option_parser.parse_options(args)
parsing_result.convert_to_openstruct! if @use_openstruct
the_command = parsing_result.command
if proceed?(parsing_result)
call_command(parsing_result)
0
else
raise PreconditionFailed, "preconditions failed"
end
rescue Exception => ex
if the_command.nil? && ex.respond_to?(:command_in_context)
the_command = ex.command_in_context
end
handle_exception(ex,the_command)
end
end | [
"def",
"run",
"(",
"args",
")",
"#:nodoc:",
"args",
"=",
"args",
".",
"dup",
"if",
"@preserve_argv",
"the_command",
"=",
"nil",
"begin",
"override_defaults_based_on_config",
"(",
"parse_config",
")",
"add_help_switch_if_needed",
"(",
"self",
")",
"gli_option_parser",
"=",
"GLIOptionParser",
".",
"new",
"(",
"commands",
",",
"flags",
",",
"switches",
",",
"accepts",
",",
":default_command",
"=>",
"@default_command",
",",
":autocomplete",
"=>",
"autocomplete",
",",
":subcommand_option_handling_strategy",
"=>",
"subcommand_option_handling_strategy",
",",
":argument_handling_strategy",
"=>",
"argument_handling_strategy",
")",
"parsing_result",
"=",
"gli_option_parser",
".",
"parse_options",
"(",
"args",
")",
"parsing_result",
".",
"convert_to_openstruct!",
"if",
"@use_openstruct",
"the_command",
"=",
"parsing_result",
".",
"command",
"if",
"proceed?",
"(",
"parsing_result",
")",
"call_command",
"(",
"parsing_result",
")",
"0",
"else",
"raise",
"PreconditionFailed",
",",
"\"preconditions failed\"",
"end",
"rescue",
"Exception",
"=>",
"ex",
"if",
"the_command",
".",
"nil?",
"&&",
"ex",
".",
"respond_to?",
"(",
":command_in_context",
")",
"the_command",
"=",
"ex",
".",
"command_in_context",
"end",
"handle_exception",
"(",
"ex",
",",
"the_command",
")",
"end",
"end"
] | Runs whatever command is needed based on the arguments.
+args+:: the command line ARGV array
Returns a number that would be a reasonable exit code | [
"Runs",
"whatever",
"command",
"is",
"needed",
"based",
"on",
"the",
"arguments",
"."
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app_support.rb#L60-L94 | train |
davetron5000/gli | lib/gli/app_support.rb | GLI.AppSupport.override_defaults_based_on_config | def override_defaults_based_on_config(config)
override_default(flags,config)
override_default(switches,config)
override_command_defaults(commands,config)
end | ruby | def override_defaults_based_on_config(config)
override_default(flags,config)
override_default(switches,config)
override_command_defaults(commands,config)
end | [
"def",
"override_defaults_based_on_config",
"(",
"config",
")",
"override_default",
"(",
"flags",
",",
"config",
")",
"override_default",
"(",
"switches",
",",
"config",
")",
"override_command_defaults",
"(",
"commands",
",",
"config",
")",
"end"
] | Sets the default values for flags based on the configuration | [
"Sets",
"the",
"default",
"values",
"for",
"flags",
"based",
"on",
"the",
"configuration"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app_support.rb#L178-L183 | train |
davetron5000/gli | lib/gli/app_support.rb | GLI.AppSupport.proceed? | def proceed?(parsing_result) #:nodoc:
if parsing_result.command && parsing_result.command.skips_pre
true
else
pre_block.call(*parsing_result)
end
end | ruby | def proceed?(parsing_result) #:nodoc:
if parsing_result.command && parsing_result.command.skips_pre
true
else
pre_block.call(*parsing_result)
end
end | [
"def",
"proceed?",
"(",
"parsing_result",
")",
"#:nodoc:",
"if",
"parsing_result",
".",
"command",
"&&",
"parsing_result",
".",
"command",
".",
"skips_pre",
"true",
"else",
"pre_block",
".",
"call",
"(",
"parsing_result",
")",
"end",
"end"
] | True if we should proceed with executing the command; this calls
the pre block if it's defined | [
"True",
"if",
"we",
"should",
"proceed",
"with",
"executing",
"the",
"command",
";",
"this",
"calls",
"the",
"pre",
"block",
"if",
"it",
"s",
"defined"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app_support.rb#L265-L271 | train |
davetron5000/gli | lib/gli/app_support.rb | GLI.AppSupport.regular_error_handling? | def regular_error_handling?(ex) #:nodoc:
if @error_block
return true if (ex.respond_to?(:exit_code) && ex.exit_code == 0)
@error_block.call(ex)
else
true
end
end | ruby | def regular_error_handling?(ex) #:nodoc:
if @error_block
return true if (ex.respond_to?(:exit_code) && ex.exit_code == 0)
@error_block.call(ex)
else
true
end
end | [
"def",
"regular_error_handling?",
"(",
"ex",
")",
"#:nodoc:",
"if",
"@error_block",
"return",
"true",
"if",
"(",
"ex",
".",
"respond_to?",
"(",
":exit_code",
")",
"&&",
"ex",
".",
"exit_code",
"==",
"0",
")",
"@error_block",
".",
"call",
"(",
"ex",
")",
"else",
"true",
"end",
"end"
] | Returns true if we should proceed with GLI's basic error handling.
This calls the error block if the user provided one | [
"Returns",
"true",
"if",
"we",
"should",
"proceed",
"with",
"GLI",
"s",
"basic",
"error",
"handling",
".",
"This",
"calls",
"the",
"error",
"block",
"if",
"the",
"user",
"provided",
"one"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/app_support.rb#L275-L282 | train |
davetron5000/gli | lib/gli/dsl.rb | GLI.DSL.flag | def flag(*names)
options = extract_options(names)
names = [names].flatten
verify_unused(names)
flag = Flag.new(names,options)
flags[flag.name] = flag
clear_nexts
flags_declaration_order << flag
flag
end | ruby | def flag(*names)
options = extract_options(names)
names = [names].flatten
verify_unused(names)
flag = Flag.new(names,options)
flags[flag.name] = flag
clear_nexts
flags_declaration_order << flag
flag
end | [
"def",
"flag",
"(",
"*",
"names",
")",
"options",
"=",
"extract_options",
"(",
"names",
")",
"names",
"=",
"[",
"names",
"]",
".",
"flatten",
"verify_unused",
"(",
"names",
")",
"flag",
"=",
"Flag",
".",
"new",
"(",
"names",
",",
"options",
")",
"flags",
"[",
"flag",
".",
"name",
"]",
"=",
"flag",
"clear_nexts",
"flags_declaration_order",
"<<",
"flag",
"flag",
"end"
] | Create a flag, which is a switch that takes an argument
+names+:: a String or Symbol, or an Array of String or Symbol that represent all the different names
and aliases for this flag. The last element can be a hash of options:
+:desc+:: the description, instead of using #desc
+:long_desc+:: the long_description, instead of using #long_desc
+:default_value+:: the default value, instead of using #default_value
+:arg_name+:: the arg name, instead of using #arg_name
+:must_match+:: A regexp that the flag's value must match or an array of allowable values
+:type+:: A Class (or object you passed to GLI::App#accept) to trigger type coversion
+:multiple+:: if true, flag may be used multiple times and values are stored in an array
Example:
desc 'Set the filename'
flag [:f,:filename,'file-name']
flag :ipaddress, :desc => "IP Address", :must_match => /\d+\.\d+\.\d+\.\d+/
flag :names, :desc => "list of names", :type => Array
Produces:
-f, --filename, --file-name=arg Set the filename | [
"Create",
"a",
"flag",
"which",
"is",
"a",
"switch",
"that",
"takes",
"an",
"argument"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/dsl.rb#L92-L103 | train |
davetron5000/gli | lib/gli/dsl.rb | GLI.DSL.verify_unused | def verify_unused(names) # :nodoc:
names.each do |name|
verify_unused_in_option(name,flags,"flag")
verify_unused_in_option(name,switches,"switch")
end
end | ruby | def verify_unused(names) # :nodoc:
names.each do |name|
verify_unused_in_option(name,flags,"flag")
verify_unused_in_option(name,switches,"switch")
end
end | [
"def",
"verify_unused",
"(",
"names",
")",
"# :nodoc:",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"verify_unused_in_option",
"(",
"name",
",",
"flags",
",",
"\"flag\"",
")",
"verify_unused_in_option",
"(",
"name",
",",
"switches",
",",
"\"switch\"",
")",
"end",
"end"
] | Checks that the names passed in have not been used in another flag or option | [
"Checks",
"that",
"the",
"names",
"passed",
"in",
"have",
"not",
"been",
"used",
"in",
"another",
"flag",
"or",
"option"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/dsl.rb#L218-L223 | train |
davetron5000/gli | lib/gli/gli_option_parser.rb | GLI.GLIOptionParser.parse_options | def parse_options(args) # :nodoc:
option_parser_class = self.class.const_get("#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser")
OptionParsingResult.new.tap { |parsing_result|
parsing_result.arguments = args
parsing_result = @global_option_parser.parse!(parsing_result)
option_parser_class.new(@accepts).parse!(parsing_result, options[:argument_handling_strategy])
}
end | ruby | def parse_options(args) # :nodoc:
option_parser_class = self.class.const_get("#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser")
OptionParsingResult.new.tap { |parsing_result|
parsing_result.arguments = args
parsing_result = @global_option_parser.parse!(parsing_result)
option_parser_class.new(@accepts).parse!(parsing_result, options[:argument_handling_strategy])
}
end | [
"def",
"parse_options",
"(",
"args",
")",
"# :nodoc:",
"option_parser_class",
"=",
"self",
".",
"class",
".",
"const_get",
"(",
"\"#{options[:subcommand_option_handling_strategy].to_s.capitalize}CommandOptionParser\"",
")",
"OptionParsingResult",
".",
"new",
".",
"tap",
"{",
"|",
"parsing_result",
"|",
"parsing_result",
".",
"arguments",
"=",
"args",
"parsing_result",
"=",
"@global_option_parser",
".",
"parse!",
"(",
"parsing_result",
")",
"option_parser_class",
".",
"new",
"(",
"@accepts",
")",
".",
"parse!",
"(",
"parsing_result",
",",
"options",
"[",
":argument_handling_strategy",
"]",
")",
"}",
"end"
] | Given the command-line argument array, returns an OptionParsingResult | [
"Given",
"the",
"command",
"-",
"line",
"argument",
"array",
"returns",
"an",
"OptionParsingResult"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/gli_option_parser.rb#L27-L34 | train |
davetron5000/gli | lib/gli/gli_option_block_parser.rb | GLI.GLIOptionBlockParser.parse! | def parse!(args)
do_parse(args)
rescue OptionParser::InvalidOption => ex
@exception_handler.call("Unknown option #{ex.args.join(' ')}",@extra_error_context)
rescue OptionParser::InvalidArgument => ex
@exception_handler.call("#{ex.reason}: #{ex.args.join(' ')}",@extra_error_context)
end | ruby | def parse!(args)
do_parse(args)
rescue OptionParser::InvalidOption => ex
@exception_handler.call("Unknown option #{ex.args.join(' ')}",@extra_error_context)
rescue OptionParser::InvalidArgument => ex
@exception_handler.call("#{ex.reason}: #{ex.args.join(' ')}",@extra_error_context)
end | [
"def",
"parse!",
"(",
"args",
")",
"do_parse",
"(",
"args",
")",
"rescue",
"OptionParser",
"::",
"InvalidOption",
"=>",
"ex",
"@exception_handler",
".",
"call",
"(",
"\"Unknown option #{ex.args.join(' ')}\"",
",",
"@extra_error_context",
")",
"rescue",
"OptionParser",
"::",
"InvalidArgument",
"=>",
"ex",
"@exception_handler",
".",
"call",
"(",
"\"#{ex.reason}: #{ex.args.join(' ')}\"",
",",
"@extra_error_context",
")",
"end"
] | Create the parser using the given +OptionParser+ instance and exception handling
strategy.
option_parser_factory:: An +OptionParserFactory+ instance, configured to parse wherever you are on the command line
exception_klass_or_block:: means of handling exceptions from +OptionParser+. One of:
an exception class:: will be raised on errors with a message
lambda/block:: will be called with a single argument - the error message.
Parse the given argument list, returning the unparsed arguments and options hash of parsed arguments.
Exceptions from +OptionParser+ are given to the handler configured in the constructor
args:: argument list. This will be mutated
Returns unparsed args | [
"Create",
"the",
"parser",
"using",
"the",
"given",
"+",
"OptionParser",
"+",
"instance",
"and",
"exception",
"handling",
"strategy",
"."
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/gli_option_block_parser.rb#L32-L38 | train |
davetron5000/gli | lib/gli/command_line_token.rb | GLI.CommandLineToken.parse_names | def parse_names(names)
# Allow strings; convert to symbols
names = [names].flatten.map { |name| name.to_sym }
names_hash = {}
names.each do |name|
raise ArgumentError.new("#{name} has spaces; they are not allowed") if name.to_s =~ /\s/
names_hash[self.class.name_as_string(name)] = true
end
name = names.shift
aliases = names.length > 0 ? names : nil
[name,aliases,names_hash]
end | ruby | def parse_names(names)
# Allow strings; convert to symbols
names = [names].flatten.map { |name| name.to_sym }
names_hash = {}
names.each do |name|
raise ArgumentError.new("#{name} has spaces; they are not allowed") if name.to_s =~ /\s/
names_hash[self.class.name_as_string(name)] = true
end
name = names.shift
aliases = names.length > 0 ? names : nil
[name,aliases,names_hash]
end | [
"def",
"parse_names",
"(",
"names",
")",
"# Allow strings; convert to symbols",
"names",
"=",
"[",
"names",
"]",
".",
"flatten",
".",
"map",
"{",
"|",
"name",
"|",
"name",
".",
"to_sym",
"}",
"names_hash",
"=",
"{",
"}",
"names",
".",
"each",
"do",
"|",
"name",
"|",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"#{name} has spaces; they are not allowed\"",
")",
"if",
"name",
".",
"to_s",
"=~",
"/",
"\\s",
"/",
"names_hash",
"[",
"self",
".",
"class",
".",
"name_as_string",
"(",
"name",
")",
"]",
"=",
"true",
"end",
"name",
"=",
"names",
".",
"shift",
"aliases",
"=",
"names",
".",
"length",
">",
"0",
"?",
"names",
":",
"nil",
"[",
"name",
",",
"aliases",
",",
"names_hash",
"]",
"end"
] | Handles dealing with the "names" param, parsing
it into the primary name and aliases list | [
"Handles",
"dealing",
"with",
"the",
"names",
"param",
"parsing",
"it",
"into",
"the",
"primary",
"name",
"and",
"aliases",
"list"
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/command_line_token.rb#L38-L49 | train |
davetron5000/gli | lib/gli/flag.rb | GLI.Flag.all_forms | def all_forms(joiner=', ')
forms = all_forms_a
string = forms.join(joiner)
if forms[-1] =~ /^\-\-/
string += '='
else
string += ' '
end
string += @argument_name
return string
end | ruby | def all_forms(joiner=', ')
forms = all_forms_a
string = forms.join(joiner)
if forms[-1] =~ /^\-\-/
string += '='
else
string += ' '
end
string += @argument_name
return string
end | [
"def",
"all_forms",
"(",
"joiner",
"=",
"', '",
")",
"forms",
"=",
"all_forms_a",
"string",
"=",
"forms",
".",
"join",
"(",
"joiner",
")",
"if",
"forms",
"[",
"-",
"1",
"]",
"=~",
"/",
"\\-",
"\\-",
"/",
"string",
"+=",
"'='",
"else",
"string",
"+=",
"' '",
"end",
"string",
"+=",
"@argument_name",
"return",
"string",
"end"
] | Returns a string of all possible forms
of this flag. Mostly intended for printing
to the user. | [
"Returns",
"a",
"string",
"of",
"all",
"possible",
"forms",
"of",
"this",
"flag",
".",
"Mostly",
"intended",
"for",
"printing",
"to",
"the",
"user",
"."
] | 2a582cc04ae182ae29411ba888c23a91a6fe8d99 | https://github.com/davetron5000/gli/blob/2a582cc04ae182ae29411ba888c23a91a6fe8d99/lib/gli/flag.rb#L85-L95 | train |
jamesotron/hamlbars | lib/hamlbars/template.rb | Hamlbars.Template.evaluate | def evaluate(scope, locals, &block)
if @engine.respond_to?(:precompiled_method_return_value, true)
super(scope, locals, &block)
else
@engine.render(scope, locals, &block)
end
end | ruby | def evaluate(scope, locals, &block)
if @engine.respond_to?(:precompiled_method_return_value, true)
super(scope, locals, &block)
else
@engine.render(scope, locals, &block)
end
end | [
"def",
"evaluate",
"(",
"scope",
",",
"locals",
",",
"&",
"block",
")",
"if",
"@engine",
".",
"respond_to?",
"(",
":precompiled_method_return_value",
",",
"true",
")",
"super",
"(",
"scope",
",",
"locals",
",",
"block",
")",
"else",
"@engine",
".",
"render",
"(",
"scope",
",",
"locals",
",",
"block",
")",
"end",
"end"
] | Uses Haml to render the template into an HTML string, then
wraps it in the neccessary JavaScript to serve to the client. | [
"Uses",
"Haml",
"to",
"render",
"the",
"template",
"into",
"an",
"HTML",
"string",
"then",
"wraps",
"it",
"in",
"the",
"neccessary",
"JavaScript",
"to",
"serve",
"to",
"the",
"client",
"."
] | 7f41686b28343ac68e7c90e04f481802e98f38d5 | https://github.com/jamesotron/hamlbars/blob/7f41686b28343ac68e7c90e04f481802e98f38d5/lib/hamlbars/template.rb#L26-L32 | train |
vitalie/webshot | lib/webshot/screenshot.rb | Webshot.Screenshot.capture | def capture(url, path, opts = {})
begin
# Default settings
width = opts.fetch(:width, 120)
height = opts.fetch(:height, 90)
gravity = opts.fetch(:gravity, "north")
quality = opts.fetch(:quality, 85)
full = opts.fetch(:full, true)
selector = opts.fetch(:selector, nil)
allowed_status_codes = opts.fetch(:allowed_status_codes, [])
# Reset session before visiting url
Capybara.reset_sessions! unless @session_started
@session_started = false
# Open page
visit url
# Timeout
sleep opts[:timeout] if opts[:timeout]
# Check response code
status_code = page.driver.status_code.to_i
unless valid_status_code?(status_code, allowed_status_codes)
fail WebshotError, "Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}"
end
tmp = Tempfile.new(["webshot", ".png"])
tmp.close
begin
screenshot_opts = { full: full }
screenshot_opts = screenshot_opts.merge({ selector: selector }) if selector
# Save screenshot to file
page.driver.save_screenshot(tmp.path, screenshot_opts)
# Resize screenshot
thumb = MiniMagick::Image.open(tmp.path)
if block_given?
# Customize MiniMagick options
yield thumb
else
thumb.combine_options do |c|
c.thumbnail "#{width}x"
c.background "white"
c.extent "#{width}x#{height}"
c.gravity gravity
c.quality quality
end
end
# Save thumbnail
thumb.write path
thumb
ensure
tmp.unlink
end
rescue Capybara::Poltergeist::StatusFailError, Capybara::Poltergeist::BrowserError, Capybara::Poltergeist::DeadClient, Capybara::Poltergeist::TimeoutError, Errno::EPIPE => e
# TODO: Handle Errno::EPIPE and Errno::ECONNRESET
raise WebshotError.new("Capybara error: #{e.message.inspect}")
end
end | ruby | def capture(url, path, opts = {})
begin
# Default settings
width = opts.fetch(:width, 120)
height = opts.fetch(:height, 90)
gravity = opts.fetch(:gravity, "north")
quality = opts.fetch(:quality, 85)
full = opts.fetch(:full, true)
selector = opts.fetch(:selector, nil)
allowed_status_codes = opts.fetch(:allowed_status_codes, [])
# Reset session before visiting url
Capybara.reset_sessions! unless @session_started
@session_started = false
# Open page
visit url
# Timeout
sleep opts[:timeout] if opts[:timeout]
# Check response code
status_code = page.driver.status_code.to_i
unless valid_status_code?(status_code, allowed_status_codes)
fail WebshotError, "Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}"
end
tmp = Tempfile.new(["webshot", ".png"])
tmp.close
begin
screenshot_opts = { full: full }
screenshot_opts = screenshot_opts.merge({ selector: selector }) if selector
# Save screenshot to file
page.driver.save_screenshot(tmp.path, screenshot_opts)
# Resize screenshot
thumb = MiniMagick::Image.open(tmp.path)
if block_given?
# Customize MiniMagick options
yield thumb
else
thumb.combine_options do |c|
c.thumbnail "#{width}x"
c.background "white"
c.extent "#{width}x#{height}"
c.gravity gravity
c.quality quality
end
end
# Save thumbnail
thumb.write path
thumb
ensure
tmp.unlink
end
rescue Capybara::Poltergeist::StatusFailError, Capybara::Poltergeist::BrowserError, Capybara::Poltergeist::DeadClient, Capybara::Poltergeist::TimeoutError, Errno::EPIPE => e
# TODO: Handle Errno::EPIPE and Errno::ECONNRESET
raise WebshotError.new("Capybara error: #{e.message.inspect}")
end
end | [
"def",
"capture",
"(",
"url",
",",
"path",
",",
"opts",
"=",
"{",
"}",
")",
"begin",
"# Default settings",
"width",
"=",
"opts",
".",
"fetch",
"(",
":width",
",",
"120",
")",
"height",
"=",
"opts",
".",
"fetch",
"(",
":height",
",",
"90",
")",
"gravity",
"=",
"opts",
".",
"fetch",
"(",
":gravity",
",",
"\"north\"",
")",
"quality",
"=",
"opts",
".",
"fetch",
"(",
":quality",
",",
"85",
")",
"full",
"=",
"opts",
".",
"fetch",
"(",
":full",
",",
"true",
")",
"selector",
"=",
"opts",
".",
"fetch",
"(",
":selector",
",",
"nil",
")",
"allowed_status_codes",
"=",
"opts",
".",
"fetch",
"(",
":allowed_status_codes",
",",
"[",
"]",
")",
"# Reset session before visiting url",
"Capybara",
".",
"reset_sessions!",
"unless",
"@session_started",
"@session_started",
"=",
"false",
"# Open page",
"visit",
"url",
"# Timeout",
"sleep",
"opts",
"[",
":timeout",
"]",
"if",
"opts",
"[",
":timeout",
"]",
"# Check response code",
"status_code",
"=",
"page",
".",
"driver",
".",
"status_code",
".",
"to_i",
"unless",
"valid_status_code?",
"(",
"status_code",
",",
"allowed_status_codes",
")",
"fail",
"WebshotError",
",",
"\"Could not fetch page: #{url.inspect}, error code: #{page.driver.status_code}\"",
"end",
"tmp",
"=",
"Tempfile",
".",
"new",
"(",
"[",
"\"webshot\"",
",",
"\".png\"",
"]",
")",
"tmp",
".",
"close",
"begin",
"screenshot_opts",
"=",
"{",
"full",
":",
"full",
"}",
"screenshot_opts",
"=",
"screenshot_opts",
".",
"merge",
"(",
"{",
"selector",
":",
"selector",
"}",
")",
"if",
"selector",
"# Save screenshot to file",
"page",
".",
"driver",
".",
"save_screenshot",
"(",
"tmp",
".",
"path",
",",
"screenshot_opts",
")",
"# Resize screenshot",
"thumb",
"=",
"MiniMagick",
"::",
"Image",
".",
"open",
"(",
"tmp",
".",
"path",
")",
"if",
"block_given?",
"# Customize MiniMagick options",
"yield",
"thumb",
"else",
"thumb",
".",
"combine_options",
"do",
"|",
"c",
"|",
"c",
".",
"thumbnail",
"\"#{width}x\"",
"c",
".",
"background",
"\"white\"",
"c",
".",
"extent",
"\"#{width}x#{height}\"",
"c",
".",
"gravity",
"gravity",
"c",
".",
"quality",
"quality",
"end",
"end",
"# Save thumbnail",
"thumb",
".",
"write",
"path",
"thumb",
"ensure",
"tmp",
".",
"unlink",
"end",
"rescue",
"Capybara",
"::",
"Poltergeist",
"::",
"StatusFailError",
",",
"Capybara",
"::",
"Poltergeist",
"::",
"BrowserError",
",",
"Capybara",
"::",
"Poltergeist",
"::",
"DeadClient",
",",
"Capybara",
"::",
"Poltergeist",
"::",
"TimeoutError",
",",
"Errno",
"::",
"EPIPE",
"=>",
"e",
"# TODO: Handle Errno::EPIPE and Errno::ECONNRESET",
"raise",
"WebshotError",
".",
"new",
"(",
"\"Capybara error: #{e.message.inspect}\"",
")",
"end",
"end"
] | Captures a screenshot of +url+ saving it to +path+. | [
"Captures",
"a",
"screenshot",
"of",
"+",
"url",
"+",
"saving",
"it",
"to",
"+",
"path",
"+",
"."
] | 2464ee47a34c6c7a8bade4686c7b179cd1c69e30 | https://github.com/vitalie/webshot/blob/2464ee47a34c6c7a8bade4686c7b179cd1c69e30/lib/webshot/screenshot.rb#L36-L97 | train |
marinosoftware/active_storage_drag_and_drop | lib/active_storage_drag_and_drop/form_builder.rb | ActiveStorageDragAndDrop.FormBuilder.drag_and_drop_file_field | def drag_and_drop_file_field(method, content_or_options = nil, options = {}, &block)
if block_given?
options = content_or_options if content_or_options.is_a? Hash
drag_and_drop_file_field_string(method, capture(&block), options)
else
drag_and_drop_file_field_string(method, content_or_options, options)
end
end | ruby | def drag_and_drop_file_field(method, content_or_options = nil, options = {}, &block)
if block_given?
options = content_or_options if content_or_options.is_a? Hash
drag_and_drop_file_field_string(method, capture(&block), options)
else
drag_and_drop_file_field_string(method, content_or_options, options)
end
end | [
"def",
"drag_and_drop_file_field",
"(",
"method",
",",
"content_or_options",
"=",
"nil",
",",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"if",
"block_given?",
"options",
"=",
"content_or_options",
"if",
"content_or_options",
".",
"is_a?",
"Hash",
"drag_and_drop_file_field_string",
"(",
"method",
",",
"capture",
"(",
"block",
")",
",",
"options",
")",
"else",
"drag_and_drop_file_field_string",
"(",
"method",
",",
"content_or_options",
",",
"options",
")",
"end",
"end"
] | Returns a file upload input tag wrapped in markup that allows dragging and dropping of files
onto the element.
@author Ian Grant
@see file:README.md#Usage Usage section of the README
@param [Symbol] method The attribute on the target model to attach the files to.
@param [String] content The content to render inside of the drag and drop file field.
@param [Hash] options A hash of options to customise the file field.
@option options [Boolean] :disabled If set to true, the user will not be able to use this
input.
@option options [Boolean] :mutiple If set to true, *in most updated browsers* the user will
be allowed to select multiple files.
@option options [String] :accept If set to one or multiple mime-types, the user will be
suggested a filter when choosing a file. You still need to set up model validations.
@option options [Integer] :size_limit The upper limit on filesize to accept in bytes.
Client-side validation only. You still need to set up model validations.
@return [String] The generated file field markup.
@example
# Accept only PNGs or JPEGs up to 5MB in size:
form.drag_and_drop_file_field :images, nil, accept: 'image/png, image/jpeg',
size_limit: 5_000_000
@example
# Pass custom content string:
form.drag_and_drop_file_field :images, '<div>Drag and Drop!</div>', accept: 'image/png'
@example
# Pass a block of content instead of passing a string
<%= form.drag_and_drop_file_field(:images, accept: 'image/png') do %>
<strong>Drag and Drop</strong> PNG files here or <strong>click to browse</strong>
<% end %> | [
"Returns",
"a",
"file",
"upload",
"input",
"tag",
"wrapped",
"in",
"markup",
"that",
"allows",
"dragging",
"and",
"dropping",
"of",
"files",
"onto",
"the",
"element",
"."
] | c67e08709fdf31c13fed05db911e97cbaa1ebd42 | https://github.com/marinosoftware/active_storage_drag_and_drop/blob/c67e08709fdf31c13fed05db911e97cbaa1ebd42/lib/active_storage_drag_and_drop/form_builder.rb#L44-L51 | train |
marinosoftware/active_storage_drag_and_drop | lib/active_storage_drag_and_drop/form_builder.rb | ActiveStorageDragAndDrop.FormBuilder.unpersisted_attachment_fields | def unpersisted_attachment_fields(method, multiple)
unpersisted_attachments(method).map.with_index do |attachment, idx|
hidden_field method,
mutiple: multiple ? :multiple : false, value: attachment.signed_id,
name: "#{object_name}[#{method}]#{'[]' if multiple}",
data: {
direct_upload_id: idx,
uploaded_file: { name: attachment.filename, size: attachment.byte_size },
icon_container_id: "asdndz-#{object_name}_#{method}__icon-container"
}
end
end | ruby | def unpersisted_attachment_fields(method, multiple)
unpersisted_attachments(method).map.with_index do |attachment, idx|
hidden_field method,
mutiple: multiple ? :multiple : false, value: attachment.signed_id,
name: "#{object_name}[#{method}]#{'[]' if multiple}",
data: {
direct_upload_id: idx,
uploaded_file: { name: attachment.filename, size: attachment.byte_size },
icon_container_id: "asdndz-#{object_name}_#{method}__icon-container"
}
end
end | [
"def",
"unpersisted_attachment_fields",
"(",
"method",
",",
"multiple",
")",
"unpersisted_attachments",
"(",
"method",
")",
".",
"map",
".",
"with_index",
"do",
"|",
"attachment",
",",
"idx",
"|",
"hidden_field",
"method",
",",
"mutiple",
":",
"multiple",
"?",
":multiple",
":",
"false",
",",
"value",
":",
"attachment",
".",
"signed_id",
",",
"name",
":",
"\"#{object_name}[#{method}]#{'[]' if multiple}\"",
",",
"data",
":",
"{",
"direct_upload_id",
":",
"idx",
",",
"uploaded_file",
":",
"{",
"name",
":",
"attachment",
".",
"filename",
",",
"size",
":",
"attachment",
".",
"byte_size",
"}",
",",
"icon_container_id",
":",
"\"asdndz-#{object_name}_#{method}__icon-container\"",
"}",
"end",
"end"
] | returns an array of tags used to pre-populate the the dropzone with tags queueing unpersisted
file attachments for attachment at the next form submission.
@author Ian Grant
@param [Symbol] method The attribute on the target model to attach the files to.
@param [Boolean] multiple Whether the dropzone should accept multiple attachments or not.
@return [Array] An array of hidden field tags for each unpersisted file attachment. | [
"returns",
"an",
"array",
"of",
"tags",
"used",
"to",
"pre",
"-",
"populate",
"the",
"the",
"dropzone",
"with",
"tags",
"queueing",
"unpersisted",
"file",
"attachments",
"for",
"attachment",
"at",
"the",
"next",
"form",
"submission",
"."
] | c67e08709fdf31c13fed05db911e97cbaa1ebd42 | https://github.com/marinosoftware/active_storage_drag_and_drop/blob/c67e08709fdf31c13fed05db911e97cbaa1ebd42/lib/active_storage_drag_and_drop/form_builder.rb#L84-L95 | train |
marinosoftware/active_storage_drag_and_drop | lib/active_storage_drag_and_drop/form_builder.rb | ActiveStorageDragAndDrop.FormBuilder.default_file_field_options | def default_file_field_options(method)
{
multiple: @object.send(method).is_a?(ActiveStorage::Attached::Many),
direct_upload: true,
style: 'display:none;',
data: {
dnd: true,
dnd_zone_id: "asdndz-#{object_name}_#{method}",
icon_container_id: "asdndz-#{object_name}_#{method}__icon-container"
}
}
end | ruby | def default_file_field_options(method)
{
multiple: @object.send(method).is_a?(ActiveStorage::Attached::Many),
direct_upload: true,
style: 'display:none;',
data: {
dnd: true,
dnd_zone_id: "asdndz-#{object_name}_#{method}",
icon_container_id: "asdndz-#{object_name}_#{method}__icon-container"
}
}
end | [
"def",
"default_file_field_options",
"(",
"method",
")",
"{",
"multiple",
":",
"@object",
".",
"send",
"(",
"method",
")",
".",
"is_a?",
"(",
"ActiveStorage",
"::",
"Attached",
"::",
"Many",
")",
",",
"direct_upload",
":",
"true",
",",
"style",
":",
"'display:none;'",
",",
"data",
":",
"{",
"dnd",
":",
"true",
",",
"dnd_zone_id",
":",
"\"asdndz-#{object_name}_#{method}\"",
",",
"icon_container_id",
":",
"\"asdndz-#{object_name}_#{method}__icon-container\"",
"}",
"}",
"end"
] | Generates a hash of default options for the embedded file input field.
@author Ian Grant
@param [Symbol] method The attribute on the target model to attach the files to.
@return [Hash] The default options for the file field | [
"Generates",
"a",
"hash",
"of",
"default",
"options",
"for",
"the",
"embedded",
"file",
"input",
"field",
"."
] | c67e08709fdf31c13fed05db911e97cbaa1ebd42 | https://github.com/marinosoftware/active_storage_drag_and_drop/blob/c67e08709fdf31c13fed05db911e97cbaa1ebd42/lib/active_storage_drag_and_drop/form_builder.rb#L120-L131 | train |
marinosoftware/active_storage_drag_and_drop | lib/active_storage_drag_and_drop/form_builder.rb | ActiveStorageDragAndDrop.FormBuilder.file_field_options | def file_field_options(method, custom_options)
default_file_field_options(method).merge(custom_options) do |_key, default, custom|
default.is_a?(Hash) && custom.is_a?(Hash) ? default.merge(custom) : custom
end
end | ruby | def file_field_options(method, custom_options)
default_file_field_options(method).merge(custom_options) do |_key, default, custom|
default.is_a?(Hash) && custom.is_a?(Hash) ? default.merge(custom) : custom
end
end | [
"def",
"file_field_options",
"(",
"method",
",",
"custom_options",
")",
"default_file_field_options",
"(",
"method",
")",
".",
"merge",
"(",
"custom_options",
")",
"do",
"|",
"_key",
",",
"default",
",",
"custom",
"|",
"default",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"custom",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"default",
".",
"merge",
"(",
"custom",
")",
":",
"custom",
"end",
"end"
] | Merges the user provided options with the default options overwriting the defaults to
generate the final options passed to the embedded file input field.
@author Ian Grant
@param [Symbol] method The attribute on the target model to attach the files to.
@param [Hash] custom_options The user provided custom options hash.
@return [Hash] The user provided options and default options merged. | [
"Merges",
"the",
"user",
"provided",
"options",
"with",
"the",
"default",
"options",
"overwriting",
"the",
"defaults",
"to",
"generate",
"the",
"final",
"options",
"passed",
"to",
"the",
"embedded",
"file",
"input",
"field",
"."
] | c67e08709fdf31c13fed05db911e97cbaa1ebd42 | https://github.com/marinosoftware/active_storage_drag_and_drop/blob/c67e08709fdf31c13fed05db911e97cbaa1ebd42/lib/active_storage_drag_and_drop/form_builder.rb#L150-L154 | train |
state-machines/state_machines | lib/state_machines/state.rb | StateMachines.State.value | def value(eval = true)
if @value.is_a?(Proc) && eval
if cache_value?
@value = @value.call
machine.states.update(self)
@value
else
@value.call
end
else
@value
end
end | ruby | def value(eval = true)
if @value.is_a?(Proc) && eval
if cache_value?
@value = @value.call
machine.states.update(self)
@value
else
@value.call
end
else
@value
end
end | [
"def",
"value",
"(",
"eval",
"=",
"true",
")",
"if",
"@value",
".",
"is_a?",
"(",
"Proc",
")",
"&&",
"eval",
"if",
"cache_value?",
"@value",
"=",
"@value",
".",
"call",
"machine",
".",
"states",
".",
"update",
"(",
"self",
")",
"@value",
"else",
"@value",
".",
"call",
"end",
"else",
"@value",
"end",
"end"
] | The value that represents this state. This will optionally evaluate the
original block if it's a lambda block. Otherwise, the static value is
returned.
For example,
State.new(machine, :parked, :value => 1).value # => 1
State.new(machine, :parked, :value => lambda {Time.now}).value # => Tue Jan 01 00:00:00 UTC 2008
State.new(machine, :parked, :value => lambda {Time.now}).value(false) # => <Proc:0xb6ea7ca0@...> | [
"The",
"value",
"that",
"represents",
"this",
"state",
".",
"This",
"will",
"optionally",
"evaluate",
"the",
"original",
"block",
"if",
"it",
"s",
"a",
"lambda",
"block",
".",
"Otherwise",
"the",
"static",
"value",
"is",
"returned",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state.rb#L143-L155 | train |
state-machines/state_machines | lib/state_machines/state.rb | StateMachines.State.context_methods | def context_methods
@context.instance_methods.inject({}) do |methods, name|
methods.merge(name.to_sym => @context.instance_method(name))
end
end | ruby | def context_methods
@context.instance_methods.inject({}) do |methods, name|
methods.merge(name.to_sym => @context.instance_method(name))
end
end | [
"def",
"context_methods",
"@context",
".",
"instance_methods",
".",
"inject",
"(",
"{",
"}",
")",
"do",
"|",
"methods",
",",
"name",
"|",
"methods",
".",
"merge",
"(",
"name",
".",
"to_sym",
"=>",
"@context",
".",
"instance_method",
"(",
"name",
")",
")",
"end",
"end"
] | The list of methods that have been defined in this state's context | [
"The",
"list",
"of",
"methods",
"that",
"have",
"been",
"defined",
"in",
"this",
"state",
"s",
"context"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state.rb#L208-L212 | train |
state-machines/state_machines | lib/state_machines/state.rb | StateMachines.State.call | def call(object, method, *args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
options = {:method_name => method}.merge(options)
state = machine.states.match!(object)
if state == self && object.respond_to?(method)
object.send(method, *args, &block)
elsif method_missing = options[:method_missing]
# Dispatch to the superclass since the object either isn't in this state
# or this state doesn't handle the method
begin
method_missing.call
rescue NoMethodError => ex
if ex.name.to_s == options[:method_name].to_s && ex.args == args
# No valid context for this method
raise InvalidContext.new(object, "State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}")
else
raise
end
end
end
end | ruby | def call(object, method, *args, &block)
options = args.last.is_a?(Hash) ? args.pop : {}
options = {:method_name => method}.merge(options)
state = machine.states.match!(object)
if state == self && object.respond_to?(method)
object.send(method, *args, &block)
elsif method_missing = options[:method_missing]
# Dispatch to the superclass since the object either isn't in this state
# or this state doesn't handle the method
begin
method_missing.call
rescue NoMethodError => ex
if ex.name.to_s == options[:method_name].to_s && ex.args == args
# No valid context for this method
raise InvalidContext.new(object, "State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}")
else
raise
end
end
end
end | [
"def",
"call",
"(",
"object",
",",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"options",
"=",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"args",
".",
"pop",
":",
"{",
"}",
"options",
"=",
"{",
":method_name",
"=>",
"method",
"}",
".",
"merge",
"(",
"options",
")",
"state",
"=",
"machine",
".",
"states",
".",
"match!",
"(",
"object",
")",
"if",
"state",
"==",
"self",
"&&",
"object",
".",
"respond_to?",
"(",
"method",
")",
"object",
".",
"send",
"(",
"method",
",",
"args",
",",
"block",
")",
"elsif",
"method_missing",
"=",
"options",
"[",
":method_missing",
"]",
"# Dispatch to the superclass since the object either isn't in this state",
"# or this state doesn't handle the method",
"begin",
"method_missing",
".",
"call",
"rescue",
"NoMethodError",
"=>",
"ex",
"if",
"ex",
".",
"name",
".",
"to_s",
"==",
"options",
"[",
":method_name",
"]",
".",
"to_s",
"&&",
"ex",
".",
"args",
"==",
"args",
"# No valid context for this method",
"raise",
"InvalidContext",
".",
"new",
"(",
"object",
",",
"\"State #{state.name.inspect} for #{machine.name.inspect} is not a valid context for calling ##{options[:method_name]}\"",
")",
"else",
"raise",
"end",
"end",
"end",
"end"
] | Calls a method defined in this state's context on the given object. All
arguments and any block will be passed into the method defined.
If the method has never been defined for this state, then a NoMethodError
will be raised. | [
"Calls",
"a",
"method",
"defined",
"in",
"this",
"state",
"s",
"context",
"on",
"the",
"given",
"object",
".",
"All",
"arguments",
"and",
"any",
"block",
"will",
"be",
"passed",
"into",
"the",
"method",
"defined",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state.rb#L219-L240 | train |
state-machines/state_machines | lib/state_machines/state.rb | StateMachines.State.add_predicate | def add_predicate
# Checks whether the current value matches this state
machine.define_helper(:instance, "#{qualified_name}?") do |machine, object|
machine.states.matches?(object, name)
end
end | ruby | def add_predicate
# Checks whether the current value matches this state
machine.define_helper(:instance, "#{qualified_name}?") do |machine, object|
machine.states.matches?(object, name)
end
end | [
"def",
"add_predicate",
"# Checks whether the current value matches this state",
"machine",
".",
"define_helper",
"(",
":instance",
",",
"\"#{qualified_name}?\"",
")",
"do",
"|",
"machine",
",",
"object",
"|",
"machine",
".",
"states",
".",
"matches?",
"(",
"object",
",",
"name",
")",
"end",
"end"
] | Adds a predicate method to the owner class so long as a name has
actually been configured for the state | [
"Adds",
"a",
"predicate",
"method",
"to",
"the",
"owner",
"class",
"so",
"long",
"as",
"a",
"name",
"has",
"actually",
"been",
"configured",
"for",
"the",
"state"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state.rb#L265-L270 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.initial_state= | def initial_state=(new_initial_state)
@initial_state = new_initial_state
add_states([@initial_state]) unless dynamic_initial_state?
# Update all states to reflect the new initial state
states.each { |state| state.initial = (state.name == @initial_state) }
# Output a warning if there are conflicting initial states for the machine's
# attribute
initial_state = states.detect { |state| state.initial }
if !owner_class_attribute_default.nil? && (dynamic_initial_state? || !owner_class_attribute_default_matches?(initial_state))
warn(
"Both #{owner_class.name} and its #{name.inspect} machine have defined "\
"a different default for \"#{attribute}\". Use only one or the other for "\
"defining defaults to avoid unexpected behaviors."
)
end
end | ruby | def initial_state=(new_initial_state)
@initial_state = new_initial_state
add_states([@initial_state]) unless dynamic_initial_state?
# Update all states to reflect the new initial state
states.each { |state| state.initial = (state.name == @initial_state) }
# Output a warning if there are conflicting initial states for the machine's
# attribute
initial_state = states.detect { |state| state.initial }
if !owner_class_attribute_default.nil? && (dynamic_initial_state? || !owner_class_attribute_default_matches?(initial_state))
warn(
"Both #{owner_class.name} and its #{name.inspect} machine have defined "\
"a different default for \"#{attribute}\". Use only one or the other for "\
"defining defaults to avoid unexpected behaviors."
)
end
end | [
"def",
"initial_state",
"=",
"(",
"new_initial_state",
")",
"@initial_state",
"=",
"new_initial_state",
"add_states",
"(",
"[",
"@initial_state",
"]",
")",
"unless",
"dynamic_initial_state?",
"# Update all states to reflect the new initial state",
"states",
".",
"each",
"{",
"|",
"state",
"|",
"state",
".",
"initial",
"=",
"(",
"state",
".",
"name",
"==",
"@initial_state",
")",
"}",
"# Output a warning if there are conflicting initial states for the machine's",
"# attribute",
"initial_state",
"=",
"states",
".",
"detect",
"{",
"|",
"state",
"|",
"state",
".",
"initial",
"}",
"if",
"!",
"owner_class_attribute_default",
".",
"nil?",
"&&",
"(",
"dynamic_initial_state?",
"||",
"!",
"owner_class_attribute_default_matches?",
"(",
"initial_state",
")",
")",
"warn",
"(",
"\"Both #{owner_class.name} and its #{name.inspect} machine have defined \"",
"\"a different default for \\\"#{attribute}\\\". Use only one or the other for \"",
"\"defining defaults to avoid unexpected behaviors.\"",
")",
"end",
"end"
] | Sets the initial state of the machine. This can be either the static name
of a state or a lambda block which determines the initial state at
creation time. | [
"Sets",
"the",
"initial",
"state",
"of",
"the",
"machine",
".",
"This",
"can",
"be",
"either",
"the",
"static",
"name",
"of",
"a",
"state",
"or",
"a",
"lambda",
"block",
"which",
"determines",
"the",
"initial",
"state",
"at",
"creation",
"time",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L593-L610 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.initialize_state | def initialize_state(object, options = {})
state = initial_state(object)
if state && (options[:force] || initialize_state?(object))
value = state.value
if hash = options[:to]
hash[attribute.to_s] = value
else
write(object, :state, value)
end
end
end | ruby | def initialize_state(object, options = {})
state = initial_state(object)
if state && (options[:force] || initialize_state?(object))
value = state.value
if hash = options[:to]
hash[attribute.to_s] = value
else
write(object, :state, value)
end
end
end | [
"def",
"initialize_state",
"(",
"object",
",",
"options",
"=",
"{",
"}",
")",
"state",
"=",
"initial_state",
"(",
"object",
")",
"if",
"state",
"&&",
"(",
"options",
"[",
":force",
"]",
"||",
"initialize_state?",
"(",
"object",
")",
")",
"value",
"=",
"state",
".",
"value",
"if",
"hash",
"=",
"options",
"[",
":to",
"]",
"hash",
"[",
"attribute",
".",
"to_s",
"]",
"=",
"value",
"else",
"write",
"(",
"object",
",",
":state",
",",
"value",
")",
"end",
"end",
"end"
] | Initializes the state on the given object. Initial values are only set if
the machine's attribute hasn't been previously initialized.
Configuration options:
* <tt>:force</tt> - Whether to initialize the state regardless of its
current value
* <tt>:to</tt> - A hash to set the initial value in instead of writing
directly to the object | [
"Initializes",
"the",
"state",
"on",
"the",
"given",
"object",
".",
"Initial",
"values",
"are",
"only",
"set",
"if",
"the",
"machine",
"s",
"attribute",
"hasn",
"t",
"been",
"previously",
"initialized",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L663-L674 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.define_helper | def define_helper(scope, method, *args, &block)
helper_module = @helper_modules.fetch(scope)
if block_given?
if !self.class.ignore_method_conflicts && conflicting_ancestor = owner_class_ancestor_has_method?(scope, method)
ancestor_name = conflicting_ancestor.name && !conflicting_ancestor.name.empty? ? conflicting_ancestor.name : conflicting_ancestor.to_s
warn "#{scope == :class ? 'Class' : 'Instance'} method \"#{method}\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true."
else
name = self.name
helper_module.class_eval do
define_method(method) do |*block_args|
block.call((scope == :instance ? self.class : self).state_machine(name), self, *block_args)
end
end
end
else
helper_module.class_eval(method, *args)
end
end | ruby | def define_helper(scope, method, *args, &block)
helper_module = @helper_modules.fetch(scope)
if block_given?
if !self.class.ignore_method_conflicts && conflicting_ancestor = owner_class_ancestor_has_method?(scope, method)
ancestor_name = conflicting_ancestor.name && !conflicting_ancestor.name.empty? ? conflicting_ancestor.name : conflicting_ancestor.to_s
warn "#{scope == :class ? 'Class' : 'Instance'} method \"#{method}\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true."
else
name = self.name
helper_module.class_eval do
define_method(method) do |*block_args|
block.call((scope == :instance ? self.class : self).state_machine(name), self, *block_args)
end
end
end
else
helper_module.class_eval(method, *args)
end
end | [
"def",
"define_helper",
"(",
"scope",
",",
"method",
",",
"*",
"args",
",",
"&",
"block",
")",
"helper_module",
"=",
"@helper_modules",
".",
"fetch",
"(",
"scope",
")",
"if",
"block_given?",
"if",
"!",
"self",
".",
"class",
".",
"ignore_method_conflicts",
"&&",
"conflicting_ancestor",
"=",
"owner_class_ancestor_has_method?",
"(",
"scope",
",",
"method",
")",
"ancestor_name",
"=",
"conflicting_ancestor",
".",
"name",
"&&",
"!",
"conflicting_ancestor",
".",
"name",
".",
"empty?",
"?",
"conflicting_ancestor",
".",
"name",
":",
"conflicting_ancestor",
".",
"to_s",
"warn",
"\"#{scope == :class ? 'Class' : 'Instance'} method \\\"#{method}\\\" is already defined in #{ancestor_name}, use generic helper instead or set StateMachines::Machine.ignore_method_conflicts = true.\"",
"else",
"name",
"=",
"self",
".",
"name",
"helper_module",
".",
"class_eval",
"do",
"define_method",
"(",
"method",
")",
"do",
"|",
"*",
"block_args",
"|",
"block",
".",
"call",
"(",
"(",
"scope",
"==",
":instance",
"?",
"self",
".",
"class",
":",
"self",
")",
".",
"state_machine",
"(",
"name",
")",
",",
"self",
",",
"block_args",
")",
"end",
"end",
"end",
"else",
"helper_module",
".",
"class_eval",
"(",
"method",
",",
"args",
")",
"end",
"end"
] | Defines a new helper method in an instance or class scope with the given
name. If the method is already defined in the scope, then this will not
override it.
If passing in a block, there are two side effects to be aware of
1. The method cannot be chained, meaning that the block cannot call +super+
2. If the method is already defined in an ancestor, then it will not get
overridden and a warning will be output.
Example:
# Instance helper
machine.define_helper(:instance, :state_name) do |machine, object|
machine.states.match(object).name
end
# Class helper
machine.define_helper(:class, :state_machine_name) do |machine, klass|
"State"
end
You can also define helpers using string evaluation like so:
# Instance helper
machine.define_helper :instance, <<-end_eval, __FILE__, __LINE__ + 1
def state_name
self.class.state_machine(:state).states.match(self).name
end
end_eval
# Class helper
machine.define_helper :class, <<-end_eval, __FILE__, __LINE__ + 1
def state_machine_name
"State"
end
end_eval | [
"Defines",
"a",
"new",
"helper",
"method",
"in",
"an",
"instance",
"or",
"class",
"scope",
"with",
"the",
"given",
"name",
".",
"If",
"the",
"method",
"is",
"already",
"defined",
"in",
"the",
"scope",
"then",
"this",
"will",
"not",
"override",
"it",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L718-L736 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.state | def state(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:value, :cache, :if, :human_name)
# Store the context so that it can be used for / matched against any state
# that gets added
@states.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any states referenced in the matcher. When matchers are used,
# states are not allowed to be configured.
raise ArgumentError, "Cannot configure states when using matchers (using #{options.inspect})" if options.any?
states = add_states(names.first.values)
else
states = add_states(names)
# Update the configuration for the state(s)
states.each do |state|
if options.include?(:value)
state.value = options[:value]
self.states.update(state)
end
state.human_name = options[:human_name] if options.include?(:human_name)
state.cache = options[:cache] if options.include?(:cache)
state.matcher = options[:if] if options.include?(:if)
end
end
states.length == 1 ? states.first : states
end | ruby | def state(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:value, :cache, :if, :human_name)
# Store the context so that it can be used for / matched against any state
# that gets added
@states.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any states referenced in the matcher. When matchers are used,
# states are not allowed to be configured.
raise ArgumentError, "Cannot configure states when using matchers (using #{options.inspect})" if options.any?
states = add_states(names.first.values)
else
states = add_states(names)
# Update the configuration for the state(s)
states.each do |state|
if options.include?(:value)
state.value = options[:value]
self.states.update(state)
end
state.human_name = options[:human_name] if options.include?(:human_name)
state.cache = options[:cache] if options.include?(:cache)
state.matcher = options[:if] if options.include?(:if)
end
end
states.length == 1 ? states.first : states
end | [
"def",
"state",
"(",
"*",
"names",
",",
"&",
"block",
")",
"options",
"=",
"names",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"names",
".",
"pop",
":",
"{",
"}",
"options",
".",
"assert_valid_keys",
"(",
":value",
",",
":cache",
",",
":if",
",",
":human_name",
")",
"# Store the context so that it can be used for / matched against any state",
"# that gets added",
"@states",
".",
"context",
"(",
"names",
",",
"block",
")",
"if",
"block_given?",
"if",
"names",
".",
"first",
".",
"is_a?",
"(",
"Matcher",
")",
"# Add any states referenced in the matcher. When matchers are used,",
"# states are not allowed to be configured.",
"raise",
"ArgumentError",
",",
"\"Cannot configure states when using matchers (using #{options.inspect})\"",
"if",
"options",
".",
"any?",
"states",
"=",
"add_states",
"(",
"names",
".",
"first",
".",
"values",
")",
"else",
"states",
"=",
"add_states",
"(",
"names",
")",
"# Update the configuration for the state(s)",
"states",
".",
"each",
"do",
"|",
"state",
"|",
"if",
"options",
".",
"include?",
"(",
":value",
")",
"state",
".",
"value",
"=",
"options",
"[",
":value",
"]",
"self",
".",
"states",
".",
"update",
"(",
"state",
")",
"end",
"state",
".",
"human_name",
"=",
"options",
"[",
":human_name",
"]",
"if",
"options",
".",
"include?",
"(",
":human_name",
")",
"state",
".",
"cache",
"=",
"options",
"[",
":cache",
"]",
"if",
"options",
".",
"include?",
"(",
":cache",
")",
"state",
".",
"matcher",
"=",
"options",
"[",
":if",
"]",
"if",
"options",
".",
"include?",
"(",
":if",
")",
"end",
"end",
"states",
".",
"length",
"==",
"1",
"?",
"states",
".",
"first",
":",
"states",
"end"
] | Customizes the definition of one or more states in the machine.
Configuration options:
* <tt>:value</tt> - The actual value to store when an object transitions
to the state. Default is the name (stringified).
* <tt>:cache</tt> - If a dynamic value (via a lambda block) is being used,
then setting this to true will cache the evaluated result
* <tt>:if</tt> - Determines whether an object's value matches the state
(e.g. :value => lambda {Time.now}, :if => lambda {|state| !state.nil?}).
By default, the configured value is matched.
* <tt>:human_name</tt> - The human-readable version of this state's name.
By default, this is either defined by the integration or stringifies the
name and converts underscores to spaces.
== Customizing the stored value
Whenever a state is automatically discovered in the state machine, its
default value is assumed to be the stringified version of the name. For
example,
class Vehicle
state_machine :initial => :parked do
event :ignite do
transition :parked => :idling
end
end
end
In the above state machine, there are two states automatically discovered:
:parked and :idling. These states, by default, will store their stringified
equivalents when an object moves into that state (e.g. "parked" / "idling").
For legacy systems or when tying state machines into existing frameworks,
it's oftentimes necessary to need to store a different value for a state
than the default. In order to continue taking advantage of an expressive
state machine and helper methods, every defined state can be re-configured
with a custom stored value. For example,
class Vehicle
state_machine :initial => :parked do
event :ignite do
transition :parked => :idling
end
state :idling, :value => 'IDLING'
state :parked, :value => 'PARKED
end
end
This is also useful if being used in association with a database and,
instead of storing the state name in a column, you want to store the
state's foreign key:
class VehicleState < ActiveRecord::Base
end
class Vehicle < ActiveRecord::Base
state_machine :attribute => :state_id, :initial => :parked do
event :ignite do
transition :parked => :idling
end
states.each do |state|
self.state(state.name, :value => lambda { VehicleState.find_by_name(state.name.to_s).id }, :cache => true)
end
end
end
In the above example, each known state is configured to store it's
associated database id in the +state_id+ attribute. Also, notice that a
lambda block is used to define the state's value. This is required in
situations (like testing) where the model is loaded without any existing
data (i.e. no VehicleState records available).
One caveat to the above example is to keep performance in mind. To avoid
constant db hits for looking up the VehicleState ids, the value is cached
by specifying the <tt>:cache</tt> option. Alternatively, a custom
caching strategy can be used like so:
class VehicleState < ActiveRecord::Base
cattr_accessor :cache_store
self.cache_store = ActiveSupport::Cache::MemoryStore.new
def self.find_by_name(name)
cache_store.fetch(name) { find(:first, :conditions => {:name => name}) }
end
end
=== Dynamic values
In addition to customizing states with other value types, lambda blocks
can also be specified to allow for a state's value to be determined
dynamically at runtime. For example,
class Vehicle
state_machine :purchased_at, :initial => :available do
event :purchase do
transition all => :purchased
end
event :restock do
transition all => :available
end
state :available, :value => nil
state :purchased, :if => lambda {|value| !value.nil?}, :value => lambda {Time.now}
end
end
In the above definition, the <tt>:purchased</tt> state is customized with
both a dynamic value *and* a value matcher.
When an object transitions to the purchased state, the value's lambda
block will be called. This will get the current time and store it in the
object's +purchased_at+ attribute.
*Note* that the custom matcher is very important here. Since there's no
way for the state machine to figure out an object's state when it's set to
a runtime value, it must be explicitly defined. If the <tt>:if</tt> option
were not configured for the state, then an ArgumentError exception would
be raised at runtime, indicating that the state machine could not figure
out what the current state of the object was.
== Behaviors
Behaviors define a series of methods to mixin with objects when the current
state matches the given one(s). This allows instance methods to behave
a specific way depending on what the value of the object's state is.
For example,
class Vehicle
attr_accessor :driver
attr_accessor :passenger
state_machine :initial => :parked do
event :ignite do
transition :parked => :idling
end
state :parked do
def speed
0
end
def rotate_driver
driver = self.driver
self.driver = passenger
self.passenger = driver
true
end
end
state :idling, :first_gear do
def speed
20
end
def rotate_driver
self.state = 'parked'
rotate_driver
end
end
other_states :backing_up
end
end
In the above example, there are two dynamic behaviors defined for the
class:
* +speed+
* +rotate_driver+
Each of these behaviors are instance methods on the Vehicle class. However,
which method actually gets invoked is based on the current state of the
object. Using the above class as the example:
vehicle = Vehicle.new
vehicle.driver = 'John'
vehicle.passenger = 'Jane'
# Behaviors in the "parked" state
vehicle.state # => "parked"
vehicle.speed # => 0
vehicle.rotate_driver # => true
vehicle.driver # => "Jane"
vehicle.passenger # => "John"
vehicle.ignite # => true
# Behaviors in the "idling" state
vehicle.state # => "idling"
vehicle.speed # => 20
vehicle.rotate_driver # => true
vehicle.driver # => "John"
vehicle.passenger # => "Jane"
As can be seen, both the +speed+ and +rotate_driver+ instance method
implementations changed how they behave based on what the current state
of the vehicle was.
=== Invalid behaviors
If a specific behavior has not been defined for a state, then a
NoMethodError exception will be raised, indicating that that method would
not normally exist for an object with that state.
Using the example from before:
vehicle = Vehicle.new
vehicle.state = 'backing_up'
vehicle.speed # => NoMethodError: undefined method 'speed' for #<Vehicle:0xb7d296ac> in state "backing_up"
=== Using matchers
The +all+ / +any+ matchers can be used to easily define behaviors for a
group of states. Note, however, that you cannot use these matchers to
set configurations for states. Behaviors using these matchers can be
defined at any point in the state machine and will always get applied to
the proper states.
For example:
state_machine :initial => :parked do
...
state all - [:parked, :idling, :stalled] do
validates_presence_of :speed
def speed
gear * 10
end
end
end
== State-aware class methods
In addition to defining scopes for instance methods that are state-aware,
the same can be done for certain types of class methods.
Some libraries have support for class-level methods that only run certain
behaviors based on a conditions hash passed in. For example:
class Vehicle < ActiveRecord::Base
state_machine do
...
state :first_gear, :second_gear, :third_gear do
validates_presence_of :speed
validates_inclusion_of :speed, :in => 0..25, :if => :in_school_zone?
end
end
end
In the above ActiveRecord model, two validations have been defined which
will *only* run when the Vehicle object is in one of the three states:
+first_gear+, +second_gear+, or +third_gear. Notice, also, that if/unless
conditions can continue to be used.
This functionality is not library-specific and can work for any class-level
method that is defined like so:
def validates_presence_of(attribute, options = {})
...
end
The minimum requirement is that the last argument in the method be an
options hash which contains at least <tt>:if</tt> condition support. | [
"Customizes",
"the",
"definition",
"of",
"one",
"or",
"more",
"states",
"in",
"the",
"machine",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1005-L1035 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.read | def read(object, attribute, ivar = false)
attribute = self.attribute(attribute)
if ivar
object.instance_variable_defined?("@#{attribute}") ? object.instance_variable_get("@#{attribute}") : nil
else
object.send(attribute)
end
end | ruby | def read(object, attribute, ivar = false)
attribute = self.attribute(attribute)
if ivar
object.instance_variable_defined?("@#{attribute}") ? object.instance_variable_get("@#{attribute}") : nil
else
object.send(attribute)
end
end | [
"def",
"read",
"(",
"object",
",",
"attribute",
",",
"ivar",
"=",
"false",
")",
"attribute",
"=",
"self",
".",
"attribute",
"(",
"attribute",
")",
"if",
"ivar",
"object",
".",
"instance_variable_defined?",
"(",
"\"@#{attribute}\"",
")",
"?",
"object",
".",
"instance_variable_get",
"(",
"\"@#{attribute}\"",
")",
":",
"nil",
"else",
"object",
".",
"send",
"(",
"attribute",
")",
"end",
"end"
] | Gets the current value stored in the given object's attribute.
For example,
class Vehicle
state_machine :initial => :parked do
...
end
end
vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
Vehicle.state_machine.read(vehicle, :state) # => "parked" # Equivalent to vehicle.state
Vehicle.state_machine.read(vehicle, :event) # => nil # Equivalent to vehicle.state_event | [
"Gets",
"the",
"current",
"value",
"stored",
"in",
"the",
"given",
"object",
"s",
"attribute",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1052-L1059 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.write | def write(object, attribute, value, ivar = false)
attribute = self.attribute(attribute)
ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value)
end | ruby | def write(object, attribute, value, ivar = false)
attribute = self.attribute(attribute)
ivar ? object.instance_variable_set("@#{attribute}", value) : object.send("#{attribute}=", value)
end | [
"def",
"write",
"(",
"object",
",",
"attribute",
",",
"value",
",",
"ivar",
"=",
"false",
")",
"attribute",
"=",
"self",
".",
"attribute",
"(",
"attribute",
")",
"ivar",
"?",
"object",
".",
"instance_variable_set",
"(",
"\"@#{attribute}\"",
",",
"value",
")",
":",
"object",
".",
"send",
"(",
"\"#{attribute}=\"",
",",
"value",
")",
"end"
] | Sets a new value in the given object's attribute.
For example,
class Vehicle
state_machine :initial => :parked do
...
end
end
vehicle = Vehicle.new # => #<Vehicle:0xb7d94ab0 @state="parked">
Vehicle.state_machine.write(vehicle, :state, 'idling') # => Equivalent to vehicle.state = 'idling'
Vehicle.state_machine.write(vehicle, :event, 'park') # => Equivalent to vehicle.state_event = 'park'
vehicle.state # => "idling"
vehicle.event # => "park" | [
"Sets",
"a",
"new",
"value",
"in",
"the",
"given",
"object",
"s",
"attribute",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1076-L1079 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.event | def event(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:human_name)
# Store the context so that it can be used for / matched against any event
# that gets added
@events.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any events referenced in the matcher. When matchers are used,
# events are not allowed to be configured.
raise ArgumentError, "Cannot configure events when using matchers (using #{options.inspect})" if options.any?
events = add_events(names.first.values)
else
events = add_events(names)
# Update the configuration for the event(s)
events.each do |event|
event.human_name = options[:human_name] if options.include?(:human_name)
# Add any states that may have been referenced within the event
add_states(event.known_states)
end
end
events.length == 1 ? events.first : events
end | ruby | def event(*names, &block)
options = names.last.is_a?(Hash) ? names.pop : {}
options.assert_valid_keys(:human_name)
# Store the context so that it can be used for / matched against any event
# that gets added
@events.context(names, &block) if block_given?
if names.first.is_a?(Matcher)
# Add any events referenced in the matcher. When matchers are used,
# events are not allowed to be configured.
raise ArgumentError, "Cannot configure events when using matchers (using #{options.inspect})" if options.any?
events = add_events(names.first.values)
else
events = add_events(names)
# Update the configuration for the event(s)
events.each do |event|
event.human_name = options[:human_name] if options.include?(:human_name)
# Add any states that may have been referenced within the event
add_states(event.known_states)
end
end
events.length == 1 ? events.first : events
end | [
"def",
"event",
"(",
"*",
"names",
",",
"&",
"block",
")",
"options",
"=",
"names",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"?",
"names",
".",
"pop",
":",
"{",
"}",
"options",
".",
"assert_valid_keys",
"(",
":human_name",
")",
"# Store the context so that it can be used for / matched against any event",
"# that gets added",
"@events",
".",
"context",
"(",
"names",
",",
"block",
")",
"if",
"block_given?",
"if",
"names",
".",
"first",
".",
"is_a?",
"(",
"Matcher",
")",
"# Add any events referenced in the matcher. When matchers are used,",
"# events are not allowed to be configured.",
"raise",
"ArgumentError",
",",
"\"Cannot configure events when using matchers (using #{options.inspect})\"",
"if",
"options",
".",
"any?",
"events",
"=",
"add_events",
"(",
"names",
".",
"first",
".",
"values",
")",
"else",
"events",
"=",
"add_events",
"(",
"names",
")",
"# Update the configuration for the event(s)",
"events",
".",
"each",
"do",
"|",
"event",
"|",
"event",
".",
"human_name",
"=",
"options",
"[",
":human_name",
"]",
"if",
"options",
".",
"include?",
"(",
":human_name",
")",
"# Add any states that may have been referenced within the event",
"add_states",
"(",
"event",
".",
"known_states",
")",
"end",
"end",
"events",
".",
"length",
"==",
"1",
"?",
"events",
".",
"first",
":",
"events",
"end"
] | Defines one or more events for the machine and the transitions that can
be performed when those events are run.
This method is also aliased as +on+ for improved compatibility with
using a domain-specific language.
Configuration options:
* <tt>:human_name</tt> - The human-readable version of this event's name.
By default, this is either defined by the integration or stringifies the
name and converts underscores to spaces.
== Instance methods
The following instance methods are generated when a new event is defined
(the "park" event is used as an example):
* <tt>park(..., run_action = true)</tt> - Fires the "park" event,
transitioning from the current state to the next valid state. If the
last argument is a boolean, it will control whether the machine's action
gets run.
* <tt>park!(..., run_action = true)</tt> - Fires the "park" event,
transitioning from the current state to the next valid state. If the
transition fails, then a StateMachines::InvalidTransition error will be
raised. If the last argument is a boolean, it will control whether the
machine's action gets run.
* <tt>can_park?(requirements = {})</tt> - Checks whether the "park" event
can be fired given the current state of the object. This will *not* run
validations or callbacks in ORM integrations. It will only determine if
the state machine defines a valid transition for the event. To check
whether an event can fire *and* passes validations, use event attributes
(e.g. state_event) as described in the "Events" documentation of each
ORM integration.
* <tt>park_transition(requirements = {})</tt> - Gets the next transition
that would be performed if the "park" event were to be fired now on the
object or nil if no transitions can be performed. Like <tt>can_park?</tt>
this will also *not* run validations or callbacks. It will only
determine if the state machine defines a valid transition for the event.
With a namespace of "car", the above names map to the following methods:
* <tt>can_park_car?</tt>
* <tt>park_car_transition</tt>
* <tt>park_car</tt>
* <tt>park_car!</tt>
The <tt>can_park?</tt> and <tt>park_transition</tt> helpers both take an
optional set of requirements for determining what transitions are available
for the current object. These requirements include:
* <tt>:from</tt> - One or more states to transition from. If none are
specified, then this will be the object's current state.
* <tt>:to</tt> - One or more states to transition to. If none are
specified, then this will match any to state.
* <tt>:guard</tt> - Whether to guard transitions with the if/unless
conditionals defined for each one. Default is true.
== Defining transitions
+event+ requires a block which allows you to define the possible
transitions that can happen as a result of that event. For example,
event :park, :stop do
transition :idling => :parked
end
event :first_gear do
transition :parked => :first_gear, :if => :seatbelt_on?
transition :parked => same # Allow to loopback if seatbelt is off
end
See StateMachines::Event#transition for more information on
the possible options that can be passed in.
*Note* that this block is executed within the context of the actual event
object. As a result, you will not be able to reference any class methods
on the model without referencing the class itself. For example,
class Vehicle
def self.safe_states
[:parked, :idling, :stalled]
end
state_machine do
event :park do
transition Vehicle.safe_states => :parked
end
end
end
== Overriding the event method
By default, this will define an instance method (with the same name as the
event) that will fire the next possible transition for that. Although the
+before_transition+, +after_transition+, and +around_transition+ hooks
allow you to define behavior that gets executed as a result of the event's
transition, you can also override the event method in order to have a
little more fine-grained control.
For example:
class Vehicle
state_machine do
event :park do
...
end
end
def park(*)
take_deep_breath # Executes before the transition (and before_transition hooks) even if no transition is possible
if result = super # Runs the transition and all before/after/around hooks
applaud # Executes after the transition (and after_transition hooks)
end
result
end
end
There are a few important things to note here. First, the method
signature is defined with an unlimited argument list in order to allow
callers to continue passing arguments that are expected by state_machine.
For example, it will still allow calls to +park+ with a single parameter
for skipping the configured action.
Second, the overridden event method must call +super+ in order to run the
logic for running the next possible transition. In order to remain
consistent with other events, the result of +super+ is returned.
Third, any behavior defined in this method will *not* get executed if
you're taking advantage of attribute-based event transitions. For example:
vehicle = Vehicle.new
vehicle.state_event = 'park'
vehicle.save
In this case, the +park+ event will run the before/after/around transition
hooks and transition the state, but the behavior defined in the overriden
+park+ method will *not* be executed.
== Defining additional arguments
Additional arguments can be passed into events and accessed by transition
hooks like so:
class Vehicle
state_machine do
after_transition :on => :park do |vehicle, transition|
kind = *transition.args # :parallel
...
end
after_transition :on => :park, :do => :take_deep_breath
event :park do
...
end
def take_deep_breath(transition)
kind = *transition.args # :parallel
...
end
end
end
vehicle = Vehicle.new
vehicle.park(:parallel)
*Remember* that if the last argument is a boolean, it will be used as the
+run_action+ parameter to the event action. Using the +park+ action
example from above, you can might call it like so:
vehicle.park # => Uses default args and runs machine action
vehicle.park(:parallel) # => Specifies the +kind+ argument and runs the machine action
vehicle.park(:parallel, false) # => Specifies the +kind+ argument and *skips* the machine action
If you decide to override the +park+ event method *and* define additional
arguments, you can do so as shown below:
class Vehicle
state_machine do
event :park do
...
end
end
def park(kind = :parallel, *args)
take_deep_breath if kind == :parallel
super
end
end
Note that +super+ is called instead of <tt>super(*args)</tt>. This allow
the entire arguments list to be accessed by transition callbacks through
StateMachines::Transition#args.
=== Using matchers
The +all+ / +any+ matchers can be used to easily execute blocks for a
group of events. Note, however, that you cannot use these matchers to
set configurations for events. Blocks using these matchers can be
defined at any point in the state machine and will always get applied to
the proper events.
For example:
state_machine :initial => :parked do
...
event all - [:crash] do
transition :stalled => :parked
end
end
== Example
class Vehicle
state_machine do
# The park, stop, and halt events will all share the given transitions
event :park, :stop, :halt do
transition [:idling, :backing_up] => :parked
end
event :stop do
transition :first_gear => :idling
end
event :ignite do
transition :parked => :idling
transition :idling => same # Allow ignite while still idling
end
end
end | [
"Defines",
"one",
"or",
"more",
"events",
"for",
"the",
"machine",
"and",
"the",
"transitions",
"that",
"can",
"be",
"performed",
"when",
"those",
"events",
"are",
"run",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1307-L1333 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.transition | def transition(options)
raise ArgumentError, 'Must specify :on event' unless options[:on]
branches = []
options = options.dup
event(*Array(options.delete(:on))) { branches << transition(options) }
branches.length == 1 ? branches.first : branches
end | ruby | def transition(options)
raise ArgumentError, 'Must specify :on event' unless options[:on]
branches = []
options = options.dup
event(*Array(options.delete(:on))) { branches << transition(options) }
branches.length == 1 ? branches.first : branches
end | [
"def",
"transition",
"(",
"options",
")",
"raise",
"ArgumentError",
",",
"'Must specify :on event'",
"unless",
"options",
"[",
":on",
"]",
"branches",
"=",
"[",
"]",
"options",
"=",
"options",
".",
"dup",
"event",
"(",
"Array",
"(",
"options",
".",
"delete",
"(",
":on",
")",
")",
")",
"{",
"branches",
"<<",
"transition",
"(",
"options",
")",
"}",
"branches",
".",
"length",
"==",
"1",
"?",
"branches",
".",
"first",
":",
"branches",
"end"
] | Creates a new transition that determines what to change the current state
to when an event fires.
== Defining transitions
The options for a new transition uses the Hash syntax to map beginning
states to ending states. For example,
transition :parked => :idling, :idling => :first_gear, :on => :ignite
In this case, when the +ignite+ event is fired, this transition will cause
the state to be +idling+ if it's current state is +parked+ or +first_gear+
if it's current state is +idling+.
To help define these implicit transitions, a set of helpers are available
for slightly more complex matching:
* <tt>all</tt> - Matches every state in the machine
* <tt>all - [:parked, :idling, ...]</tt> - Matches every state except those specified
* <tt>any</tt> - An alias for +all+ (matches every state in the machine)
* <tt>same</tt> - Matches the same state being transitioned from
See StateMachines::MatcherHelpers for more information.
Examples:
transition all => nil, :on => :ignite # Transitions to nil regardless of the current state
transition all => :idling, :on => :ignite # Transitions to :idling regardless of the current state
transition all - [:idling, :first_gear] => :idling, :on => :ignite # Transitions every state but :idling and :first_gear to :idling
transition nil => :idling, :on => :ignite # Transitions to :idling from the nil state
transition :parked => :idling, :on => :ignite # Transitions to :idling if :parked
transition [:parked, :stalled] => :idling, :on => :ignite # Transitions to :idling if :parked or :stalled
transition :parked => same, :on => :park # Loops :parked back to :parked
transition [:parked, :stalled] => same, :on => [:park, :stall] # Loops either :parked or :stalled back to the same state on the park and stall events
transition all - :parked => same, :on => :noop # Loops every state but :parked back to the same state
# Transitions to :idling if :parked, :first_gear if :idling, or :second_gear if :first_gear
transition :parked => :idling, :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up
== Verbose transitions
Transitions can also be defined use an explicit set of configuration
options:
* <tt>:from</tt> - A state or array of states that can be transitioned from.
If not specified, then the transition can occur for *any* state.
* <tt>:to</tt> - The state that's being transitioned to. If not specified,
then the transition will simply loop back (i.e. the state will not change).
* <tt>:except_from</tt> - A state or array of states that *cannot* be
transitioned from.
These options must be used when defining transitions within the context
of a state.
Examples:
transition :to => nil, :on => :park
transition :to => :idling, :on => :ignite
transition :except_from => [:idling, :first_gear], :to => :idling, :on => :ignite
transition :from => nil, :to => :idling, :on => :ignite
transition :from => [:parked, :stalled], :to => :idling, :on => :ignite
== Conditions
In addition to the state requirements for each transition, a condition
can also be defined to help determine whether that transition is
available. These options will work on both the normal and verbose syntax.
Configuration options:
* <tt>:if</tt> - A method, proc or string to call to determine if the
transition should occur (e.g. :if => :moving?, or :if => lambda {|vehicle| vehicle.speed > 60}).
The condition should return or evaluate to true or false.
* <tt>:unless</tt> - A method, proc or string to call to determine if the
transition should not occur (e.g. :unless => :stopped?, or :unless => lambda {|vehicle| vehicle.speed <= 60}).
The condition should return or evaluate to true or false.
Examples:
transition :parked => :idling, :on => :ignite, :if => :moving?
transition :parked => :idling, :on => :ignite, :unless => :stopped?
transition :idling => :first_gear, :first_gear => :second_gear, :on => :shift_up, :if => :seatbelt_on?
transition :from => :parked, :to => :idling, :on => ignite, :if => :moving?
transition :from => :parked, :to => :idling, :on => ignite, :unless => :stopped?
== Order of operations
Transitions are evaluated in the order in which they're defined. As a
result, if more than one transition applies to a given object, then the
first transition that matches will be performed. | [
"Creates",
"a",
"new",
"transition",
"that",
"determines",
"what",
"to",
"change",
"the",
"current",
"state",
"to",
"when",
"an",
"event",
"fires",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1426-L1434 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.generate_message | def generate_message(name, values = [])
message = (@messages[name] || self.class.default_messages[name])
# Check whether there are actually any values to interpolate to avoid
# any warnings
if message.scan(/%./).any? { |match| match != '%%' }
message % values.map { |value| value.last }
else
message
end
end | ruby | def generate_message(name, values = [])
message = (@messages[name] || self.class.default_messages[name])
# Check whether there are actually any values to interpolate to avoid
# any warnings
if message.scan(/%./).any? { |match| match != '%%' }
message % values.map { |value| value.last }
else
message
end
end | [
"def",
"generate_message",
"(",
"name",
",",
"values",
"=",
"[",
"]",
")",
"message",
"=",
"(",
"@messages",
"[",
"name",
"]",
"||",
"self",
".",
"class",
".",
"default_messages",
"[",
"name",
"]",
")",
"# Check whether there are actually any values to interpolate to avoid",
"# any warnings",
"if",
"message",
".",
"scan",
"(",
"/",
"/",
")",
".",
"any?",
"{",
"|",
"match",
"|",
"match",
"!=",
"'%%'",
"}",
"message",
"%",
"values",
".",
"map",
"{",
"|",
"value",
"|",
"value",
".",
"last",
"}",
"else",
"message",
"end",
"end"
] | Generates the message to use when invalidating the given object after
failing to transition on a specific event | [
"Generates",
"the",
"message",
"to",
"use",
"when",
"invalidating",
"the",
"given",
"object",
"after",
"failing",
"to",
"transition",
"on",
"a",
"specific",
"event"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1849-L1859 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.action_hook? | def action_hook?(self_only = false)
@action_hook_defined || !self_only && owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self && machine.action_hook?(true) }
end | ruby | def action_hook?(self_only = false)
@action_hook_defined || !self_only && owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self && machine.action_hook?(true) }
end | [
"def",
"action_hook?",
"(",
"self_only",
"=",
"false",
")",
"@action_hook_defined",
"||",
"!",
"self_only",
"&&",
"owner_class",
".",
"state_machines",
".",
"any?",
"{",
"|",
"name",
",",
"machine",
"|",
"machine",
".",
"action",
"==",
"action",
"&&",
"machine",
"!=",
"self",
"&&",
"machine",
".",
"action_hook?",
"(",
"true",
")",
"}",
"end"
] | Determines whether an action hook was defined for firing attribute-based
event transitions when the configured action gets called. | [
"Determines",
"whether",
"an",
"action",
"hook",
"was",
"defined",
"for",
"firing",
"attribute",
"-",
"based",
"event",
"transitions",
"when",
"the",
"configured",
"action",
"gets",
"called",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1881-L1883 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.sibling_machines | def sibling_machines
owner_class.state_machines.inject([]) do |machines, (name, machine)|
if machine.attribute == attribute && machine != self
machines << (owner_class.state_machine(name) {})
end
machines
end
end | ruby | def sibling_machines
owner_class.state_machines.inject([]) do |machines, (name, machine)|
if machine.attribute == attribute && machine != self
machines << (owner_class.state_machine(name) {})
end
machines
end
end | [
"def",
"sibling_machines",
"owner_class",
".",
"state_machines",
".",
"inject",
"(",
"[",
"]",
")",
"do",
"|",
"machines",
",",
"(",
"name",
",",
"machine",
")",
"|",
"if",
"machine",
".",
"attribute",
"==",
"attribute",
"&&",
"machine",
"!=",
"self",
"machines",
"<<",
"(",
"owner_class",
".",
"state_machine",
"(",
"name",
")",
"{",
"}",
")",
"end",
"machines",
"end",
"end"
] | Looks up other machines that have been defined in the owner class and
are targeting the same attribute as this machine. When accessing
sibling machines, they will be automatically copied for the current
class if they haven't been already. This ensures that any configuration
changes made to the sibling machines only affect this class and not any
base class that may have originally defined the machine. | [
"Looks",
"up",
"other",
"machines",
"that",
"have",
"been",
"defined",
"in",
"the",
"owner",
"class",
"and",
"are",
"targeting",
"the",
"same",
"attribute",
"as",
"this",
"machine",
".",
"When",
"accessing",
"sibling",
"machines",
"they",
"will",
"be",
"automatically",
"copied",
"for",
"the",
"current",
"class",
"if",
"they",
"haven",
"t",
"been",
"already",
".",
"This",
"ensures",
"that",
"any",
"configuration",
"changes",
"made",
"to",
"the",
"sibling",
"machines",
"only",
"affect",
"this",
"class",
"and",
"not",
"any",
"base",
"class",
"that",
"may",
"have",
"originally",
"defined",
"the",
"machine",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1896-L1903 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.initialize_state? | def initialize_state?(object)
value = read(object, :state)
(value.nil? || value.respond_to?(:empty?) && value.empty?) && !states[value, :value]
end | ruby | def initialize_state?(object)
value = read(object, :state)
(value.nil? || value.respond_to?(:empty?) && value.empty?) && !states[value, :value]
end | [
"def",
"initialize_state?",
"(",
"object",
")",
"value",
"=",
"read",
"(",
"object",
",",
":state",
")",
"(",
"value",
".",
"nil?",
"||",
"value",
".",
"respond_to?",
"(",
":empty?",
")",
"&&",
"value",
".",
"empty?",
")",
"&&",
"!",
"states",
"[",
"value",
",",
":value",
"]",
"end"
] | Determines if the machine's attribute needs to be initialized. This
will only be true if the machine's attribute is blank. | [
"Determines",
"if",
"the",
"machine",
"s",
"attribute",
"needs",
"to",
"be",
"initialized",
".",
"This",
"will",
"only",
"be",
"true",
"if",
"the",
"machine",
"s",
"attribute",
"is",
"blank",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1907-L1910 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.define_path_helpers | def define_path_helpers
# Gets the paths of transitions available to the current object
define_helper(:instance, attribute(:paths)) do |machine, object, *args|
machine.paths_for(object, *args)
end
end | ruby | def define_path_helpers
# Gets the paths of transitions available to the current object
define_helper(:instance, attribute(:paths)) do |machine, object, *args|
machine.paths_for(object, *args)
end
end | [
"def",
"define_path_helpers",
"# Gets the paths of transitions available to the current object",
"define_helper",
"(",
":instance",
",",
"attribute",
"(",
":paths",
")",
")",
"do",
"|",
"machine",
",",
"object",
",",
"*",
"args",
"|",
"machine",
".",
"paths_for",
"(",
"object",
",",
"args",
")",
"end",
"end"
] | Adds helper methods for getting information about this state machine's
available transition paths | [
"Adds",
"helper",
"methods",
"for",
"getting",
"information",
"about",
"this",
"state",
"machine",
"s",
"available",
"transition",
"paths"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L1997-L2002 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.define_action_helpers? | def define_action_helpers?
action && !owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self }
end | ruby | def define_action_helpers?
action && !owner_class.state_machines.any? { |name, machine| machine.action == action && machine != self }
end | [
"def",
"define_action_helpers?",
"action",
"&&",
"!",
"owner_class",
".",
"state_machines",
".",
"any?",
"{",
"|",
"name",
",",
"machine",
"|",
"machine",
".",
"action",
"==",
"action",
"&&",
"machine",
"!=",
"self",
"}",
"end"
] | Determines whether action helpers should be defined for this machine.
This is only true if there is an action configured and no other machines
have process this same configuration already. | [
"Determines",
"whether",
"action",
"helpers",
"should",
"be",
"defined",
"for",
"this",
"machine",
".",
"This",
"is",
"only",
"true",
"if",
"there",
"is",
"an",
"action",
"configured",
"and",
"no",
"other",
"machines",
"have",
"process",
"this",
"same",
"configuration",
"already",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2007-L2009 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.owner_class_ancestor_has_method? | def owner_class_ancestor_has_method?(scope, method)
return false unless owner_class_has_method?(scope, method)
superclasses = owner_class.ancestors.select { |ancestor| ancestor.is_a?(Class) }[1..-1]
if scope == :class
current = owner_class.singleton_class
superclass = superclasses.first
else
current = owner_class
superclass = owner_class.superclass
end
# Generate the list of modules that *only* occur in the owner class, but
# were included *prior* to the helper modules, in addition to the
# superclasses
ancestors = current.ancestors - superclass.ancestors + superclasses
ancestors = ancestors[ancestors.index(@helper_modules[scope])..-1].reverse
# Search for for the first ancestor that defined this method
ancestors.detect do |ancestor|
ancestor = ancestor.singleton_class if scope == :class && ancestor.is_a?(Class)
ancestor.method_defined?(method) || ancestor.private_method_defined?(method)
end
end | ruby | def owner_class_ancestor_has_method?(scope, method)
return false unless owner_class_has_method?(scope, method)
superclasses = owner_class.ancestors.select { |ancestor| ancestor.is_a?(Class) }[1..-1]
if scope == :class
current = owner_class.singleton_class
superclass = superclasses.first
else
current = owner_class
superclass = owner_class.superclass
end
# Generate the list of modules that *only* occur in the owner class, but
# were included *prior* to the helper modules, in addition to the
# superclasses
ancestors = current.ancestors - superclass.ancestors + superclasses
ancestors = ancestors[ancestors.index(@helper_modules[scope])..-1].reverse
# Search for for the first ancestor that defined this method
ancestors.detect do |ancestor|
ancestor = ancestor.singleton_class if scope == :class && ancestor.is_a?(Class)
ancestor.method_defined?(method) || ancestor.private_method_defined?(method)
end
end | [
"def",
"owner_class_ancestor_has_method?",
"(",
"scope",
",",
"method",
")",
"return",
"false",
"unless",
"owner_class_has_method?",
"(",
"scope",
",",
"method",
")",
"superclasses",
"=",
"owner_class",
".",
"ancestors",
".",
"select",
"{",
"|",
"ancestor",
"|",
"ancestor",
".",
"is_a?",
"(",
"Class",
")",
"}",
"[",
"1",
"..",
"-",
"1",
"]",
"if",
"scope",
"==",
":class",
"current",
"=",
"owner_class",
".",
"singleton_class",
"superclass",
"=",
"superclasses",
".",
"first",
"else",
"current",
"=",
"owner_class",
"superclass",
"=",
"owner_class",
".",
"superclass",
"end",
"# Generate the list of modules that *only* occur in the owner class, but",
"# were included *prior* to the helper modules, in addition to the",
"# superclasses",
"ancestors",
"=",
"current",
".",
"ancestors",
"-",
"superclass",
".",
"ancestors",
"+",
"superclasses",
"ancestors",
"=",
"ancestors",
"[",
"ancestors",
".",
"index",
"(",
"@helper_modules",
"[",
"scope",
"]",
")",
"..",
"-",
"1",
"]",
".",
"reverse",
"# Search for for the first ancestor that defined this method",
"ancestors",
".",
"detect",
"do",
"|",
"ancestor",
"|",
"ancestor",
"=",
"ancestor",
".",
"singleton_class",
"if",
"scope",
"==",
":class",
"&&",
"ancestor",
".",
"is_a?",
"(",
"Class",
")",
"ancestor",
".",
"method_defined?",
"(",
"method",
")",
"||",
"ancestor",
".",
"private_method_defined?",
"(",
"method",
")",
"end",
"end"
] | Determines whether there's already a helper method defined within the
given scope. This is true only if one of the owner's ancestors defines
the method and is further along in the ancestor chain than this
machine's helper module. | [
"Determines",
"whether",
"there",
"s",
"already",
"a",
"helper",
"method",
"defined",
"within",
"the",
"given",
"scope",
".",
"This",
"is",
"true",
"only",
"if",
"one",
"of",
"the",
"owner",
"s",
"ancestors",
"defines",
"the",
"method",
"and",
"is",
"further",
"along",
"in",
"the",
"ancestor",
"chain",
"than",
"this",
"machine",
"s",
"helper",
"module",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2052-L2076 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.define_name_helpers | def define_name_helpers
# Gets the humanized version of a state
define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state|
machine.states.fetch(state).human_name(klass)
end
# Gets the humanized version of an event
define_helper(:class, "human_#{attribute(:event_name)}") do |machine, klass, event|
machine.events.fetch(event).human_name(klass)
end
# Gets the state name for the current value
define_helper(:instance, attribute(:name)) do |machine, object|
machine.states.match!(object).name
end
# Gets the human state name for the current value
define_helper(:instance, "human_#{attribute(:name)}") do |machine, object|
machine.states.match!(object).human_name(object.class)
end
end | ruby | def define_name_helpers
# Gets the humanized version of a state
define_helper(:class, "human_#{attribute(:name)}") do |machine, klass, state|
machine.states.fetch(state).human_name(klass)
end
# Gets the humanized version of an event
define_helper(:class, "human_#{attribute(:event_name)}") do |machine, klass, event|
machine.events.fetch(event).human_name(klass)
end
# Gets the state name for the current value
define_helper(:instance, attribute(:name)) do |machine, object|
machine.states.match!(object).name
end
# Gets the human state name for the current value
define_helper(:instance, "human_#{attribute(:name)}") do |machine, object|
machine.states.match!(object).human_name(object.class)
end
end | [
"def",
"define_name_helpers",
"# Gets the humanized version of a state",
"define_helper",
"(",
":class",
",",
"\"human_#{attribute(:name)}\"",
")",
"do",
"|",
"machine",
",",
"klass",
",",
"state",
"|",
"machine",
".",
"states",
".",
"fetch",
"(",
"state",
")",
".",
"human_name",
"(",
"klass",
")",
"end",
"# Gets the humanized version of an event",
"define_helper",
"(",
":class",
",",
"\"human_#{attribute(:event_name)}\"",
")",
"do",
"|",
"machine",
",",
"klass",
",",
"event",
"|",
"machine",
".",
"events",
".",
"fetch",
"(",
"event",
")",
".",
"human_name",
"(",
"klass",
")",
"end",
"# Gets the state name for the current value",
"define_helper",
"(",
":instance",
",",
"attribute",
"(",
":name",
")",
")",
"do",
"|",
"machine",
",",
"object",
"|",
"machine",
".",
"states",
".",
"match!",
"(",
"object",
")",
".",
"name",
"end",
"# Gets the human state name for the current value",
"define_helper",
"(",
":instance",
",",
"\"human_#{attribute(:name)}\"",
")",
"do",
"|",
"machine",
",",
"object",
"|",
"machine",
".",
"states",
".",
"match!",
"(",
"object",
")",
".",
"human_name",
"(",
"object",
".",
"class",
")",
"end",
"end"
] | Adds helper methods for accessing naming information about states and
events on the owner class | [
"Adds",
"helper",
"methods",
"for",
"accessing",
"naming",
"information",
"about",
"states",
"and",
"events",
"on",
"the",
"owner",
"class"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2085-L2105 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.run_scope | def run_scope(scope, machine, klass, states)
values = states.flatten.map { |state| machine.states.fetch(state).value }
scope.call(klass, values)
end | ruby | def run_scope(scope, machine, klass, states)
values = states.flatten.map { |state| machine.states.fetch(state).value }
scope.call(klass, values)
end | [
"def",
"run_scope",
"(",
"scope",
",",
"machine",
",",
"klass",
",",
"states",
")",
"values",
"=",
"states",
".",
"flatten",
".",
"map",
"{",
"|",
"state",
"|",
"machine",
".",
"states",
".",
"fetch",
"(",
"state",
")",
".",
"value",
"}",
"scope",
".",
"call",
"(",
"klass",
",",
"values",
")",
"end"
] | Generates the results for the given scope based on one or more states to
filter by | [
"Generates",
"the",
"results",
"for",
"the",
"given",
"scope",
"based",
"on",
"one",
"or",
"more",
"states",
"to",
"filter",
"by"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2132-L2135 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.add_sibling_machine_configs | def add_sibling_machine_configs
# Add existing states
sibling_machines.each do |machine|
machine.states.each { |state| states << state unless states[state.name] }
end
end | ruby | def add_sibling_machine_configs
# Add existing states
sibling_machines.each do |machine|
machine.states.each { |state| states << state unless states[state.name] }
end
end | [
"def",
"add_sibling_machine_configs",
"# Add existing states",
"sibling_machines",
".",
"each",
"do",
"|",
"machine",
"|",
"machine",
".",
"states",
".",
"each",
"{",
"|",
"state",
"|",
"states",
"<<",
"state",
"unless",
"states",
"[",
"state",
".",
"name",
"]",
"}",
"end",
"end"
] | Updates this machine based on the configuration of other machines in the
owner class that share the same target attribute. | [
"Updates",
"this",
"machine",
"based",
"on",
"the",
"configuration",
"of",
"other",
"machines",
"in",
"the",
"owner",
"class",
"that",
"share",
"the",
"same",
"target",
"attribute",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2181-L2186 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.add_callback | def add_callback(type, options, &block)
callbacks[type == :around ? :before : type] << callback = Callback.new(type, options, &block)
add_states(callback.known_states)
callback
end | ruby | def add_callback(type, options, &block)
callbacks[type == :around ? :before : type] << callback = Callback.new(type, options, &block)
add_states(callback.known_states)
callback
end | [
"def",
"add_callback",
"(",
"type",
",",
"options",
",",
"&",
"block",
")",
"callbacks",
"[",
"type",
"==",
":around",
"?",
":before",
":",
"type",
"]",
"<<",
"callback",
"=",
"Callback",
".",
"new",
"(",
"type",
",",
"options",
",",
"block",
")",
"add_states",
"(",
"callback",
".",
"known_states",
")",
"callback",
"end"
] | Adds a new transition callback of the given type. | [
"Adds",
"a",
"new",
"transition",
"callback",
"of",
"the",
"given",
"type",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2189-L2193 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.add_states | def add_states(new_states)
new_states.map do |new_state|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if new_state && conflict = states.detect { |state| state.name && state.name.class != new_state.class }
raise ArgumentError, "#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent"
end
unless state = states[new_state]
states << state = State.new(self, new_state)
# Copy states over to sibling machines
sibling_machines.each { |machine| machine.states << state }
end
state
end
end | ruby | def add_states(new_states)
new_states.map do |new_state|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if new_state && conflict = states.detect { |state| state.name && state.name.class != new_state.class }
raise ArgumentError, "#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent"
end
unless state = states[new_state]
states << state = State.new(self, new_state)
# Copy states over to sibling machines
sibling_machines.each { |machine| machine.states << state }
end
state
end
end | [
"def",
"add_states",
"(",
"new_states",
")",
"new_states",
".",
"map",
"do",
"|",
"new_state",
"|",
"# Check for other states that use a different class type for their name.",
"# This typically prevents string / symbol misuse.",
"if",
"new_state",
"&&",
"conflict",
"=",
"states",
".",
"detect",
"{",
"|",
"state",
"|",
"state",
".",
"name",
"&&",
"state",
".",
"name",
".",
"class",
"!=",
"new_state",
".",
"class",
"}",
"raise",
"ArgumentError",
",",
"\"#{new_state.inspect} state defined as #{new_state.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all states must be consistent\"",
"end",
"unless",
"state",
"=",
"states",
"[",
"new_state",
"]",
"states",
"<<",
"state",
"=",
"State",
".",
"new",
"(",
"self",
",",
"new_state",
")",
"# Copy states over to sibling machines",
"sibling_machines",
".",
"each",
"{",
"|",
"machine",
"|",
"machine",
".",
"states",
"<<",
"state",
"}",
"end",
"state",
"end",
"end"
] | Tracks the given set of states in the list of all known states for
this machine | [
"Tracks",
"the",
"given",
"set",
"of",
"states",
"in",
"the",
"list",
"of",
"all",
"known",
"states",
"for",
"this",
"machine"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2197-L2214 | train |
state-machines/state_machines | lib/state_machines/machine.rb | StateMachines.Machine.add_events | def add_events(new_events)
new_events.map do |new_event|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if conflict = events.detect { |event| event.name.class != new_event.class }
raise ArgumentError, "#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent"
end
unless event = events[new_event]
events << event = Event.new(self, new_event)
end
event
end
end | ruby | def add_events(new_events)
new_events.map do |new_event|
# Check for other states that use a different class type for their name.
# This typically prevents string / symbol misuse.
if conflict = events.detect { |event| event.name.class != new_event.class }
raise ArgumentError, "#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent"
end
unless event = events[new_event]
events << event = Event.new(self, new_event)
end
event
end
end | [
"def",
"add_events",
"(",
"new_events",
")",
"new_events",
".",
"map",
"do",
"|",
"new_event",
"|",
"# Check for other states that use a different class type for their name.",
"# This typically prevents string / symbol misuse.",
"if",
"conflict",
"=",
"events",
".",
"detect",
"{",
"|",
"event",
"|",
"event",
".",
"name",
".",
"class",
"!=",
"new_event",
".",
"class",
"}",
"raise",
"ArgumentError",
",",
"\"#{new_event.inspect} event defined as #{new_event.class}, #{conflict.name.inspect} defined as #{conflict.name.class}; all events must be consistent\"",
"end",
"unless",
"event",
"=",
"events",
"[",
"new_event",
"]",
"events",
"<<",
"event",
"=",
"Event",
".",
"new",
"(",
"self",
",",
"new_event",
")",
"end",
"event",
"end",
"end"
] | Tracks the given set of events in the list of all known events for
this machine | [
"Tracks",
"the",
"given",
"set",
"of",
"events",
"in",
"the",
"list",
"of",
"all",
"known",
"events",
"for",
"this",
"machine"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine.rb#L2218-L2232 | train |
state-machines/state_machines | lib/state_machines/state_collection.rb | StateMachines.StateCollection.match | def match(object)
value = machine.read(object, :state)
self[value, :value] || detect { |state| state.matches?(value) }
end | ruby | def match(object)
value = machine.read(object, :state)
self[value, :value] || detect { |state| state.matches?(value) }
end | [
"def",
"match",
"(",
"object",
")",
"value",
"=",
"machine",
".",
"read",
"(",
"object",
",",
":state",
")",
"self",
"[",
"value",
",",
":value",
"]",
"||",
"detect",
"{",
"|",
"state",
"|",
"state",
".",
"matches?",
"(",
"value",
")",
"}",
"end"
] | Determines the current state of the given object as configured by this
state machine. This will attempt to find a known state that matches
the value of the attribute on the object.
== Examples
class Vehicle
state_machine :initial => :parked do
other_states :idling
end
end
states = Vehicle.state_machine.states
vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
states.match(vehicle) # => #<StateMachines::State name=:parked value="parked" initial=true>
vehicle.state = 'idling'
states.match(vehicle) # => #<StateMachines::State name=:idling value="idling" initial=true>
vehicle.state = 'invalid'
states.match(vehicle) # => nil | [
"Determines",
"the",
"current",
"state",
"of",
"the",
"given",
"object",
"as",
"configured",
"by",
"this",
"state",
"machine",
".",
"This",
"will",
"attempt",
"to",
"find",
"a",
"known",
"state",
"that",
"matches",
"the",
"value",
"of",
"the",
"attribute",
"on",
"the",
"object",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state_collection.rb#L53-L56 | train |
state-machines/state_machines | lib/state_machines/branch.rb | StateMachines.Branch.build_matcher | def build_matcher(options, whitelist_option, blacklist_option)
options.assert_exclusive_keys(whitelist_option, blacklist_option)
if options.include?(whitelist_option)
value = options[whitelist_option]
value.is_a?(Matcher) ? value : WhitelistMatcher.new(options[whitelist_option])
elsif options.include?(blacklist_option)
value = options[blacklist_option]
raise ArgumentError, ":#{blacklist_option} option cannot use matchers; use :#{whitelist_option} instead" if value.is_a?(Matcher)
BlacklistMatcher.new(value)
else
AllMatcher.instance
end
end | ruby | def build_matcher(options, whitelist_option, blacklist_option)
options.assert_exclusive_keys(whitelist_option, blacklist_option)
if options.include?(whitelist_option)
value = options[whitelist_option]
value.is_a?(Matcher) ? value : WhitelistMatcher.new(options[whitelist_option])
elsif options.include?(blacklist_option)
value = options[blacklist_option]
raise ArgumentError, ":#{blacklist_option} option cannot use matchers; use :#{whitelist_option} instead" if value.is_a?(Matcher)
BlacklistMatcher.new(value)
else
AllMatcher.instance
end
end | [
"def",
"build_matcher",
"(",
"options",
",",
"whitelist_option",
",",
"blacklist_option",
")",
"options",
".",
"assert_exclusive_keys",
"(",
"whitelist_option",
",",
"blacklist_option",
")",
"if",
"options",
".",
"include?",
"(",
"whitelist_option",
")",
"value",
"=",
"options",
"[",
"whitelist_option",
"]",
"value",
".",
"is_a?",
"(",
"Matcher",
")",
"?",
"value",
":",
"WhitelistMatcher",
".",
"new",
"(",
"options",
"[",
"whitelist_option",
"]",
")",
"elsif",
"options",
".",
"include?",
"(",
"blacklist_option",
")",
"value",
"=",
"options",
"[",
"blacklist_option",
"]",
"raise",
"ArgumentError",
",",
"\":#{blacklist_option} option cannot use matchers; use :#{whitelist_option} instead\"",
"if",
"value",
".",
"is_a?",
"(",
"Matcher",
")",
"BlacklistMatcher",
".",
"new",
"(",
"value",
")",
"else",
"AllMatcher",
".",
"instance",
"end",
"end"
] | Builds a matcher strategy to use for the given options. If neither a
whitelist nor a blacklist option is specified, then an AllMatcher is
built. | [
"Builds",
"a",
"matcher",
"strategy",
"to",
"use",
"for",
"the",
"given",
"options",
".",
"If",
"neither",
"a",
"whitelist",
"nor",
"a",
"blacklist",
"option",
"is",
"specified",
"then",
"an",
"AllMatcher",
"is",
"built",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/branch.rb#L130-L143 | train |
state-machines/state_machines | lib/state_machines/branch.rb | StateMachines.Branch.match_states | def match_states(query)
state_requirements.detect do |state_requirement|
[:from, :to].all? {|option| matches_requirement?(query, option, state_requirement[option])}
end
end | ruby | def match_states(query)
state_requirements.detect do |state_requirement|
[:from, :to].all? {|option| matches_requirement?(query, option, state_requirement[option])}
end
end | [
"def",
"match_states",
"(",
"query",
")",
"state_requirements",
".",
"detect",
"do",
"|",
"state_requirement",
"|",
"[",
":from",
",",
":to",
"]",
".",
"all?",
"{",
"|",
"option",
"|",
"matches_requirement?",
"(",
"query",
",",
"option",
",",
"state_requirement",
"[",
"option",
"]",
")",
"}",
"end",
"end"
] | Verifies that the state requirements match the given query. If a
matching requirement is found, then it is returned. | [
"Verifies",
"that",
"the",
"state",
"requirements",
"match",
"the",
"given",
"query",
".",
"If",
"a",
"matching",
"requirement",
"is",
"found",
"then",
"it",
"is",
"returned",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/branch.rb#L163-L167 | train |
state-machines/state_machines | lib/state_machines/branch.rb | StateMachines.Branch.matches_requirement? | def matches_requirement?(query, option, requirement)
!query.include?(option) || requirement.matches?(query[option], query)
end | ruby | def matches_requirement?(query, option, requirement)
!query.include?(option) || requirement.matches?(query[option], query)
end | [
"def",
"matches_requirement?",
"(",
"query",
",",
"option",
",",
"requirement",
")",
"!",
"query",
".",
"include?",
"(",
"option",
")",
"||",
"requirement",
".",
"matches?",
"(",
"query",
"[",
"option",
"]",
",",
"query",
")",
"end"
] | Verifies that an option in the given query matches the values required
for that option | [
"Verifies",
"that",
"an",
"option",
"in",
"the",
"given",
"query",
"matches",
"the",
"values",
"required",
"for",
"that",
"option"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/branch.rb#L171-L173 | train |
state-machines/state_machines | lib/state_machines/branch.rb | StateMachines.Branch.matches_conditions? | def matches_conditions?(object, query)
query[:guard] == false ||
Array(if_condition).all? {|condition| evaluate_method(object, condition)} &&
!Array(unless_condition).any? {|condition| evaluate_method(object, condition)}
end | ruby | def matches_conditions?(object, query)
query[:guard] == false ||
Array(if_condition).all? {|condition| evaluate_method(object, condition)} &&
!Array(unless_condition).any? {|condition| evaluate_method(object, condition)}
end | [
"def",
"matches_conditions?",
"(",
"object",
",",
"query",
")",
"query",
"[",
":guard",
"]",
"==",
"false",
"||",
"Array",
"(",
"if_condition",
")",
".",
"all?",
"{",
"|",
"condition",
"|",
"evaluate_method",
"(",
"object",
",",
"condition",
")",
"}",
"&&",
"!",
"Array",
"(",
"unless_condition",
")",
".",
"any?",
"{",
"|",
"condition",
"|",
"evaluate_method",
"(",
"object",
",",
"condition",
")",
"}",
"end"
] | Verifies that the conditionals for this branch evaluate to true for the
given object | [
"Verifies",
"that",
"the",
"conditionals",
"for",
"this",
"branch",
"evaluate",
"to",
"true",
"for",
"the",
"given",
"object"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/branch.rb#L177-L181 | train |
state-machines/state_machines | lib/state_machines/path_collection.rb | StateMachines.PathCollection.initial_paths | def initial_paths
machine.events.transitions_for(object, :from => from_name, :guard => @guard).map do |transition|
path = Path.new(object, machine, :target => to_name, :guard => @guard)
path << transition
path
end
end | ruby | def initial_paths
machine.events.transitions_for(object, :from => from_name, :guard => @guard).map do |transition|
path = Path.new(object, machine, :target => to_name, :guard => @guard)
path << transition
path
end
end | [
"def",
"initial_paths",
"machine",
".",
"events",
".",
"transitions_for",
"(",
"object",
",",
":from",
"=>",
"from_name",
",",
":guard",
"=>",
"@guard",
")",
".",
"map",
"do",
"|",
"transition",
"|",
"path",
"=",
"Path",
".",
"new",
"(",
"object",
",",
"machine",
",",
":target",
"=>",
"to_name",
",",
":guard",
"=>",
"@guard",
")",
"path",
"<<",
"transition",
"path",
"end",
"end"
] | Gets the initial set of paths to walk | [
"Gets",
"the",
"initial",
"set",
"of",
"paths",
"to",
"walk"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/path_collection.rb#L73-L79 | train |
state-machines/state_machines | lib/state_machines/path_collection.rb | StateMachines.PathCollection.walk | def walk(path)
self << path if path.complete?
path.walk {|next_path| walk(next_path)} unless to_name && path.complete? && !@deep
end | ruby | def walk(path)
self << path if path.complete?
path.walk {|next_path| walk(next_path)} unless to_name && path.complete? && !@deep
end | [
"def",
"walk",
"(",
"path",
")",
"self",
"<<",
"path",
"if",
"path",
".",
"complete?",
"path",
".",
"walk",
"{",
"|",
"next_path",
"|",
"walk",
"(",
"next_path",
")",
"}",
"unless",
"to_name",
"&&",
"path",
".",
"complete?",
"&&",
"!",
"@deep",
"end"
] | Walks down the given path. Each new path that matches the configured
requirements will be added to this collection. | [
"Walks",
"down",
"the",
"given",
"path",
".",
"Each",
"new",
"path",
"that",
"matches",
"the",
"configured",
"requirements",
"will",
"be",
"added",
"to",
"this",
"collection",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/path_collection.rb#L83-L86 | train |
state-machines/state_machines | lib/state_machines/path.rb | StateMachines.Path.recently_walked? | def recently_walked?(transition)
transitions = self
if @target && @target != to_name && target_transition = detect {|t| t.to_name == @target}
transitions = transitions[index(target_transition) + 1..-1]
end
transitions.include?(transition)
end | ruby | def recently_walked?(transition)
transitions = self
if @target && @target != to_name && target_transition = detect {|t| t.to_name == @target}
transitions = transitions[index(target_transition) + 1..-1]
end
transitions.include?(transition)
end | [
"def",
"recently_walked?",
"(",
"transition",
")",
"transitions",
"=",
"self",
"if",
"@target",
"&&",
"@target",
"!=",
"to_name",
"&&",
"target_transition",
"=",
"detect",
"{",
"|",
"t",
"|",
"t",
".",
"to_name",
"==",
"@target",
"}",
"transitions",
"=",
"transitions",
"[",
"index",
"(",
"target_transition",
")",
"+",
"1",
"..",
"-",
"1",
"]",
"end",
"transitions",
".",
"include?",
"(",
"transition",
")",
"end"
] | Determines whether the given transition has been recently walked down in
this path. If a target is configured for this path, then this will only
look at transitions walked down since the target was last reached. | [
"Determines",
"whether",
"the",
"given",
"transition",
"has",
"been",
"recently",
"walked",
"down",
"in",
"this",
"path",
".",
"If",
"a",
"target",
"is",
"configured",
"for",
"this",
"path",
"then",
"this",
"will",
"only",
"look",
"at",
"transitions",
"walked",
"down",
"since",
"the",
"target",
"was",
"last",
"reached",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/path.rb#L98-L104 | train |
state-machines/state_machines | lib/state_machines/path.rb | StateMachines.Path.transitions | def transitions
@transitions ||= empty? ? [] : machine.events.transitions_for(object, :from => to_name, :guard => @guard).select {|transition| can_walk_to?(transition)}
end | ruby | def transitions
@transitions ||= empty? ? [] : machine.events.transitions_for(object, :from => to_name, :guard => @guard).select {|transition| can_walk_to?(transition)}
end | [
"def",
"transitions",
"@transitions",
"||=",
"empty?",
"?",
"[",
"]",
":",
"machine",
".",
"events",
".",
"transitions_for",
"(",
"object",
",",
":from",
"=>",
"to_name",
",",
":guard",
"=>",
"@guard",
")",
".",
"select",
"{",
"|",
"transition",
"|",
"can_walk_to?",
"(",
"transition",
")",
"}",
"end"
] | Get the next set of transitions that can be walked to starting from the
end of this path | [
"Get",
"the",
"next",
"set",
"of",
"transitions",
"that",
"can",
"be",
"walked",
"to",
"starting",
"from",
"the",
"end",
"of",
"this",
"path"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/path.rb#L116-L118 | train |
state-machines/state_machines | lib/state_machines/state_context.rb | StateMachines.StateContext.method_missing | def method_missing(*args, &block)
# Get the configuration
if args.last.is_a?(Hash)
options = args.last
else
args << options = {}
end
# Get any existing condition that may need to be merged
if_condition = options.delete(:if)
unless_condition = options.delete(:unless)
# Provide scope access to configuration in case the block is evaluated
# within the object instance
proxy = self
proxy_condition = @condition
# Replace the configuration condition with the one configured for this
# proxy, merging together any existing conditions
options[:if] = lambda do |*condition_args|
# Block may be executed within the context of the actual object, so
# it'll either be the first argument or the executing context
object = condition_args.first || self
proxy.evaluate_method(object, proxy_condition) &&
Array(if_condition).all? {|condition| proxy.evaluate_method(object, condition)} &&
!Array(unless_condition).any? {|condition| proxy.evaluate_method(object, condition)}
end
# Evaluate the method on the owner class with the condition proxied
# through
machine.owner_class.send(*args, &block)
end | ruby | def method_missing(*args, &block)
# Get the configuration
if args.last.is_a?(Hash)
options = args.last
else
args << options = {}
end
# Get any existing condition that may need to be merged
if_condition = options.delete(:if)
unless_condition = options.delete(:unless)
# Provide scope access to configuration in case the block is evaluated
# within the object instance
proxy = self
proxy_condition = @condition
# Replace the configuration condition with the one configured for this
# proxy, merging together any existing conditions
options[:if] = lambda do |*condition_args|
# Block may be executed within the context of the actual object, so
# it'll either be the first argument or the executing context
object = condition_args.first || self
proxy.evaluate_method(object, proxy_condition) &&
Array(if_condition).all? {|condition| proxy.evaluate_method(object, condition)} &&
!Array(unless_condition).any? {|condition| proxy.evaluate_method(object, condition)}
end
# Evaluate the method on the owner class with the condition proxied
# through
machine.owner_class.send(*args, &block)
end | [
"def",
"method_missing",
"(",
"*",
"args",
",",
"&",
"block",
")",
"# Get the configuration",
"if",
"args",
".",
"last",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"args",
".",
"last",
"else",
"args",
"<<",
"options",
"=",
"{",
"}",
"end",
"# Get any existing condition that may need to be merged",
"if_condition",
"=",
"options",
".",
"delete",
"(",
":if",
")",
"unless_condition",
"=",
"options",
".",
"delete",
"(",
":unless",
")",
"# Provide scope access to configuration in case the block is evaluated",
"# within the object instance",
"proxy",
"=",
"self",
"proxy_condition",
"=",
"@condition",
"# Replace the configuration condition with the one configured for this",
"# proxy, merging together any existing conditions",
"options",
"[",
":if",
"]",
"=",
"lambda",
"do",
"|",
"*",
"condition_args",
"|",
"# Block may be executed within the context of the actual object, so",
"# it'll either be the first argument or the executing context",
"object",
"=",
"condition_args",
".",
"first",
"||",
"self",
"proxy",
".",
"evaluate_method",
"(",
"object",
",",
"proxy_condition",
")",
"&&",
"Array",
"(",
"if_condition",
")",
".",
"all?",
"{",
"|",
"condition",
"|",
"proxy",
".",
"evaluate_method",
"(",
"object",
",",
"condition",
")",
"}",
"&&",
"!",
"Array",
"(",
"unless_condition",
")",
".",
"any?",
"{",
"|",
"condition",
"|",
"proxy",
".",
"evaluate_method",
"(",
"object",
",",
"condition",
")",
"}",
"end",
"# Evaluate the method on the owner class with the condition proxied",
"# through",
"machine",
".",
"owner_class",
".",
"send",
"(",
"args",
",",
"block",
")",
"end"
] | Hooks in condition-merging to methods that don't exist in this module | [
"Hooks",
"in",
"condition",
"-",
"merging",
"to",
"methods",
"that",
"don",
"t",
"exist",
"in",
"this",
"module"
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/state_context.rb#L99-L131 | train |
state-machines/state_machines | lib/state_machines/event_collection.rb | StateMachines.EventCollection.valid_for | def valid_for(object, requirements = {})
match(requirements).select { |event| event.can_fire?(object, requirements) }
end | ruby | def valid_for(object, requirements = {})
match(requirements).select { |event| event.can_fire?(object, requirements) }
end | [
"def",
"valid_for",
"(",
"object",
",",
"requirements",
"=",
"{",
"}",
")",
"match",
"(",
"requirements",
")",
".",
"select",
"{",
"|",
"event",
"|",
"event",
".",
"can_fire?",
"(",
"object",
",",
"requirements",
")",
"}",
"end"
] | Gets the list of events that can be fired on the given object.
Valid requirement options:
* <tt>:from</tt> - One or more states being transitioned from. If none
are specified, then this will be the object's current state.
* <tt>:to</tt> - One or more states being transitioned to. If none are
specified, then this will match any to state.
* <tt>:on</tt> - One or more events that fire the transition. If none
are specified, then this will match any event.
* <tt>:guard</tt> - Whether to guard transitions with the if/unless
conditionals defined for each one. Default is true.
== Examples
class Vehicle
state_machine :initial => :parked do
event :park do
transition :idling => :parked
end
event :ignite do
transition :parked => :idling
end
end
end
events = Vehicle.state_machine(:state).events
vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
events.valid_for(vehicle) # => [#<StateMachines::Event name=:ignite transitions=[:parked => :idling]>]
vehicle.state = 'idling'
events.valid_for(vehicle) # => [#<StateMachines::Event name=:park transitions=[:idling => :parked]>] | [
"Gets",
"the",
"list",
"of",
"events",
"that",
"can",
"be",
"fired",
"on",
"the",
"given",
"object",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L41-L43 | train |
state-machines/state_machines | lib/state_machines/event_collection.rb | StateMachines.EventCollection.transitions_for | def transitions_for(object, requirements = {})
match(requirements).map { |event| event.transition_for(object, requirements) }.compact
end | ruby | def transitions_for(object, requirements = {})
match(requirements).map { |event| event.transition_for(object, requirements) }.compact
end | [
"def",
"transitions_for",
"(",
"object",
",",
"requirements",
"=",
"{",
"}",
")",
"match",
"(",
"requirements",
")",
".",
"map",
"{",
"|",
"event",
"|",
"event",
".",
"transition_for",
"(",
"object",
",",
"requirements",
")",
"}",
".",
"compact",
"end"
] | Gets the list of transitions that can be run on the given object.
Valid requirement options:
* <tt>:from</tt> - One or more states being transitioned from. If none
are specified, then this will be the object's current state.
* <tt>:to</tt> - One or more states being transitioned to. If none are
specified, then this will match any to state.
* <tt>:on</tt> - One or more events that fire the transition. If none
are specified, then this will match any event.
* <tt>:guard</tt> - Whether to guard transitions with the if/unless
conditionals defined for each one. Default is true.
== Examples
class Vehicle
state_machine :initial => :parked do
event :park do
transition :idling => :parked
end
event :ignite do
transition :parked => :idling
end
end
end
events = Vehicle.state_machine.events
vehicle = Vehicle.new # => #<Vehicle:0xb7c464b0 @state="parked">
events.transitions_for(vehicle) # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>]
vehicle.state = 'idling'
events.transitions_for(vehicle) # => [#<StateMachines::Transition attribute=:state event=:park from="idling" from_name=:idling to="parked" to_name=:parked>]
# Search for explicit transitions regardless of the current state
events.transitions_for(vehicle, :from => :parked) # => [#<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling>] | [
"Gets",
"the",
"list",
"of",
"transitions",
"that",
"can",
"be",
"run",
"on",
"the",
"given",
"object",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L81-L83 | train |
state-machines/state_machines | lib/state_machines/event_collection.rb | StateMachines.EventCollection.attribute_transition_for | def attribute_transition_for(object, invalidate = false)
return unless machine.action
# TODO, simplify
machine.read(object, :event_transition) || if event_name = machine.read(object, :event)
if event = self[event_name.to_sym, :name]
event.transition_for(object) || begin
# No valid transition: invalidate
machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate
false
end
else
# Event is unknown: invalidate
machine.invalidate(object, :event, :invalid) if invalidate
false
end
end
end | ruby | def attribute_transition_for(object, invalidate = false)
return unless machine.action
# TODO, simplify
machine.read(object, :event_transition) || if event_name = machine.read(object, :event)
if event = self[event_name.to_sym, :name]
event.transition_for(object) || begin
# No valid transition: invalidate
machine.invalidate(object, :event, :invalid_event, [[:state, machine.states.match!(object).human_name(object.class)]]) if invalidate
false
end
else
# Event is unknown: invalidate
machine.invalidate(object, :event, :invalid) if invalidate
false
end
end
end | [
"def",
"attribute_transition_for",
"(",
"object",
",",
"invalidate",
"=",
"false",
")",
"return",
"unless",
"machine",
".",
"action",
"# TODO, simplify",
"machine",
".",
"read",
"(",
"object",
",",
":event_transition",
")",
"||",
"if",
"event_name",
"=",
"machine",
".",
"read",
"(",
"object",
",",
":event",
")",
"if",
"event",
"=",
"self",
"[",
"event_name",
".",
"to_sym",
",",
":name",
"]",
"event",
".",
"transition_for",
"(",
"object",
")",
"||",
"begin",
"# No valid transition: invalidate",
"machine",
".",
"invalidate",
"(",
"object",
",",
":event",
",",
":invalid_event",
",",
"[",
"[",
":state",
",",
"machine",
".",
"states",
".",
"match!",
"(",
"object",
")",
".",
"human_name",
"(",
"object",
".",
"class",
")",
"]",
"]",
")",
"if",
"invalidate",
"false",
"end",
"else",
"# Event is unknown: invalidate",
"machine",
".",
"invalidate",
"(",
"object",
",",
":event",
",",
":invalid",
")",
"if",
"invalidate",
"false",
"end",
"end",
"end"
] | Gets the transition that should be performed for the event stored in the
given object's event attribute. This also takes an additional parameter
for automatically invalidating the object if the event or transition are
invalid. By default, this is turned off.
*Note* that if a transition has already been generated for the event, then
that transition will be used.
== Examples
class Vehicle < ActiveRecord::Base
state_machine :initial => :parked do
event :ignite do
transition :parked => :idling
end
end
end
vehicle = Vehicle.new # => #<Vehicle id: nil, state: "parked">
events = Vehicle.state_machine.events
vehicle.state_event = nil
events.attribute_transition_for(vehicle) # => nil # Event isn't defined
vehicle.state_event = 'invalid'
events.attribute_transition_for(vehicle) # => false # Event is invalid
vehicle.state_event = 'ignite'
events.attribute_transition_for(vehicle) # => #<StateMachines::Transition attribute=:state event=:ignite from="parked" from_name=:parked to="idling" to_name=:idling> | [
"Gets",
"the",
"transition",
"that",
"should",
"be",
"performed",
"for",
"the",
"event",
"stored",
"in",
"the",
"given",
"object",
"s",
"event",
"attribute",
".",
"This",
"also",
"takes",
"an",
"additional",
"parameter",
"for",
"automatically",
"invalidating",
"the",
"object",
"if",
"the",
"event",
"or",
"transition",
"are",
"invalid",
".",
"By",
"default",
"this",
"is",
"turned",
"off",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event_collection.rb#L114-L132 | train |
state-machines/state_machines | lib/state_machines/event.rb | StateMachines.Event.transition_for | def transition_for(object, requirements = {})
requirements.assert_valid_keys(:from, :to, :guard)
requirements[:from] = machine.states.match!(object).name unless custom_from_state = requirements.include?(:from)
branches.each do |branch|
if match = branch.match(object, requirements)
# Branch allows for the transition to occur
from = requirements[:from]
to = if match[:to].is_a?(LoopbackMatcher)
from
else
values = requirements.include?(:to) ? [requirements[:to]].flatten : [from] | machine.states.map { |state| state.name }
match[:to].filter(values).first
end
return Transition.new(object, machine, name, from, to, !custom_from_state)
end
end
# No transition matched
nil
end | ruby | def transition_for(object, requirements = {})
requirements.assert_valid_keys(:from, :to, :guard)
requirements[:from] = machine.states.match!(object).name unless custom_from_state = requirements.include?(:from)
branches.each do |branch|
if match = branch.match(object, requirements)
# Branch allows for the transition to occur
from = requirements[:from]
to = if match[:to].is_a?(LoopbackMatcher)
from
else
values = requirements.include?(:to) ? [requirements[:to]].flatten : [from] | machine.states.map { |state| state.name }
match[:to].filter(values).first
end
return Transition.new(object, machine, name, from, to, !custom_from_state)
end
end
# No transition matched
nil
end | [
"def",
"transition_for",
"(",
"object",
",",
"requirements",
"=",
"{",
"}",
")",
"requirements",
".",
"assert_valid_keys",
"(",
":from",
",",
":to",
",",
":guard",
")",
"requirements",
"[",
":from",
"]",
"=",
"machine",
".",
"states",
".",
"match!",
"(",
"object",
")",
".",
"name",
"unless",
"custom_from_state",
"=",
"requirements",
".",
"include?",
"(",
":from",
")",
"branches",
".",
"each",
"do",
"|",
"branch",
"|",
"if",
"match",
"=",
"branch",
".",
"match",
"(",
"object",
",",
"requirements",
")",
"# Branch allows for the transition to occur",
"from",
"=",
"requirements",
"[",
":from",
"]",
"to",
"=",
"if",
"match",
"[",
":to",
"]",
".",
"is_a?",
"(",
"LoopbackMatcher",
")",
"from",
"else",
"values",
"=",
"requirements",
".",
"include?",
"(",
":to",
")",
"?",
"[",
"requirements",
"[",
":to",
"]",
"]",
".",
"flatten",
":",
"[",
"from",
"]",
"|",
"machine",
".",
"states",
".",
"map",
"{",
"|",
"state",
"|",
"state",
".",
"name",
"}",
"match",
"[",
":to",
"]",
".",
"filter",
"(",
"values",
")",
".",
"first",
"end",
"return",
"Transition",
".",
"new",
"(",
"object",
",",
"machine",
",",
"name",
",",
"from",
",",
"to",
",",
"!",
"custom_from_state",
")",
"end",
"end",
"# No transition matched",
"nil",
"end"
] | Finds and builds the next transition that can be performed on the given
object. If no transitions can be made, then this will return nil.
Valid requirement options:
* <tt>:from</tt> - One or more states being transitioned from. If none
are specified, then this will be the object's current state.
* <tt>:to</tt> - One or more states being transitioned to. If none are
specified, then this will match any to state.
* <tt>:guard</tt> - Whether to guard transitions with the if/unless
conditionals defined for each one. Default is true. | [
"Finds",
"and",
"builds",
"the",
"next",
"transition",
"that",
"can",
"be",
"performed",
"on",
"the",
"given",
"object",
".",
"If",
"no",
"transitions",
"can",
"be",
"made",
"then",
"this",
"will",
"return",
"nil",
"."
] | 10b03af5fc9245bcb09bbd9c40c58ffba9a85422 | https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L121-L143 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.