id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
16,200
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
16,201
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
16,202
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
16,203
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
16,204
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
16,205
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
16,206
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
16,207
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
16,208
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
16,209
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
16,210
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
16,211
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
16,212
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
16,213
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
16,214
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
16,215
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
16,216
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
16,217
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
16,218
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
16,219
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
16,220
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
16,221
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
16,222
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
16,223
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
16,224
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
16,225
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
16,226
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
16,227
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
16,228
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
16,229
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
16,230
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
16,231
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
16,232
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
16,233
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
16,234
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
16,235
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
16,236
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
16,237
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
16,238
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
16,239
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
16,240
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
16,241
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
16,242
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
16,243
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
16,244
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
16,245
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
16,246
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
16,247
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
16,248
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
16,249
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
16,250
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
16,251
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
16,252
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
16,253
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
16,254
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
16,255
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
16,256
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
16,257
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
16,258
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
16,259
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
16,260
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
16,261
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
16,262
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
16,263
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
16,264
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
16,265
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
16,266
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
16,267
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
16,268
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
16,269
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
16,270
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
16,271
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
16,272
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
16,273
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
16,274
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.fire
def fire(object, *args) machine.reset(object) if transition = transition_for(object) transition.perform(*args) else on_failure(object, *args) false end end
ruby
def fire(object, *args) machine.reset(object) if transition = transition_for(object) transition.perform(*args) else on_failure(object, *args) false end end
[ "def", "fire", "(", "object", ",", "*", "args", ")", "machine", ".", "reset", "(", "object", ")", "if", "transition", "=", "transition_for", "(", "object", ")", "transition", ".", "perform", "(", "args", ")", "else", "on_failure", "(", "object", ",", "args", ")", "false", "end", "end" ]
Attempts to perform the next available transition on the given object. If no transitions can be made, then this will return false, otherwise true. Any additional arguments are passed to the StateMachines::Transition#perform instance method.
[ "Attempts", "to", "perform", "the", "next", "available", "transition", "on", "the", "given", "object", ".", "If", "no", "transitions", "can", "be", "made", "then", "this", "will", "return", "false", "otherwise", "true", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L151-L160
16,275
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.on_failure
def on_failure(object, *args) state = machine.states.match!(object) machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]]) transition = Transition.new(object, machine, name, state.name, state.name) transition.args = args if args.any? transition.run_callbacks(:before => false) end
ruby
def on_failure(object, *args) state = machine.states.match!(object) machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]]) transition = Transition.new(object, machine, name, state.name, state.name) transition.args = args if args.any? transition.run_callbacks(:before => false) end
[ "def", "on_failure", "(", "object", ",", "*", "args", ")", "state", "=", "machine", ".", "states", ".", "match!", "(", "object", ")", "machine", ".", "invalidate", "(", "object", ",", ":state", ",", ":invalid_transition", ",", "[", "[", ":event", ",", "human_name", "(", "object", ".", "class", ")", "]", ",", "[", ":state", ",", "state", ".", "human_name", "(", "object", ".", "class", ")", "]", "]", ")", "transition", "=", "Transition", ".", "new", "(", "object", ",", "machine", ",", "name", ",", "state", ".", "name", ",", "state", ".", "name", ")", "transition", ".", "args", "=", "args", "if", "args", ".", "any?", "transition", ".", "run_callbacks", "(", ":before", "=>", "false", ")", "end" ]
Marks the object as invalid and runs any failure callbacks associated with this event. This should get called anytime this event fails to transition.
[ "Marks", "the", "object", "as", "invalid", "and", "runs", "any", "failure", "callbacks", "associated", "with", "this", "event", ".", "This", "should", "get", "called", "anytime", "this", "event", "fails", "to", "transition", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L164-L171
16,276
state-machines/state_machines
lib/state_machines/event.rb
StateMachines.Event.add_actions
def add_actions # Checks whether the event can be fired on the current object machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args| machine.event(name).can_fire?(object, *args) end # Gets the next transition that would be performed if the event were # fired now machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args| machine.event(name).transition_for(object, *args) end # Fires the event machine.define_helper(:instance, qualified_name) do |machine, object, *args| machine.event(name).fire(object, *args) end # Fires the event, raising an exception if it fails machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args| object.send(qualified_name, *args) || raise(StateMachines::InvalidTransition.new(object, machine, name)) end end
ruby
def add_actions # Checks whether the event can be fired on the current object machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args| machine.event(name).can_fire?(object, *args) end # Gets the next transition that would be performed if the event were # fired now machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args| machine.event(name).transition_for(object, *args) end # Fires the event machine.define_helper(:instance, qualified_name) do |machine, object, *args| machine.event(name).fire(object, *args) end # Fires the event, raising an exception if it fails machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args| object.send(qualified_name, *args) || raise(StateMachines::InvalidTransition.new(object, machine, name)) end end
[ "def", "add_actions", "# Checks whether the event can be fired on the current object", "machine", ".", "define_helper", "(", ":instance", ",", "\"can_#{qualified_name}?\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "can_fire?", "(", "object", ",", "args", ")", "end", "# Gets the next transition that would be performed if the event were", "# fired now", "machine", ".", "define_helper", "(", ":instance", ",", "\"#{qualified_name}_transition\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "transition_for", "(", "object", ",", "args", ")", "end", "# Fires the event", "machine", ".", "define_helper", "(", ":instance", ",", "qualified_name", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "machine", ".", "event", "(", "name", ")", ".", "fire", "(", "object", ",", "args", ")", "end", "# Fires the event, raising an exception if it fails", "machine", ".", "define_helper", "(", ":instance", ",", "\"#{qualified_name}!\"", ")", "do", "|", "machine", ",", "object", ",", "*", "args", "|", "object", ".", "send", "(", "qualified_name", ",", "args", ")", "||", "raise", "(", "StateMachines", "::", "InvalidTransition", ".", "new", "(", "object", ",", "machine", ",", "name", ")", ")", "end", "end" ]
Add the various instance methods that can transition the object using the current event
[ "Add", "the", "various", "instance", "methods", "that", "can", "transition", "the", "object", "using", "the", "current", "event" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/event.rb#L207-L228
16,277
state-machines/state_machines
lib/state_machines/machine_collection.rb
StateMachines.MachineCollection.transitions
def transitions(object, action, options = {}) transitions = map do |name, machine| machine.events.attribute_transition_for(object, true) if machine.action == action end AttributeTransitionCollection.new(transitions.compact, {use_transactions: resolve_use_transactions}.merge(options)) end
ruby
def transitions(object, action, options = {}) transitions = map do |name, machine| machine.events.attribute_transition_for(object, true) if machine.action == action end AttributeTransitionCollection.new(transitions.compact, {use_transactions: resolve_use_transactions}.merge(options)) end
[ "def", "transitions", "(", "object", ",", "action", ",", "options", "=", "{", "}", ")", "transitions", "=", "map", "do", "|", "name", ",", "machine", "|", "machine", ".", "events", ".", "attribute_transition_for", "(", "object", ",", "true", ")", "if", "machine", ".", "action", "==", "action", "end", "AttributeTransitionCollection", ".", "new", "(", "transitions", ".", "compact", ",", "{", "use_transactions", ":", "resolve_use_transactions", "}", ".", "merge", "(", "options", ")", ")", "end" ]
Builds the collection of transitions for all event attributes defined on the given object. This will only include events whose machine actions match the one specified. These should only be fired as a result of the action being run.
[ "Builds", "the", "collection", "of", "transitions", "for", "all", "event", "attributes", "defined", "on", "the", "given", "object", ".", "This", "will", "only", "include", "events", "whose", "machine", "actions", "match", "the", "one", "specified", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/machine_collection.rb#L76-L82
16,278
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.<<
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
ruby
def <<(node) @nodes << node @index_names.each { |name| add_to_index(name, value(node, name), node) } @contexts.each { |context| eval_context(context, node) } self end
[ "def", "<<", "(", "node", ")", "@nodes", "<<", "node", "@index_names", ".", "each", "{", "|", "name", "|", "add_to_index", "(", "name", ",", "value", "(", "node", ",", "name", ")", ",", "node", ")", "}", "@contexts", ".", "each", "{", "|", "context", "|", "eval_context", "(", "context", ",", "node", ")", "}", "self", "end" ]
Adds a new node to the collection. By doing so, this will also add it to the configured indices. This will also evaluate any existings contexts that match the new node.
[ "Adds", "a", "new", "node", "to", "the", "collection", ".", "By", "doing", "so", "this", "will", "also", "add", "it", "to", "the", "configured", "indices", ".", "This", "will", "also", "evaluate", "any", "existings", "contexts", "that", "match", "the", "new", "node", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L85-L90
16,279
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.update_index
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
ruby
def update_index(name, node) index = self.index(name) old_key = index.key(node) new_key = value(node, name) # Only replace the key if it's changed if old_key != new_key remove_from_index(name, old_key) add_to_index(name, new_key, node) end end
[ "def", "update_index", "(", "name", ",", "node", ")", "index", "=", "self", ".", "index", "(", "name", ")", "old_key", "=", "index", ".", "key", "(", "node", ")", "new_key", "=", "value", "(", "node", ",", "name", ")", "# Only replace the key if it's changed", "if", "old_key", "!=", "new_key", "remove_from_index", "(", "name", ",", "old_key", ")", "add_to_index", "(", "name", ",", "new_key", ",", "node", ")", "end", "end" ]
Updates the node for the given index, including the string and symbol versions of the index
[ "Updates", "the", "node", "for", "the", "given", "index", "including", "the", "string", "and", "symbol", "versions", "of", "the", "index" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L196-L206
16,280
state-machines/state_machines
lib/state_machines/node_collection.rb
StateMachines.NodeCollection.eval_context
def eval_context(context, node) node.context(&context[:block]) if context[:nodes].matches?(node.name) end
ruby
def eval_context(context, node) node.context(&context[:block]) if context[:nodes].matches?(node.name) end
[ "def", "eval_context", "(", "context", ",", "node", ")", "node", ".", "context", "(", "context", "[", ":block", "]", ")", "if", "context", "[", ":nodes", "]", ".", "matches?", "(", "node", ".", "name", ")", "end" ]
Evaluates the given context for a particular node. This will only evaluate the context if the node matches.
[ "Evaluates", "the", "given", "context", "for", "a", "particular", "node", ".", "This", "will", "only", "evaluate", "the", "context", "if", "the", "node", "matches", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/node_collection.rb#L215-L217
16,281
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.pause
def pause raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported? unless @resume_block require 'continuation' unless defined?(callcc) callcc do |block| @paused_block = block throw :halt, true end end end
ruby
def pause raise ArgumentError, 'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.' unless self.class.pause_supported? unless @resume_block require 'continuation' unless defined?(callcc) callcc do |block| @paused_block = block throw :halt, true end end end
[ "def", "pause", "raise", "ArgumentError", ",", "'around_transition callbacks cannot be called in multiple execution contexts in java implementations of Ruby. Use before/after_transitions instead.'", "unless", "self", ".", "class", ".", "pause_supported?", "unless", "@resume_block", "require", "'continuation'", "unless", "defined?", "(", "callcc", ")", "callcc", "do", "|", "block", "|", "@paused_block", "=", "block", "throw", ":halt", ",", "true", "end", "end", "end" ]
Pauses the current callback execution. This should only occur within around callbacks when the remainder of the callback will be executed at a later point in time.
[ "Pauses", "the", "current", "callback", "execution", ".", "This", "should", "only", "occur", "within", "around", "callbacks", "when", "the", "remainder", "of", "the", "callback", "will", "be", "executed", "at", "a", "later", "point", "in", "time", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L307-L317
16,282
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.resume
def resume if @paused_block halted, error = callcc do |block| @resume_block = block @paused_block.call end @resume_block = @paused_block = nil raise error if error !halted else true end end
ruby
def resume if @paused_block halted, error = callcc do |block| @resume_block = block @paused_block.call end @resume_block = @paused_block = nil raise error if error !halted else true end end
[ "def", "resume", "if", "@paused_block", "halted", ",", "error", "=", "callcc", "do", "|", "block", "|", "@resume_block", "=", "block", "@paused_block", ".", "call", "end", "@resume_block", "=", "@paused_block", "=", "nil", "raise", "error", "if", "error", "!", "halted", "else", "true", "end", "end" ]
Resumes the execution of a previously paused callback execution. Once the paused callbacks complete, the current execution will continue.
[ "Resumes", "the", "execution", "of", "a", "previously", "paused", "callback", "execution", ".", "Once", "the", "paused", "callbacks", "complete", "the", "current", "execution", "will", "continue", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L321-L335
16,283
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.before
def before(complete = true, index = 0, &block) unless @before_run while callback = machine.callbacks[:before][index] index += 1 if callback.type == :around # Around callback: need to handle recursively. Execution only gets # paused if: # * The block fails and the callback doesn't run on failures OR # * The block succeeds, but after callbacks are disabled (in which # case a continuation is stored for later execution) return if catch(:cancel) do callback.call(object, context, self) do before(complete, index, &block) pause if @success && !complete throw :cancel, true unless @success end end else # Normal before callback callback.call(object, context, self) end end @before_run = true end action = {:success => true}.merge(block_given? ? yield : {}) @result, @success = action[:result], action[:success] end
ruby
def before(complete = true, index = 0, &block) unless @before_run while callback = machine.callbacks[:before][index] index += 1 if callback.type == :around # Around callback: need to handle recursively. Execution only gets # paused if: # * The block fails and the callback doesn't run on failures OR # * The block succeeds, but after callbacks are disabled (in which # case a continuation is stored for later execution) return if catch(:cancel) do callback.call(object, context, self) do before(complete, index, &block) pause if @success && !complete throw :cancel, true unless @success end end else # Normal before callback callback.call(object, context, self) end end @before_run = true end action = {:success => true}.merge(block_given? ? yield : {}) @result, @success = action[:result], action[:success] end
[ "def", "before", "(", "complete", "=", "true", ",", "index", "=", "0", ",", "&", "block", ")", "unless", "@before_run", "while", "callback", "=", "machine", ".", "callbacks", "[", ":before", "]", "[", "index", "]", "index", "+=", "1", "if", "callback", ".", "type", "==", ":around", "# Around callback: need to handle recursively. Execution only gets", "# paused if:", "# * The block fails and the callback doesn't run on failures OR", "# * The block succeeds, but after callbacks are disabled (in which", "# case a continuation is stored for later execution)", "return", "if", "catch", "(", ":cancel", ")", "do", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "do", "before", "(", "complete", ",", "index", ",", "block", ")", "pause", "if", "@success", "&&", "!", "complete", "throw", ":cancel", ",", "true", "unless", "@success", "end", "end", "else", "# Normal before callback", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "end", "end", "@before_run", "=", "true", "end", "action", "=", "{", ":success", "=>", "true", "}", ".", "merge", "(", "block_given?", "?", "yield", ":", "{", "}", ")", "@result", ",", "@success", "=", "action", "[", ":result", "]", ",", "action", "[", ":success", "]", "end" ]
Runs the machine's +before+ callbacks for this transition. Only callbacks that are configured to match the event, from state, and to state will be invoked. Once the callbacks are run, they cannot be run again until this transition is reset.
[ "Runs", "the", "machine", "s", "+", "before", "+", "callbacks", "for", "this", "transition", ".", "Only", "callbacks", "that", "are", "configured", "to", "match", "the", "event", "from", "state", "and", "to", "state", "will", "be", "invoked", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L343-L373
16,284
state-machines/state_machines
lib/state_machines/transition.rb
StateMachines.Transition.after
def after unless @after_run # First resume previously paused callbacks if resume catch(:halt) do type = @success ? :after : :failure machine.callbacks[type].each {|callback| callback.call(object, context, self)} end end @after_run = true end end
ruby
def after unless @after_run # First resume previously paused callbacks if resume catch(:halt) do type = @success ? :after : :failure machine.callbacks[type].each {|callback| callback.call(object, context, self)} end end @after_run = true end end
[ "def", "after", "unless", "@after_run", "# First resume previously paused callbacks", "if", "resume", "catch", "(", ":halt", ")", "do", "type", "=", "@success", "?", ":after", ":", ":failure", "machine", ".", "callbacks", "[", "type", "]", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "(", "object", ",", "context", ",", "self", ")", "}", "end", "end", "@after_run", "=", "true", "end", "end" ]
Runs the machine's +after+ callbacks for this transition. Only callbacks that are configured to match the event, from state, and to state will be invoked. Once the callbacks are run, they cannot be run again until this transition is reset. == Halting If any callback throws a <tt>:halt</tt> exception, it will be caught and the callback chain will be automatically stopped. However, this exception will not bubble up to the caller since +after+ callbacks should never halt the execution of a +perform+.
[ "Runs", "the", "machine", "s", "+", "after", "+", "callbacks", "for", "this", "transition", ".", "Only", "callbacks", "that", "are", "configured", "to", "match", "the", "event", "from", "state", "and", "to", "state", "will", "be", "invoked", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition.rb#L388-L400
16,285
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.TransitionCollection.run_callbacks
def run_callbacks(index = 0, &block) if transition = self[index] throw :halt unless transition.run_callbacks(:after => !skip_after) do run_callbacks(index + 1, &block) {:result => results[transition.action], :success => success?} end else persist run_actions(&block) end end
ruby
def run_callbacks(index = 0, &block) if transition = self[index] throw :halt unless transition.run_callbacks(:after => !skip_after) do run_callbacks(index + 1, &block) {:result => results[transition.action], :success => success?} end else persist run_actions(&block) end end
[ "def", "run_callbacks", "(", "index", "=", "0", ",", "&", "block", ")", "if", "transition", "=", "self", "[", "index", "]", "throw", ":halt", "unless", "transition", ".", "run_callbacks", "(", ":after", "=>", "!", "skip_after", ")", "do", "run_callbacks", "(", "index", "+", "1", ",", "block", ")", "{", ":result", "=>", "results", "[", "transition", ".", "action", "]", ",", ":success", "=>", "success?", "}", "end", "else", "persist", "run_actions", "(", "block", ")", "end", "end" ]
Runs each transition's callbacks recursively. Once all before callbacks have been executed, the transitions will then be persisted and the configured actions will be run. If any transition fails to run its callbacks, :halt will be thrown.
[ "Runs", "each", "transition", "s", "callbacks", "recursively", ".", "Once", "all", "before", "callbacks", "have", "been", "executed", "the", "transitions", "will", "then", "be", "persisted", "and", "the", "configured", "actions", "will", "be", "run", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L125-L135
16,286
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.TransitionCollection.run_actions
def run_actions catch_exceptions do @success = if block_given? result = yield actions.each {|action| results[action] = result} !!result else actions.compact.each {|action| !skip_actions && results[action] = object.send(action)} results.values.all? end end end
ruby
def run_actions catch_exceptions do @success = if block_given? result = yield actions.each {|action| results[action] = result} !!result else actions.compact.each {|action| !skip_actions && results[action] = object.send(action)} results.values.all? end end end
[ "def", "run_actions", "catch_exceptions", "do", "@success", "=", "if", "block_given?", "result", "=", "yield", "actions", ".", "each", "{", "|", "action", "|", "results", "[", "action", "]", "=", "result", "}", "!", "!", "result", "else", "actions", ".", "compact", ".", "each", "{", "|", "action", "|", "!", "skip_actions", "&&", "results", "[", "action", "]", "=", "object", ".", "send", "(", "action", ")", "}", "results", ".", "values", ".", "all?", "end", "end", "end" ]
Runs the actions for each transition. If a block is given method, then it will be called instead of invoking each transition's action. The results of the actions will be used to determine #success?.
[ "Runs", "the", "actions", "for", "each", "transition", ".", "If", "a", "block", "is", "given", "method", "then", "it", "will", "be", "called", "instead", "of", "invoking", "each", "transition", "s", "action", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L147-L158
16,287
state-machines/state_machines
lib/state_machines/transition_collection.rb
StateMachines.AttributeTransitionCollection.rollback
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
ruby
def rollback super each {|transition| transition.machine.write(object, :event, transition.event) unless transition.transient?} end
[ "def", "rollback", "super", "each", "{", "|", "transition", "|", "transition", ".", "machine", ".", "write", "(", "object", ",", ":event", ",", "transition", ".", "event", ")", "unless", "transition", ".", "transient?", "}", "end" ]
Resets the event attribute so it can be re-evaluated if attempted again
[ "Resets", "the", "event", "attribute", "so", "it", "can", "be", "re", "-", "evaluated", "if", "attempted", "again" ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/transition_collection.rb#L241-L244
16,288
state-machines/state_machines
lib/state_machines/callback.rb
StateMachines.Callback.call
def call(object, context = {}, *args, &block) if @branch.matches?(object, context) run_methods(object, context, 0, *args, &block) true else false end end
ruby
def call(object, context = {}, *args, &block) if @branch.matches?(object, context) run_methods(object, context, 0, *args, &block) true else false end end
[ "def", "call", "(", "object", ",", "context", "=", "{", "}", ",", "*", "args", ",", "&", "block", ")", "if", "@branch", ".", "matches?", "(", "object", ",", "context", ")", "run_methods", "(", "object", ",", "context", ",", "0", ",", "args", ",", "block", ")", "true", "else", "false", "end", "end" ]
Runs the callback as long as the transition context matches the branch requirements configured for this callback. If a block is provided, it will be called when the last method has run. If a terminator has been configured and it matches the result from the evaluated method, then the callback chain should be halted.
[ "Runs", "the", "callback", "as", "long", "as", "the", "transition", "context", "matches", "the", "branch", "requirements", "configured", "for", "this", "callback", ".", "If", "a", "block", "is", "provided", "it", "will", "be", "called", "when", "the", "last", "method", "has", "run", "." ]
10b03af5fc9245bcb09bbd9c40c58ffba9a85422
https://github.com/state-machines/state_machines/blob/10b03af5fc9245bcb09bbd9c40c58ffba9a85422/lib/state_machines/callback.rb#L157-L164
16,289
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.get
def get(uri, opts = {}, &block) initialize_socket(uri, opts) HttpStream::get(uri, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
def get(uri, opts = {}, &block) initialize_socket(uri, opts) HttpStream::get(uri, opts, &block) rescue IOError => e raise e unless @intentional_termination end
[ "def", "get", "(", "uri", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "initialize_socket", "(", "uri", ",", "opts", ")", "HttpStream", "::", "get", "(", "uri", ",", "opts", ",", "block", ")", "rescue", "IOError", "=>", "e", "raise", "e", "unless", "@intentional_termination", "end" ]
Makes a basic HTTP GET request to the URI provided allowing the user to terminate the connection
[ "Makes", "a", "basic", "HTTP", "GET", "request", "to", "the", "URI", "provided", "allowing", "the", "user", "to", "terminate", "the", "connection" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L37-L42
16,290
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.post
def post(uri, body, opts = {}, &block) initialize_socket(uri, opts) HttpStream::post(uri, body, opts, &block) rescue IOError => e raise e unless @intentional_termination end
ruby
def post(uri, body, opts = {}, &block) initialize_socket(uri, opts) HttpStream::post(uri, body, opts, &block) rescue IOError => e raise e unless @intentional_termination end
[ "def", "post", "(", "uri", ",", "body", ",", "opts", "=", "{", "}", ",", "&", "block", ")", "initialize_socket", "(", "uri", ",", "opts", ")", "HttpStream", "::", "post", "(", "uri", ",", "body", ",", "opts", ",", "block", ")", "rescue", "IOError", "=>", "e", "raise", "e", "unless", "@intentional_termination", "end" ]
Makes a basic HTTP POST request to the URI provided allowing the user to terminate the connection
[ "Makes", "a", "basic", "HTTP", "POST", "request", "to", "the", "URI", "provided", "allowing", "the", "user", "to", "terminate", "the", "connection" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L50-L55
16,291
brianmario/yajl-ruby
lib/yajl/http_stream.rb
Yajl.HttpStream.initialize_socket
def initialize_socket(uri, opts = {}) return if opts[:socket] @socket = TCPSocket.new(uri.host, uri.port) opts.merge!({:socket => @socket}) @intentional_termination = false end
ruby
def initialize_socket(uri, opts = {}) return if opts[:socket] @socket = TCPSocket.new(uri.host, uri.port) opts.merge!({:socket => @socket}) @intentional_termination = false end
[ "def", "initialize_socket", "(", "uri", ",", "opts", "=", "{", "}", ")", "return", "if", "opts", "[", ":socket", "]", "@socket", "=", "TCPSocket", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "opts", ".", "merge!", "(", "{", ":socket", "=>", "@socket", "}", ")", "@intentional_termination", "=", "false", "end" ]
Initialize socket and add it to the opts
[ "Initialize", "socket", "and", "add", "it", "to", "the", "opts" ]
2f927c42bf4e1d766a1eb1f532d5924c3b61f588
https://github.com/brianmario/yajl-ruby/blob/2f927c42bf4e1d766a1eb1f532d5924c3b61f588/lib/yajl/http_stream.rb#L205-L211
16,292
brentd/xray-rails
lib/xray/middleware.rb
Xray.Middleware.append_js!
def append_js!(html, after_script_name, script_name) html.sub!(script_matcher(after_script_name)) do "#{$~}\n" + helper.javascript_include_tag(script_name) end end
ruby
def append_js!(html, after_script_name, script_name) html.sub!(script_matcher(after_script_name)) do "#{$~}\n" + helper.javascript_include_tag(script_name) end end
[ "def", "append_js!", "(", "html", ",", "after_script_name", ",", "script_name", ")", "html", ".", "sub!", "(", "script_matcher", "(", "after_script_name", ")", ")", "do", "\"#{$~}\\n\"", "+", "helper", ".", "javascript_include_tag", "(", "script_name", ")", "end", "end" ]
Appends the given `script_name` after the `after_script_name`.
[ "Appends", "the", "given", "script_name", "after", "the", "after_script_name", "." ]
ab86801b55285771c567352e1784ae4346dc06a4
https://github.com/brentd/xray-rails/blob/ab86801b55285771c567352e1784ae4346dc06a4/lib/xray/middleware.rb#L114-L118
16,293
plataformatec/has_scope
lib/has_scope.rb
HasScope.ClassMethods.has_scope
def has_scope(*scopes, &block) options = scopes.extract_options! options.symbolize_keys! options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in) if options.key?(:in) options[:as] = options[:in] options[:using] = scopes end if options.key?(:using) if options.key?(:type) && options[:type] != :hash raise "You cannot use :using with another :type different than :hash" else options[:type] = :hash end options[:using] = Array(options[:using]) end options[:only] = Array(options[:only]) options[:except] = Array(options[:except]) self.scopes_configuration = scopes_configuration.dup scopes.each do |scope| scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } scopes_configuration[scope] = self.scopes_configuration[scope].merge(options) end end
ruby
def has_scope(*scopes, &block) options = scopes.extract_options! options.symbolize_keys! options.assert_valid_keys(:type, :only, :except, :if, :unless, :default, :as, :using, :allow_blank, :in) if options.key?(:in) options[:as] = options[:in] options[:using] = scopes end if options.key?(:using) if options.key?(:type) && options[:type] != :hash raise "You cannot use :using with another :type different than :hash" else options[:type] = :hash end options[:using] = Array(options[:using]) end options[:only] = Array(options[:only]) options[:except] = Array(options[:except]) self.scopes_configuration = scopes_configuration.dup scopes.each do |scope| scopes_configuration[scope] ||= { :as => scope, :type => :default, :block => block } scopes_configuration[scope] = self.scopes_configuration[scope].merge(options) end end
[ "def", "has_scope", "(", "*", "scopes", ",", "&", "block", ")", "options", "=", "scopes", ".", "extract_options!", "options", ".", "symbolize_keys!", "options", ".", "assert_valid_keys", "(", ":type", ",", ":only", ",", ":except", ",", ":if", ",", ":unless", ",", ":default", ",", ":as", ",", ":using", ",", ":allow_blank", ",", ":in", ")", "if", "options", ".", "key?", "(", ":in", ")", "options", "[", ":as", "]", "=", "options", "[", ":in", "]", "options", "[", ":using", "]", "=", "scopes", "end", "if", "options", ".", "key?", "(", ":using", ")", "if", "options", ".", "key?", "(", ":type", ")", "&&", "options", "[", ":type", "]", "!=", ":hash", "raise", "\"You cannot use :using with another :type different than :hash\"", "else", "options", "[", ":type", "]", "=", ":hash", "end", "options", "[", ":using", "]", "=", "Array", "(", "options", "[", ":using", "]", ")", "end", "options", "[", ":only", "]", "=", "Array", "(", "options", "[", ":only", "]", ")", "options", "[", ":except", "]", "=", "Array", "(", "options", "[", ":except", "]", ")", "self", ".", "scopes_configuration", "=", "scopes_configuration", ".", "dup", "scopes", ".", "each", "do", "|", "scope", "|", "scopes_configuration", "[", "scope", "]", "||=", "{", ":as", "=>", "scope", ",", ":type", "=>", ":default", ",", ":block", "=>", "block", "}", "scopes_configuration", "[", "scope", "]", "=", "self", ".", "scopes_configuration", "[", "scope", "]", ".", "merge", "(", "options", ")", "end", "end" ]
Detects params from url and apply as scopes to your classes. == Options * <tt>:type</tt> - Checks the type of the parameter sent. If set to :boolean it just calls the named scope, without any argument. By default, it does not allow hashes or arrays to be given, except if type :hash or :array are set. * <tt>:only</tt> - In which actions the scope is applied. By default is :all. * <tt>:except</tt> - In which actions the scope is not applied. By default is :none. * <tt>:as</tt> - The key in the params hash expected to find the scope. Defaults to the scope name. * <tt>:using</tt> - If type is a hash, you can provide :using to convert the hash to a named scope call with several arguments. * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the scope should apply * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the scope should NOT apply. * <tt>:default</tt> - Default value for the scope. Whenever supplied the scope is always called. * <tt>:allow_blank</tt> - Blank values are not sent to scopes by default. Set to true to overwrite. == Block usage has_scope also accepts a block. The controller, current scope and value are yielded to the block so the user can apply the scope on its own. This is useful in case we need to manipulate the given value: has_scope :category do |controller, scope, value| value != "all" ? scope.by_category(value) : scope end has_scope :not_voted_by_me, :type => :boolean do |controller, scope| scope.not_voted_by(controller.current_user.id) end
[ "Detects", "params", "from", "url", "and", "apply", "as", "scopes", "to", "your", "classes", "." ]
ac9f4e68ce14f3f4b94fd323d7b9a0acbab4cfb3
https://github.com/plataformatec/has_scope/blob/ac9f4e68ce14f3f4b94fd323d7b9a0acbab4cfb3/lib/has_scope.rb#L64-L93
16,294
ohler55/ox
lib/ox/element.rb
Ox.Element.attr_match
def attr_match(cond) cond.each_pair { |k,v| return false unless v == @attributes[k.to_sym] || v == @attributes[k.to_s] } true end
ruby
def attr_match(cond) cond.each_pair { |k,v| return false unless v == @attributes[k.to_sym] || v == @attributes[k.to_s] } true end
[ "def", "attr_match", "(", "cond", ")", "cond", ".", "each_pair", "{", "|", "k", ",", "v", "|", "return", "false", "unless", "v", "==", "@attributes", "[", "k", ".", "to_sym", "]", "||", "v", "==", "@attributes", "[", "k", ".", "to_s", "]", "}", "true", "end" ]
Return true if all the key-value pairs in the cond Hash match the @attributes key-values.
[ "Return", "true", "if", "all", "the", "key", "-", "value", "pairs", "in", "the", "cond", "Hash", "match", "the" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L106-L109
16,295
ohler55/ox
lib/ox/element.rb
Ox.Element.each
def each(cond=nil) if cond.nil? nodes.each { |n| yield(n) } else cond = cond.to_s if cond.is_a?(Symbol) if cond.is_a?(String) nodes.each { |n| yield(n) if n.is_a?(Element) && cond == n.name } elsif cond.is_a?(Hash) nodes.each { |n| yield(n) if n.is_a?(Element) && n.attr_match(cond) } end end end
ruby
def each(cond=nil) if cond.nil? nodes.each { |n| yield(n) } else cond = cond.to_s if cond.is_a?(Symbol) if cond.is_a?(String) nodes.each { |n| yield(n) if n.is_a?(Element) && cond == n.name } elsif cond.is_a?(Hash) nodes.each { |n| yield(n) if n.is_a?(Element) && n.attr_match(cond) } end end end
[ "def", "each", "(", "cond", "=", "nil", ")", "if", "cond", ".", "nil?", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "}", "else", "cond", "=", "cond", ".", "to_s", "if", "cond", ".", "is_a?", "(", "Symbol", ")", "if", "cond", ".", "is_a?", "(", "String", ")", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "if", "n", ".", "is_a?", "(", "Element", ")", "&&", "cond", "==", "n", ".", "name", "}", "elsif", "cond", ".", "is_a?", "(", "Hash", ")", "nodes", ".", "each", "{", "|", "n", "|", "yield", "(", "n", ")", "if", "n", ".", "is_a?", "(", "Element", ")", "&&", "n", ".", "attr_match", "(", "cond", ")", "}", "end", "end", "end" ]
Iterate over each child of the instance yielding according to the cond argument value. If the cond argument is nil then all child nodes are yielded to. If cond is a string then only the child Elements with a matching name will be yielded to. If the cond is a Hash then the keys-value pairs in the cond must match the child attribute values with the same keys. Any other cond type will yield to nothing.
[ "Iterate", "over", "each", "child", "of", "the", "instance", "yielding", "according", "to", "the", "cond", "argument", "value", ".", "If", "the", "cond", "argument", "is", "nil", "then", "all", "child", "nodes", "are", "yielded", "to", ".", "If", "cond", "is", "a", "string", "then", "only", "the", "child", "Elements", "with", "a", "matching", "name", "will", "be", "yielded", "to", ".", "If", "the", "cond", "is", "a", "Hash", "then", "the", "keys", "-", "value", "pairs", "in", "the", "cond", "must", "match", "the", "child", "attribute", "values", "with", "the", "same", "keys", ".", "Any", "other", "cond", "type", "will", "yield", "to", "nothing", "." ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L117-L128
16,296
ohler55/ox
lib/ox/element.rb
Ox.Element.remove_children
def remove_children(*children) return self if children.compact.empty? recursive_children_removal(children.compact.map { |c| c.object_id }) self end
ruby
def remove_children(*children) return self if children.compact.empty? recursive_children_removal(children.compact.map { |c| c.object_id }) self end
[ "def", "remove_children", "(", "*", "children", ")", "return", "self", "if", "children", ".", "compact", ".", "empty?", "recursive_children_removal", "(", "children", ".", "compact", ".", "map", "{", "|", "c", "|", "c", ".", "object_id", "}", ")", "self", "end" ]
Remove all the children matching the path provided Examples are: * <code>element.remove_children(Ox:Element)</code> removes the element passed as argument if child of the element. * <code>element.remove_children(Ox:Element, Ox:Element)</code> removes the list of elements passed as argument if children of the element. - +children+ [Array] array of OX
[ "Remove", "all", "the", "children", "matching", "the", "path", "provided" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L192-L196
16,297
ohler55/ox
lib/ox/element.rb
Ox.Element.recursive_children_removal
def recursive_children_removal(found) return if found.empty? nodes.tap do |ns| # found.delete(n.object_id) stops looking for an already found object_id ns.delete_if { |n| found.include?(n.object_id) ? found.delete(n.object_id) : false } nodes.each do |n| n.send(:recursive_children_removal, found) if n.is_a?(Ox::Element) end end end
ruby
def recursive_children_removal(found) return if found.empty? nodes.tap do |ns| # found.delete(n.object_id) stops looking for an already found object_id ns.delete_if { |n| found.include?(n.object_id) ? found.delete(n.object_id) : false } nodes.each do |n| n.send(:recursive_children_removal, found) if n.is_a?(Ox::Element) end end end
[ "def", "recursive_children_removal", "(", "found", ")", "return", "if", "found", ".", "empty?", "nodes", ".", "tap", "do", "|", "ns", "|", "# found.delete(n.object_id) stops looking for an already found object_id", "ns", ".", "delete_if", "{", "|", "n", "|", "found", ".", "include?", "(", "n", ".", "object_id", ")", "?", "found", ".", "delete", "(", "n", ".", "object_id", ")", ":", "false", "}", "nodes", ".", "each", "do", "|", "n", "|", "n", ".", "send", "(", ":recursive_children_removal", ",", "found", ")", "if", "n", ".", "is_a?", "(", "Ox", "::", "Element", ")", "end", "end", "end" ]
Removes recursively children for nodes and sub_nodes - +found+ [Array] An array of Ox::Element
[ "Removes", "recursively", "children", "for", "nodes", "and", "sub_nodes" ]
f5b618285a0b9c885aa86dd9d51188fce2d60856
https://github.com/ohler55/ox/blob/f5b618285a0b9c885aa86dd9d51188fce2d60856/lib/ox/element.rb#L418-L427
16,298
igor-makarov/xcake
lib/xcake/visitor.rb
Xcake.Visitor.visit
def visit(item) item_name = item_name(item) method = "visit_#{item_name}" send(method, item) if respond_to? method end
ruby
def visit(item) item_name = item_name(item) method = "visit_#{item_name}" send(method, item) if respond_to? method end
[ "def", "visit", "(", "item", ")", "item_name", "=", "item_name", "(", "item", ")", "method", "=", "\"visit_#{item_name}\"", "send", "(", "method", ",", "item", ")", "if", "respond_to?", "method", "end" ]
This is called when a visitor is visiting a visitable item. By default this method calls the method `visit_<visitable classname>` so make sure you've created a method for each visitable you intend to visit. @param [Visitable] visitable the visitable item the visitor is visiting
[ "This", "is", "called", "when", "a", "visitor", "is", "visiting", "a", "visitable", "item", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/visitor.rb#L41-L46
16,299
igor-makarov/xcake
lib/xcake/visitor.rb
Xcake.Visitor.leave
def leave(item) item_name = item_name(item) method = "leave_#{item_name}" send(method, item) if respond_to? method end
ruby
def leave(item) item_name = item_name(item) method = "leave_#{item_name}" send(method, item) if respond_to? method end
[ "def", "leave", "(", "item", ")", "item_name", "=", "item_name", "(", "item", ")", "method", "=", "\"leave_#{item_name}\"", "send", "(", "method", ",", "item", ")", "if", "respond_to?", "method", "end" ]
This is called when a visitor is leaving a visitable item. By default this method calls the method `leave_<visitable classname>` so make sure you've created a method for each visitable you intend to visit. @param [Visitable] visitable the visitable item the visitor has left
[ "This", "is", "called", "when", "a", "visitor", "is", "leaving", "a", "visitable", "item", "." ]
4a16d5cf2662cfe1dc521b6818e441748ba5a02a
https://github.com/igor-makarov/xcake/blob/4a16d5cf2662cfe1dc521b6818e441748ba5a02a/lib/xcake/visitor.rb#L59-L64