idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,000
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 .
6,001
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 , st...
Marks the object as invalid and runs any failure callbacks associated with this event . This should get called anytime this event fails to transition .
6,002
def add_actions machine . define_helper ( :instance , "can_#{qualified_name}?" ) do | machine , object , * args | machine . event ( name ) . can_fire? ( object , * args ) end machine . define_helper ( :instance , "#{qualified_name}_transition" ) do | machine , object , * args | machine . event ( name ) . transition_for...
Add the various instance methods that can transition the object using the current event
6,003
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 ) ) ...
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 .
6,004
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 .
6,005
def update_index ( name , node ) index = self . index ( name ) old_key = index . key ( node ) new_key = value ( node , name ) 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
6,006
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 .
6,007
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_b...
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 .
6,008
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 .
6,009
def before ( complete = true , index = 0 , & block ) unless @before_run while callback = machine . callbacks [ :before ] [ index ] index += 1 if callback . type == :around return if catch ( :cancel ) do callback . call ( object , context , self ) do before ( complete , index , & block ) pause if @success && ! complete ...
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 .
6,010
def after unless @after_run 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 .
6,011
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 .
6,012
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 .
6,013
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
6,014
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 .
6,015
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
6,016
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
6,017
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
6,018
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 .
6,019
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...
Detects params from url and apply as scopes to your classes .
6,020
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
6,021
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 ) &&...
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 th...
6,022
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
6,023
def recursive_children_removal ( found ) return if found . empty? nodes . tap do | ns | 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
6,024
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 .
6,025
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 .
6,026
def copy_files_build_phase ( name , & block ) phase = CopyFilesBuildPhase . new ( & block ) phase . name = name build_phases << phase phase end
Creates a new Copy Files build phase for the target
6,027
def pre_shell_script_build_phase ( name , script , & block ) phase = ShellScriptBuildPhase . new ( & block ) phase . name = name phase . script = script pinned_build_phases << phase phase end
Creates a new Shell Script build phase for the target before all of the other build phases
6,028
def shell_script_build_phase ( name , script , & block ) phase = ShellScriptBuildPhase . new ( & block ) phase . name = name phase . script = script build_phases << phase phase end
Creates a new Shell Script build phase for the target
6,029
def build_rule ( name , file_type , output_files , output_files_compiler_flags , script , & block ) rule = BuildRule . new ( & block ) rule . name = name rule . file_type = file_type rule . output_files = output_files rule . output_files_compiler_flags = output_files_compiler_flags rule . script = script build_rules <<...
Creates a new build rule for the target
6,030
def configuration ( name , type ) default_settings = default_settings_for_type ( type ) configurations = configurations_of_type ( type ) build_configuration = if name . nil? configurations . first else configurations . detect do | c | c . name == name . to_s end end if build_configuration . nil? name = type . to_s . ca...
This either finds a configuration with the same name and type or creates one .
6,031
def application_for ( platform , deployment_target , language = :objc ) target do | t | t . type = :application t . platform = platform t . deployment_target = deployment_target t . language = language yield ( t ) if block_given? end end
Defines a new application target .
6,032
def extension_for ( host_target ) target = target do | t | t . type = :app_extension t . platform = host_target . platform t . deployment_target = host_target . deployment_target t . language = host_target . language end host_target . target_dependencies << target yield ( target ) if block_given? target end
Defines a extension target .
6,033
def watch_app_for ( host_target , deployment_target , language = :objc ) watch_app_target = target do | t | t . name = "#{host_target.name}-Watch" t . type = :watch2_app t . platform = :watchos t . deployment_target = deployment_target t . language = language end watch_extension_target = target do | t | t . name = "#{h...
Defines targets for watch app .
6,034
def default_system_frameworks_for ( platform ) case platform when :ios %w( Foundation UIKit ) when :osx %w( Cocoa ) when :tvos %w( Foundation UIKit ) when :watchos %w( Foundation UIKit WatchKit ) else abort 'Platform not supported!' end end
Returns an array of default system frameworks to use for a given platform .
6,035
def possible_states col = @stateful_enum . instance_variable_get :@column possible_events . flat_map { | e | e . instance_variable_get ( :@transitions ) [ @model_instance . send ( col ) . to_sym ] . first } end
List of transitionable states from the current state
6,036
def to_local ( time ) raise ArgumentError , 'time must be specified' unless time Timestamp . for ( time ) do | ts | TimestampWithOffset . set_timezone_offset ( ts , period_for ( ts ) . offset ) end end
Converts a time to the local time for the time zone .
6,037
def utc_to_local ( utc_time ) raise ArgumentError , 'utc_time must be specified' unless utc_time Timestamp . for ( utc_time , :treat_as_utc ) do | ts | to_local ( ts ) end end
Converts a time in UTC to the local time for the time zone .
6,038
def local_to_utc ( local_time , dst = Timezone . default_dst ) raise ArgumentError , 'local_time must be specified' unless local_time Timestamp . for ( local_time , :ignore ) do | ts | period = if block_given? period_for_local ( ts , dst ) { | periods | yield periods } else period_for_local ( ts , dst ) end ts . add_an...
Converts a local time for the time zone to UTC .
6,039
def try_with_encoding ( string , encoding ) result = yield string return result if result unless encoding == string . encoding string = string . encode ( encoding ) yield string end end
Tries an operation using string directly . If the operation fails the string is copied and encoded with encoding and the operation is tried again .
6,040
def invisible_captcha ( honeypot = nil , scope = nil , options = { } ) if InvisibleCaptcha . timestamp_enabled session [ :invisible_captcha_timestamp ] = Time . zone . now . iso8601 end build_invisible_captcha ( honeypot , scope , options ) end
Builds the honeypot html
6,041
def fetch ( flag ) o = option ( flag ) if o . nil? cleaned_key = clean_key ( flag ) raise UnknownOption . new ( "option not found: '#{cleaned_key}'" , "#{cleaned_key}" ) else o . value end end
Returns an option s value raises UnknownOption if the option does not exist .
6,042
def []= ( flag , value ) if o = option ( flag ) o . value = value else raise ArgumentError , "no option with flag `#{flag}'" end end
Set the value for an option . Raises an ArgumentError if the option does not exist .
6,043
def option ( flag ) options . find do | o | o . flags . any? { | f | clean_key ( f ) == clean_key ( flag ) } end end
Returns an Option if it exists . Ignores any prefixed hyphens .
6,044
def to_hash Hash [ options . reject ( & :null? ) . map { | o | [ o . key , o . value ] } ] end
Returns a hash with option key = > value .
6,045
def try_process ( flag , arg ) if option = matching_option ( flag ) process ( option , arg ) elsif flag . start_with? ( "--no-" ) && option = matching_option ( flag . sub ( "no-" , "" ) ) process ( option , false ) elsif flag =~ / \A / try_process_smashed_arg ( flag ) || try_process_grouped_flags ( flag , arg ) else if...
Try and find an option to process
6,046
def key key = config [ :key ] || flags . last . sub ( / \A / , '' ) key = key . tr '-' , '_' if underscore_flags? key . to_sym end
Returns the last key as a symbol . Used in Options . to_hash .
6,047
def separator ( string = "" ) if separators [ options . size ] separators [ - 1 ] += "\n#{string}" else separators [ options . size ] = string end end
Add a separator between options . Used when displaying the help text .
6,048
def method_missing ( name , * args , ** config , & block ) if respond_to_missing? ( name ) config [ :type ] = name on ( * args , config , & block ) else super end end
Handle custom option types . Will fall back to raising an exception if an option is not defined .
6,049
def write_summary ( duration , total , failures , pending ) _write do | f | f . puts _message ( total , failures , pending , duration ) f . puts _failed_paths . join ( "\n" ) if failures > 0 end end
Write summary to temporary file for runner
6,050
def run if PryNav . current_remote_server raise 'Already running a pry-remote session!' else PryNav . current_remote_server = self end setup Pry . start @object , { :input => client . input_proxy , :output => client . output , :pry_remote => true } end
Override the call to Pry . start to save off current Server pass a pry_remote flag so pry - nav knows this is a remote session and not kill the server right away
6,051
def pausable begin halted = ! catch ( :halt ) { yield ; true } rescue Exception => error raise unless @resume_block end if @resume_block @resume_block . call ( halted , error ) else halted end end
Runs a block that may get paused . If the block doesn t pause then execution will continue as normal . If the block gets paused then it will take care of switching the execution context when it s resumed .
6,052
def transition ( options ) raise ArgumentError , 'Must specify as least one transition requirement' if options . empty? assert_valid_keys ( options , :from , :to , :except_from , :except_to , :if , :unless ) if ( options . keys - [ :from , :to , :on , :except_from , :except_to , :except_on , :if , :unless ] ) . empty? ...
Creates a new transition that determines what to change the current state to when this event fires .
6,053
def transition ( options ) assert_valid_keys ( options , :from , :to , :on , :if , :unless ) raise ArgumentError , 'Must specify :on event' unless options [ :on ] raise ArgumentError , 'Must specify either :to or :from state' unless ! options [ :to ] ^ ! options [ :from ] machine . transition ( options . merge ( option...
Creates a new context for the given state Creates a new transition that determines what to change the current state to when an event fires from this state .
6,054
def initialize_copy ( orig ) super nodes = @nodes contexts = @contexts @nodes = [ ] @contexts = [ ] @indices = @indices . inject ( { } ) { | indices , ( name , * ) | indices [ name ] = { } ; indices } concat ( nodes . map { | n | n . dup } ) @contexts = contexts . dup end
Creates a new collection of nodes for the given state machine . By default the collection is empty .
6,055
def context ( nodes , & block ) nodes = nodes . first . is_a? ( Matcher ) ? nodes . first : WhitelistMatcher . new ( nodes ) @contexts << context = { :nodes => nodes , :block => block } each { | node | eval_context ( context , node ) } context end
Tracks a context that should be evaluated for any nodes that get added which match the given set of nodes . Matchers can be used so that the context can get added once and evaluated after multiple adds .
6,056
def owner_class = ( klass ) @owner_class = klass @helper_modules = helper_modules = { :instance => HelperModule . new ( self , :instance ) , :class => HelperModule . new ( self , :class ) } owner_class . class_eval do extend helper_modules [ :class ] include helper_modules [ :instance ] end unless owner_class < StateMa...
Sets the class which is the owner of this state machine . Any methods generated by states events or other parts of the machine will be defined on the given owner class .
6,057
def run_methods ( object , context = { } , index = 0 , * args , & block ) if type == :around if current_method = @methods [ index ] yielded = false evaluate_method ( object , current_method , * args ) do yielded = true run_methods ( object , context , index + 1 , * args , & block ) end throw :halt unless yielded else y...
Runs all of the methods configured for this callback .
6,058
def accept @socket = server . accept @messages = { } @driver = :: WebSocket :: Driver . server ( self ) @driver . on ( :connect ) { | _event | @driver . start } @driver . on ( :message ) do | event | command_id = JSON . parse ( event . data ) [ 'command_id' ] @messages [ command_id ] = event . data end end
Accept a client on the TCP server socket then receive its initial HTTP request and use that to initialize a Web Socket .
6,059
def send ( cmd_id , message , accept_timeout = nil ) accept unless connected? driver . text ( message ) receive ( cmd_id , accept_timeout ) rescue Errno :: EWOULDBLOCK raise TimeoutError , message end
Send a message and block until there is a response
6,060
def using_single_table_inheritance? ( klass , record ) inheritance_column = klass . inheritance_column record [ inheritance_column ] . present? && record . has_attribute? ( inheritance_column ) end
Backport for Rails 3 . 2
6,061
def tag ( * tags ) attribute "tags" do | existing_tags | existing_tags ||= [ ] tags . each do | tag | if ! existing_tags . include? ( tag . to_s ) existing_tags << tag . to_s end end existing_tags end end
Patchy tags tag webserver apache myenvironment
6,062
def with_svg ( doc ) doc = Nokogiri :: XML :: Document . parse ( doc . to_html ( encoding : "UTF-8" ) , nil , "UTF-8" ) svg = doc . at_css "svg" yield svg if svg && block_given? doc end
Parses a document and yields the contained SVG nodeset to the given block if it exists .
6,063
def named ( asset_name ) assets [ key_for_asset ( asset_name ) ] or raise InlineSvg :: AssetFile :: FileNotFound . new ( "Asset not found: #{asset_name}" ) end
For each of the given paths recursively reads each asset and stores its contents alongside the full path to the asset .
6,064
def doc_strings_to_utf8 ( obj ) case obj when :: Hash then { } . tap { | new_hash | obj . each do | key , value | new_hash [ key ] = doc_strings_to_utf8 ( value ) end } when Array then obj . map { | item | doc_strings_to_utf8 ( item ) } when String then if obj [ 0 , 2 ] . unpack ( "C*" ) == [ 254 , 255 ] utf16_to_utf8 ...
recursively convert strings from outside a content stream into UTF - 8
6,065
def save_group_four ( filename ) k = stream . hash [ :DecodeParms ] [ :K ] h = stream . hash [ :Height ] w = stream . hash [ :Width ] bpc = stream . hash [ :BitsPerComponent ] mask = stream . hash [ :ImageMask ] len = stream . hash [ :Length ] cols = stream . hash [ :DecodeParms ] [ :Columns ] puts "#{filename}: h=#{h}...
Group 4 2D
6,066
def disabled_for? ( object ) klass = object . class return false unless klass . respond_to? ( :observers ) klass . observers . disabled_for? ( self ) end
Returns true if notifications are disabled for this object .
6,067
def copy ( from ) @scalar = from . scalar @numerator = from . numerator @denominator = from . denominator @base = from . base? @signature = from . signature @base_scalar = from . base_scalar @unit_name = begin from . unit_name rescue nil end self end
Used to copy one unit to another
6,068
def base? return @base if defined? @base @base = ( @numerator + @denominator ) . compact . uniq . map { | unit | RubyUnits :: Unit . definition ( unit ) } . all? { | element | element . unity? || element . base? } @base end
Is this unit in base form?
6,069
def to_base return self if base? if @@unit_map [ units ] =~ / \A \Z / @signature = @@kinds . key ( :temperature ) base = if temperature? convert_to ( 'tempK' ) elsif degree? convert_to ( 'degK' ) end return base end cached = ( begin ( @@base_unit_cache [ units ] * scalar ) rescue nil end ) return cached if cached num =...
convert to base SI units results of the conversion are cached so subsequent calls to this will be fast
6,070
def to_s ( target_units = nil ) out = @output [ target_units ] return out if out separator = RubyUnits . configuration . separator case target_units when :ft inches = convert_to ( 'in' ) . scalar . to_int out = "#{(inches / 12).truncate}\'#{(inches % 12).round}\"" when :lbs ounces = convert_to ( 'oz' ) . scalar . to_in...
Generate human readable output . If the name of a unit is passed the unit will first be converted to the target unit before output . some named conversions are available
6,071
def =~ ( other ) case other when Unit signature == other . signature else begin x , y = coerce ( other ) return x =~ y rescue ArgumentError return false end end end
Compare two Unit objects . Throws an exception if they are not of compatible types . Comparisons are done based on the value of the unit in base SI units .
6,072
def + ( other ) case other when Unit if zero? other . dup elsif self =~ other raise ArgumentError , 'Cannot add two temperatures' if [ self , other ] . all? ( & :temperature? ) if [ self , other ] . any? ( & :temperature? ) if temperature? RubyUnits :: Unit . new ( scalar : ( scalar + other . convert_to ( temperature_s...
Add two units together . Result is same units as receiver and scalar and base_scalar are updated appropriately throws an exception if the units are not compatible . It is possible to add Time objects to units of time
6,073
def * ( other ) case other when Unit raise ArgumentError , 'Cannot multiply by temperatures' if [ other , self ] . any? ( & :temperature? ) opts = RubyUnits :: Unit . eliminate_terms ( @scalar * other . scalar , @numerator + other . numerator , @denominator + other . denominator ) opts [ :signature ] = @signature + oth...
Multiply two units .
6,074
def / ( other ) case other when Unit raise ZeroDivisionError if other . zero? raise ArgumentError , 'Cannot divide with temperatures' if [ other , self ] . any? ( & :temperature? ) sc = Rational ( @scalar , other . scalar ) sc = sc . numerator if sc . denominator == 1 opts = RubyUnits :: Unit . eliminate_terms ( sc , @...
Divide two units . Throws an exception if divisor is 0
6,075
def divmod ( other ) raise ArgumentError , "Incompatible Units ('#{self}' not compatible with '#{other}')" unless self =~ other return scalar . divmod ( other . scalar ) if units == other . units to_base . scalar . divmod ( other . to_base . scalar ) end
divide two units and return quotient and remainder when both units are in the same units we just use divmod on the raw scalars otherwise we use the scalar of the base unit which will be a float
6,076
def ** ( other ) raise ArgumentError , 'Cannot raise a temperature to a power' if temperature? if other . is_a? ( Numeric ) return inverse if other == - 1 return self if other == 1 return 1 if other . zero? end case other when Rational return power ( other . numerator ) . root ( other . denominator ) when Integer retur...
Exponentiate . Only takes integer powers . Note that anything raised to the power of 0 results in a Unit object with a scalar of 1 and no units . Throws an exception if exponent is not an integer . Ideally this routine should accept a float for the exponent It should then convert the float to a rational and raise the u...
6,077
def power ( n ) raise ArgumentError , 'Cannot raise a temperature to a power' if temperature? raise ArgumentError , 'Exponent must an Integer' unless n . is_a? ( Integer ) return inverse if n == - 1 return 1 if n . zero? return self if n == 1 return ( 1 .. ( n - 1 ) . to_i ) . inject ( self ) { | acc , _elem | acc * se...
returns the unit raised to the n - th power
6,078
def units ( with_prefix : true ) return '' if @numerator == UNITY_ARRAY && @denominator == UNITY_ARRAY output_numerator = [ '1' ] output_denominator = [ ] num = @numerator . clone . compact den = @denominator . clone . compact unless num == UNITY_ARRAY definitions = num . map { | element | RubyUnits :: Unit . definitio...
returns the unit part of the Unit object without the scalar
6,079
def coerce ( other ) return [ other . to_unit , self ] if other . respond_to? :to_unit case other when Unit [ other , self ] else [ RubyUnits :: Unit . new ( other ) , self ] end end
automatically coerce objects to units when possible if an object defines a to_unit method it will be coerced using that method
6,080
def best_prefix return to_base if scalar . zero? best_prefix = if kind == :information @@prefix_values . key ( 2 ** ( ( Math . log ( base_scalar , 2 ) / 10.0 ) . floor * 10 ) ) else @@prefix_values . key ( 10 ** ( ( Math . log10 ( base_scalar ) / 3.0 ) . floor * 3 ) ) end to ( RubyUnits :: Unit . new ( @@prefix_map . k...
returns a new unit that has been scaled to be more in line with typical usage .
6,081
def unit_signature_vector return to_base . unit_signature_vector unless base? vector = Array . new ( SIGNATURE_VECTOR . size , 0 ) @numerator . map { | element | RubyUnits :: Unit . definition ( element ) } . each do | definition | index = SIGNATURE_VECTOR . index ( definition . kind ) vector [ index ] += 1 if index en...
calculates the unit signature vector used by unit_signature
6,082
def unit_signature return @signature unless @signature . nil? vector = unit_signature_vector vector . each_with_index { | item , index | vector [ index ] = item * 20 ** index } @signature = vector . inject ( 0 ) { | acc , elem | acc + elem } @signature end
calculates the unit signature id for use in comparing compatible units and simplification the signature is based on a simple classification of units and is based on the following publication
6,083
def parent_class_name ( obj ) unless DEFAULT_PARENTS . include? obj . class . superclass return obj . class . base_class . name end obj . class . name end
Retrieves the parent class name if using STI .
6,084
def with ( options = nil , & block ) adapter = self if block builder = Builder . new ( & block ) builder . adapter ( adapter ) adapter = builder . build . last end options ? OptionMerger . new ( adapter , options ) : adapter end
Return Moneta store with default options or additional proxies
6,085
def fetch ( key , default = nil , options = nil ) if block_given? raise ArgumentError , 'Only one argument accepted if block is given' if options result = load ( key , default || { } ) result == nil ? yield ( key ) : result else result = load ( key , options || { } ) result == nil ? default : result end end
Fetch a value with a key
6,086
def slice ( * keys , ** options ) keys . zip ( values_at ( * keys , ** options ) ) . reject do | _ , value | value == nil end end
Returns a collection of key - value pairs corresponding to those supplied keys which are present in the key - value store and their associated values . Only those keys present in the store will have pairs in the return value . The return value can be any enumerable object that yields pairs so it could be a hash but nee...
6,087
def expires_at ( options , default = @default_expires ) value = expires_value ( options , default ) Numeric === value ? Time . now + value : value end
Calculates the time when something will expire .
6,088
def expires_value ( options , default = @default_expires ) case value = options [ :expires ] when 0 , false false when nil default ? default . to_r : nil when Numeric value = value . to_r raise ArgumentError , ":expires must be a positive value, got #{value}" if value < 0 value else raise ArgumentError , ":expires must...
Calculates the number of seconds something should last .
6,089
def use ( proxy , options = { } , & block ) proxy = Moneta . const_get ( proxy ) if Symbol === proxy raise ArgumentError , 'You must give a Class or a Symbol' unless Class === proxy @proxies . unshift [ proxy , options , block ] nil end
Add proxy to stack
6,090
def adapter ( adapter , options = { } , & block ) case adapter when Symbol use ( Adapters . const_get ( adapter ) , options , & block ) when Class use ( adapter , options , & block ) else raise ArgumentError , 'Adapter must be a Moneta store' unless adapter . respond_to? ( :load ) && adapter . respond_to? ( :store ) ra...
Add adapter to stack
6,091
def run raise 'Already running' if @running @stop = false @running = true begin until @stop mainloop end ensure File . unlink ( @socket ) if @socket @ios . each { | io | io . close rescue nil } end end
Run the server
6,092
def handle ( indicator , code , tailch , rspace , lspace ) case indicator when '|=' , '|==' rspace = nil if tailch && ! tailch . empty? add_text ( lspace ) if lspace escape_capture = ! ( ( indicator == '|=' ) ^ @escape_capture ) src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.l...
Handle the <%| = and <%| == tags
6,093
def open ( store_name ) certstore_handler = CertOpenStore ( CERT_STORE_PROV_SYSTEM , 0 , nil , CERT_SYSTEM_STORE_LOCAL_MACHINE , wstring ( store_name ) ) unless certstore_handler last_error = FFI :: LastError . error raise SystemCallError . new ( "Unable to open the Certificate Store `#{store_name}`." , last_error ) en...
To open certstore and return open certificate store pointer
6,094
def empty_exp? ( exp ) case exp [ 0 ] when :multi exp [ 1 .. - 1 ] . all? { | e | empty_exp? ( e ) } when :newline true else false end end
Check if expression is empty
6,095
def loggers_to_close loggers_to_close = [ ] all_loggers . each do | logger | next unless ( logdev = logger . instance_variable_get ( :" " ) ) loggers_to_close << logger if logdev . filename end loggers_to_close end
select all loggers with File log devices
6,096
def normalize_json ( json ) json = json . to_json unless json . is_a? ( String ) JSON . parse ( json ) end
normalizes datetime objects to strings etc . more similar to what the client would see .
6,097
def active? ( feature , repository ) feature_active? ( feature ) or ( rollout . active? ( feature , repository . owner ) or repository_active? ( feature , repository ) ) end
Returns whether a given feature is enabled either globally or for a given repository .
6,098
def owner_active? ( feature , owner ) redis . sismember ( owner_key ( feature , owner ) , owner . id ) end
Return whether a feature has been enabled for a user .
6,099
def exclusive ( timeout = 30 ) give_up_at = Time . now + timeout if timeout while timeout . nil? || Time . now < give_up_at do if obtained_lock? return yield else sleep ( rand ( 0.1 .. 0.2 ) ) end end ensure release_lock unless transactional end
must be used within a transaction