idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
5,900
def find_home [ 'HOME' , 'USERPROFILE' ] . each { | e | return ENV [ e ] if ENV [ e ] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV [ 'HOMEDRIVE' ] && ENV [ 'HOMEPATH' ] File . expand_path ( "~" ) rescue File :: ALT_SEPARATOR ? "C:/" : "/" end
From Rubygems determine a user s home .
5,901
def build_args ( args ) args . each do | arg | arg . each do | key , value | case key . to_s when 'query_params' @query_params = value when 'request_headers' update_headers ( value ) when 'request_body' @request_body = value end end end end
Set the query params request headers and request body
5,902
def build_url ( query_params : nil ) url = [ add_version ( '' ) , * @url_path ] . join ( '/' ) url = build_query_params ( url , query_params ) if query_params URI . parse ( "#{@host}#{url}" ) end
Build the final url
5,903
def make_request ( http , request ) response = http . request ( request ) Response . new ( response ) end
Make the API call and return the response . This is separated into it s own function so we can mock it easily for testing .
5,904
def build_http ( host , port ) params = [ host , port ] params += @proxy_options . values_at ( :host , :port , :user , :pass ) unless @proxy_options . empty? add_ssl ( Net :: HTTP . new ( * params ) ) end
Build HTTP request object
5,905
def add_ssl ( http ) if host . start_with? ( 'https' ) http . use_ssl = true http . verify_mode = OpenSSL :: SSL :: VERIFY_PEER end http end
Allow for https calls
5,906
def fetch ( ids ) data = nil model . synchronize do ids . each do | id | redis . queue ( "HGETALL" , namespace [ id ] ) end data = redis . commit end return [ ] if data . nil? [ ] . tap do | result | data . each_with_index do | atts , idx | result << model . new ( Utils . dict ( atts ) . update ( :id => ids [ idx ] ) )...
Wraps the whole pipelining functionality .
5,907
def sort ( options = { } ) if options . has_key? ( :get ) options [ :get ] = to_key ( options [ :get ] ) Stal . solve ( redis , [ "SORT" , key , * Utils . sort_options ( options ) ] ) else fetch ( Stal . solve ( redis , [ "SORT" , key , * Utils . sort_options ( options ) ] ) ) end end
Allows you to sort your models using their IDs . This is much faster than sort_by . If you simply want to get records in ascending or descending order then this is the best method to do that .
5,908
def find ( dict ) Ohm :: Set . new ( model , namespace , [ :SINTER , key , * model . filters ( dict ) ] ) end
Chain new fiters on an existing set .
5,909
def replace ( models ) ids = models . map ( & :id ) model . synchronize do redis . queue ( "MULTI" ) redis . queue ( "DEL" , key ) ids . each { | id | redis . queue ( "SADD" , key , id ) } redis . queue ( "EXEC" ) redis . commit end end
Replace all the existing elements of a set with a different collection of models . This happens atomically in a MULTI - EXEC block .
5,910
def set ( att , val ) if val . to_s . empty? key . call ( "HDEL" , att ) else key . call ( "HSET" , att , val ) end @attributes [ att ] = val end
Update an attribute value atomically . The best usecase for this is when you simply want to update one value .
5,911
def save indices = { } model . indices . each do | field | next unless ( value = send ( field ) ) indices [ field ] = Array ( value ) . map ( & :to_s ) end uniques = { } model . uniques . each do | field | next unless ( value = send ( field ) ) uniques [ field ] = value . to_s end features = { "name" => model . name } ...
Persist the model attributes and update indices and unique indices . The counter s and set s are not touched during save .
5,912
def grab_file ( source_file ) source_name = File . join ( PictureTag . config . source_dir , source_file ) unless File . exist? source_name raise "Jekyll Picture Tag could not find #{source_name}." end source_name end
Turn a relative filename into an absolute one and make sure it exists .
5,913
def transform dom = Nokogiri :: HTML . parse html callback before_transformation , dom improve dom inline dom , keep_uninlinable_in : :head rewrite_urls dom callback after_transformation , dom remove_ignore_markers dom serialize_document dom end
Transform the input HTML as a full document and returns the processed HTML .
5,914
def extract_css stylesheets = @dom . css ( STYLE_ELEMENT_QUERY ) . map { | element | stylesheet = read_stylesheet ( element ) element . remove if stylesheet stylesheet } . compact stylesheets end
Looks for all non - ignored stylesheets removes their references from the DOM and then returns them .
5,915
def generate_url ( path , base = "/" ) return root_uri . to_s if path . nil? or path . empty? return path if path_is_anchor? ( path ) return add_scheme ( path ) if path_is_schemeless? ( path ) return path if Utils . path_is_absolute? ( path ) combine_segments ( root_uri , base , path ) . to_s end
Create a new instance with the given URL options .
5,916
def add_uninlinable_styles ( parent , blocks , merge_media_queries ) return if blocks . empty? parent_node = case parent when :head find_head when :root dom else raise ArgumentError , "Parent must be either :head or :root. Was #{parent.inspect}" end create_style_element ( blocks , parent_node , merge_media_queries ) en...
Adds unlineable styles in the specified part of the document either the head or in the document
5,917
def by_name ( & block ) @grouped ||= @gems . group_by ( & :name ) . map { | name , collection | [ name , Geminabox :: GemVersionCollection . new ( collection ) ] } . sort_by { | name , collection | name . downcase } if block_given? @grouped . each ( & block ) else @grouped end end
The collection can contain gems of different names this method groups them by name and then sorts the different version of each name by version and platform .
5,918
def create_ssl_certificate ( cert_params ) file_path = cert_params [ :output_file ] . sub ( / \. \w / , "" ) path = prompt_for_file_path file_path = File . join ( path , file_path ) unless path . empty? cert_params [ :domain ] = prompt_for_domain rsa_key = generate_keypair cert_params [ :key_length ] cert = generate_ce...
SSL certificate generation for knife - azure ssl bootstrap
5,919
def get_images ( img_type ) images = Hash . new if img_type == "OSImage" response = @connection . query_azure ( "images" ) elsif img_type == "VMImage" response = @connection . query_azure ( "vmimages" ) end unless response . to_s . empty? osimages = response . css ( img_type ) osimages . each do | image | item = Image ...
img_type = OSImages or VMImage
5,920
def exists_on_cloud? ( name ) ret_val = @connection . query_azure ( "storageservices/#{name}" ) error_code , error_message = error_from_response_xml ( ret_val ) if ret_val if ret_val . nil? || error_code . length > 0 Chef :: Log . warn "Unable to find storage account:" + error_message + " : " + error_message if ret_val...
Look up on cloud and not local cache
5,921
def subnets_list_for_specific_address_space ( address_prefix , subnets_list ) list = [ ] address_space = IPAddress ( address_prefix ) subnets_list . each do | sbn | subnet_address_prefix = IPAddress ( sbn . address_prefix ) list << sbn if address_space . include? subnet_address_prefix end list end
lists subnets of only a specific virtual network address space
5,922
def subnets_list ( resource_group_name , vnet_name , address_prefix = nil ) list = network_resource_client . subnets . list ( resource_group_name , vnet_name ) ! address_prefix . nil? && ! list . empty? ? subnets_list_for_specific_address_space ( address_prefix , list ) : list end
lists all subnets under a virtual network or lists subnets of only a particular address space
5,923
def sort_available_networks ( available_networks ) available_networks . sort_by { | nwrk | nwrk . network . address . split ( "." ) . map ( & :to_i ) } end
sort available networks pool in ascending order based on the network s IP address to allocate the network for the new subnet to be added in the existing virtual network
5,924
def sort_subnets_by_cidr_prefix ( subnets ) subnets . sort_by . with_index { | sbn , i | [ subnet_address_prefix ( sbn ) . split ( "/" ) [ 1 ] . to_i , i ] } end
sort existing subnets in ascending order based on their cidr prefix or netmask to have subnets with larger networks on the top
5,925
def sort_used_networks_by_hosts_size ( used_network ) used_network . sort_by . with_index { | nwrk , i | [ - nwrk . hosts . size , i ] } end
sort used networks pool in descending order based on the number of hosts it contains this helps to keep larger networks on top thereby eliminating more number of entries in available_networks_pool at a faster pace
5,926
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 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
5,927
def new_subnet_address_prefix ( vnet_address_prefix , subnets ) if subnets . empty? divide_network ( vnet_address_prefix ) else 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...
calculate and return address_prefix for the new subnet to be added in the existing virtual network
5,928
def add_subnet ( subnet_name , vnet_config , subnets ) new_subnet_prefix = nil vnet_address_prefix_count = 0 vnet_address_space = vnet_config [ :addressPrefixes ] while new_subnet_prefix . nil? && vnet_address_space . length > vnet_address_prefix_count new_subnet_prefix = new_subnet_address_prefix ( vnet_address_space ...
add new subnet into the existing virtual network
5,929
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 = t...
virtual network configuration creation for the new vnet creation or to handle existing vnet
5,930
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 r...
Look up hosted service on cloud and not local cache
5,931
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 .
5,932
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 .
5,933
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...
Selects all the rules matching given hostame .
5,934
def start! @active = true Minicron . establish_db_connection ( Minicron . config [ 'server' ] [ 'database' ] , Minicron . config [ 'verbose' ] ) @start_time = Time . now . utc @thread = Thread . new do while @active schedules = Minicron :: Hub :: Model :: Schedule . all schedules . each do | schedule | begin monitor ( ...
Starts the execution monitor in a new thread
5,935
def monitor ( schedule ) cron = CronParser . new ( schedule . formatted ) expected_at = cron . last ( Time . now . utc ) - 30 expected_by = expected_at + 30 + 60 + 30 if expected_at > @start_time && Time . now . utc > expected_by && expected_by > schedule . updated_at check = Minicron :: Hub :: Model :: Execution . exi...
Handle the monitoring of a cron schedule
5,936
def build_crontab ( host ) crontab = "#\n" crontab += "# This file was automatically generated by minicron at #{Time.now.utc}, DO NOT EDIT manually!\n" crontab += "#\n\n" crontab += "# ENV variables\n" crontab += "PATH=#{PATH}\n" crontab += "MAILTO=\"\"\n" crontab += "\n" unless host . nil? host . jobs . each do | job ...
Build the crontab multiline string that includes all the given jobs
5,937
def with_default_scheme ( url ) parsed ( url ) && parsed ( url ) . scheme . nil? ? 'http://' + url : url end
Adds http as default scheme if there is none
5,938
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 ...
5,939
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 ,...
Returns all document data as a nested Hash
5,940
def has_option? ( option ) 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
5,941
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
5,942
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...
5,943
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_f...
Sets that this app uses a config file as well as the name of the config file .
5,944
def reset 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 @aut...
Reset the GLI module internal data structures ; mostly useful for testing
5,945
def run ( args ) 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 , :s...
Runs whatever command is needed based on the arguments .
5,946
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
5,947
def proceed? ( parsing_result ) 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
5,948
def regular_error_handling? ( ex ) 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
5,949
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
5,950
def verify_unused ( names ) 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
5,951
def parse_options ( args ) 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 ) op...
Given the command - line argument array returns an OptionParsingResult
5,952
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 .
5,953
def parse_names ( names ) 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...
Handles dealing with the names param parsing it into the primary name and aliases list
5,954
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 .
5,955
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 .
5,956
def capture ( url , path , opts = { } ) begin 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 ....
Captures a screenshot of + url + saving it to + path + .
5,957
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 , opt...
Returns a file upload input tag wrapped in markup that allows dragging and dropping of files onto the element .
5,958
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 , ...
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 .
5,959
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" ...
Generates a hash of default options for the embedded file input field .
5,960
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 .
5,961
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 .
5,962
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
5,963
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_mis...
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 .
5,964
def add_predicate 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
5,965
def initial_state = ( new_initial_state ) @initial_state = new_initial_state add_states ( [ @initial_state ] ) unless dynamic_initial_state? states . each { | state | state . initial = ( state . name == @initial_state ) } initial_state = states . detect { | state | state . initial } if ! owner_class_attribute_default ....
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 .
5,966
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 .
5,967
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...
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 .
5,968
def state ( * names , & block ) options = names . last . is_a? ( Hash ) ? names . pop : { } options . assert_valid_keys ( :value , :cache , :if , :human_name ) @states . context ( names , & block ) if block_given? if names . first . is_a? ( Matcher ) raise ArgumentError , "Cannot configure states when using matchers (u...
Customizes the definition of one or more states in the machine .
5,969
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 .
5,970
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 .
5,971
def event ( * names , & block ) options = names . last . is_a? ( Hash ) ? names . pop : { } options . assert_valid_keys ( :human_name ) @events . context ( names , & block ) if block_given? if names . first . is_a? ( Matcher ) raise ArgumentError , "Cannot configure events when using matchers (using #{options.inspect})...
Defines one or more events for the machine and the transitions that can be performed when those events are run .
5,972
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 .
5,973
def generate_message ( name , values = [ ] ) message = ( @messages [ name ] || self . class . default_messages [ name ] ) 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
5,974
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 .
5,975
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 af...
5,976
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 .
5,977
def define_path_helpers 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
5,978
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 .
5,979
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 els...
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 .
5,980
def define_name_helpers define_helper ( :class , "human_#{attribute(:name)}" ) do | machine , klass , state | machine . states . fetch ( state ) . human_name ( klass ) end define_helper ( :class , "human_#{attribute(:event_name)}" ) do | machine , klass , event | machine . events . fetch ( event ) . human_name ( klass ...
Adds helper methods for accessing naming information about states and events on the owner class
5,981
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
5,982
def add_sibling_machine_configs 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 .
5,983
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 .
5,984
def add_states ( new_states ) new_states . map do | new_state | 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}; ...
Tracks the given set of states in the list of all known states for this machine
5,985
def add_events ( new_events ) new_events . map do | new_event | 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...
Tracks the given set of events in the list of all known events for this machine
5,986
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 .
5,987
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 op...
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 .
5,988
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 .
5,989
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
5,990
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
5,991
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
5,992
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 .
5,993
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 .
5,994
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
5,995
def method_missing ( * args , & block ) if args . last . is_a? ( Hash ) options = args . last else args << options = { } end if_condition = options . delete ( :if ) unless_condition = options . delete ( :unless ) proxy = self proxy_condition = @condition options [ :if ] = lambda do | * condition_args | object = conditi...
Hooks in condition - merging to methods that don t exist in this module
5,996
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 .
5,997
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 .
5,998
def attribute_transition_for ( object , invalidate = false ) return unless machine . action 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 machine . invalidate ( object , :even...
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 .
5,999
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 )...
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 .