idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
4,900
def to_hash { :name => repository . name , :status => status , :sha1 => ( current_build && current_build . sha1 ) , :compare => ( current_build && current_build . compare ) } end
Hash representation of this branch status .
4,901
def job_name md5 = Digest :: MD5 . new md5 << name md5 << uri md5 << job_config_path . read md5 << builder . callback_url . to_s "#{name}-#{md5.hexdigest[0,12]}" end
Calculate the name of the Jenkins job .
4,902
def rerun ( new_room_id = nil ) build = branch . build_for ( commit , new_room_id ) build . run build end
Run a copy of itself . Typically used to force a build in case of temporary test failure or when auto - build is disabled .
4,903
def start ( url , now ) if started? raise Error , "Build #{id} already started" elsif completed? raise Error , "Build #{id} already completed" else update_attributes! ( :url => url , :started_at => now ) Notifier . started ( self ) end end
Mark the build as started .
4,904
def complete ( green , now ) if ! started? raise Error , "Build #{id} not started" elsif completed? raise Error , "Build #{id} already completed" else update_attributes! ( :green => green , :completed_at => now , :output => output_remote ) Notifier . completed ( self ) end end
Mark the build as complete store the build output and notify Campfire .
4,905
def solved_keys if Array === env versions = env . map { | single_env | single_env [ "application_version" ] } else versions = env [ "application_version" ] end if versions && backtrace && backtrace . length > 0 versions = [ versions ] if String === versions versions . map do | version | Digest :: SHA1 . hexdigest "#{ve...
todo - memoize?
4,906
def datagrid_rows ( grid , assets = grid . assets , ** options , & block ) datagrid_renderer . rows ( grid , assets , options , & block ) end
Renders HTML table rows using given grid definition using columns defined in it . Allows to provide a custom layout for each for in place with a block
4,907
def datagrid_row ( grid , asset , & block ) HtmlRow . new ( self , grid , asset ) . tap do | row | if block_given? return capture ( row , & block ) end end end
Provides access to datagrid columns data .
4,908
def datagrid_order_path ( grid , column , descending ) datagrid_renderer . order_path ( grid , column , descending , request ) end
Generates an ascending or descending order url for the given column
4,909
def datagrid_filter ( filter_or_attribute , options = { } , & block ) filter = datagrid_get_filter ( filter_or_attribute ) options = add_html_classes ( options , filter . name , datagrid_filter_html_class ( filter ) ) options . delete ( :partials ) self . send ( filter . form_builder_helper_name , filter , options , & ...
Returns a form input html for the corresponding filter name
4,910
def datagrid_label ( filter_or_attribute , options_or_text = { } , options = { } , & block ) filter = datagrid_get_filter ( filter_or_attribute ) text , options = options_or_text . is_a? ( Hash ) ? [ filter . header , options_or_text ] : [ options_or_text , options ] label ( filter . name , text , options , & block ) e...
Returns a form label html for the corresponding filter name
4,911
def _ ( expr ) expr = Arel . sql ( expr . to_sql ) if expr . is_a? :: ActiveRecord :: Relation Nodes . wrap Arel :: Nodes :: Grouping . new ( expr ) end
Create a Grouping node . This allows you to set balanced pairs of parentheses around your SQL .
4,912
def set_current_tenant_by_subdomain ( tenant = :account , column = :subdomain ) self . class_eval do cattr_accessor :tenant_class , :tenant_column end self . tenant_class = tenant . to_s . camelcase . constantize self . tenant_column = column . to_sym self . class_eval do before_action :find_tenant_by_subdomain helper_...
this method allows setting the current_tenant by reading the subdomain and looking it up in the tenant - model passed to the method . The method will look for the subdomain in a column referenced by the second argument .
4,913
def set_current_tenant_through_filter self . class_eval do helper_method :current_tenant if respond_to? ( :helper_method ) private def set_current_tenant ( current_tenant_object ) ActsAsTenant . current_tenant = current_tenant_object end def current_tenant ActsAsTenant . current_tenant end end end
This method sets up a method that allows manual setting of the current_tenant . This method should be used in a before_action . In addition a helper is setup that returns the current_tenant
4,914
def condition ( kind ) begin c = Condition . generate ( kind , self . watch ) rescue NoSuchConditionError => e abort e . message end yield ( c ) if block_given? c . prepare unless Condition . valid? ( c ) && c . valid? abort "Exiting on invalid condition" end if c . kind_of? ( PollCondition ) && ! c . interval if self ...
Initialize a new Metric .
4,915
def start begin @drb ||= DRb . start_service ( self . socket , self ) applog ( nil , :info , "Started on #{DRb.uri}" ) rescue Errno :: EADDRINUSE applog ( nil , :info , "Socket already in use" ) server = DRbObject . new ( nil , self . socket ) begin Timeout . timeout ( 5 ) do server . ping end abort "Socket #{self.sock...
Start the DRb server . Abort if there is already a running god instance on the socket .
4,916
def valid? valid = true if self . name . nil? valid = false applog ( self , :error , "No name String was specified." ) end if self . valid_states . nil? valid = false applog ( self , :error , "No valid_states Array or Symbols was specified." ) end if self . initial_state . nil? valid = false applog ( self , :error , "N...
Verify that the minimum set of configuration requirements has been met .
4,917
def move ( to_state ) if ! self . driver . in_driver_context? self . driver . message ( :move , [ to_state ] ) else orig_to_state = to_state from_state = self . state msg = "#{self.name} move '#{from_state}' to '#{to_state}'" applog ( self , :info , msg ) self . driver . clear_events self . metrics [ from_state ] . eac...
Move to the given state .
4,918
def action ( a , c = nil ) if ! self . driver . in_driver_context? self . driver . message ( :action , [ a , c ] ) else if self . respond_to? ( a ) command = self . send ( a ) case command when String msg = "#{self.name} #{a}: #{command}" applog ( self , :info , msg ) system ( command ) when Proc msg = "#{self.name} #{...
Perform the given action .
4,919
def handle_event ( condition ) metric = self . directory [ condition ] messages = self . log_line ( self , metric , condition , true ) if condition . notify self . notify ( condition , messages . last ) end dest = if condition . transition condition . transition else metric . destination && metric . destination [ true ...
Asynchronously evaluate and handle the given event condition . Handles logging notifications and moving to the new state if necessary .
4,920
def log_line ( watch , metric , condition , result ) status = if self . trigger? ( metric , result ) "[trigger]" else "[ok]" end messages = [ ] if condition . info Array ( condition . info ) . each do | condition_info | messages << "#{watch.name} #{status} #{condition_info} (#{condition.base_name})" applog ( watch , :i...
Log info about the condition and return the list of messages logged .
4,921
def dest_desc ( metric , condition ) if condition . transition { true => condition . transition } . inspect else if metric . destination metric . destination . inspect else 'none' end end end
Format the destination specification for use in debug logging .
4,922
def notify ( condition , message ) spec = Contact . normalize ( condition . notify ) unmatched = [ ] resolved_contacts = spec [ :contacts ] . inject ( [ ] ) do | acc , contact_name_or_group | cons = Array ( God . contacts [ contact_name_or_group ] || God . contact_groups [ contact_name_or_group ] ) unmatched << contact...
Notify all recipients of the given condition with the specified message .
4,923
def level = ( lev ) SysLogger . level = SimpleLogger :: CONSTANT_TO_SYMBOL [ lev ] if Logger . syslog super ( lev ) end
Instantiate a new Logger object
4,924
def watch_log_since ( watch_name , since ) self . logs [ watch_name ] ||= Timeline . new ( God :: LOG_BUFFER_SIZE_DEFAULT ) @mutex . synchronize do @spool = Time . now self . logs [ watch_name ] . select do | x | x . first > since end . map do | x | x [ 1 ] end . join end end
Get all log output for a given Watch since a certain Time . + watch_name + is the String name of the Watch + since + is the Time since which to fetch log lines
4,925
def pid contents = File . read ( self . pid_file ) . strip rescue '' real_pid = contents =~ / \d / ? contents . to_i : nil if real_pid @pid = real_pid real_pid else @pid end end
Fetch the PID from pid_file . If the pid_file does not exist then use the PID from the last time it was read . If it has never been read then return nil .
4,926
def signal ( sig ) sig = sig . to_i if sig . to_i != 0 applog ( self , :info , "#{self.name} sending signal '#{sig}' to pid #{self.pid}" ) :: Process . kill ( sig , self . pid ) rescue nil end
Send the given signal to this process .
4,927
def ensure_stop applog ( self , :warn , "#{self.name} ensuring stop..." ) unless self . pid applog ( self , :warn , "#{self.name} stop called but pid is uknown" ) return end @stop_timeout . times do begin :: Process . kill ( 0 , self . pid ) rescue Errno :: ESRCH return end sleep 1 end :: Process . kill ( 'KILL' , self...
Ensure that a stop command actually stops the process . Force kill if necessary .
4,928
def pop @monitor . synchronize do if @events . empty? raise ThreadError , "queue empty" if @shutdown @resource . wait else delay = @events . first . at - Time . now @resource . wait ( delay ) if delay > 0 end @events . shift end end
Wait until the queue has something due pop it off the queue and return it .
4,929
def schedule ( condition , delay = condition . interval ) applog ( nil , :debug , "driver schedule #{condition} in #{delay} seconds" ) @events . push ( DriverEvent . new ( delay , @task , condition ) ) end
Create and schedule a new DriverEvent .
4,930
def call_action ( condition , action ) before_items = self . behaviors before_items += [ condition ] if condition before_items . each do | b | info = b . send ( "before_#{action}" ) if info msg = "#{self.name} before_#{action}: #{info} (#{b.base_name})" applog ( self , :info , msg ) end end if self . send ( action ) ms...
Perform the specifics of the action .
4,931
def collection get_collection_ivar || begin c = end_of_association_chain set_collection_ivar ( c . respond_to? ( :scoped ) ? c . scoped : c . all ) end end
This is how the collection is loaded .
4,932
def end_of_association_chain if chain = association_chain . last if method_for_association_chain apply_scopes_if_available ( chain . send ( method_for_association_chain ) ) else chain end else apply_scopes_if_available ( resource_class ) end end
This methods gets your begin_of_association_chain join it with your parents chain and returns the scoped association .
4,933
def smart_collection_url url = nil if respond_to? :index url ||= collection_url rescue nil end if respond_to? :parent , true url ||= parent_url rescue nil end url ||= root_url rescue nil end
URL to redirect to when redirect implies collection url .
4,934
def build_resource_params parameters = permitted_params || params rparams = [ parameters [ resource_request_name ] || parameters [ resource_instance_name ] || { } ] if without_protection_given? rparams << without_protection else rparams << as_role if role_given? end rparams end
extract attributes from params
4,935
def actions ( * actions_to_keep ) raise ArgumentError , 'Wrong number of arguments. You have to provide which actions you want to keep.' if actions_to_keep . empty? options = actions_to_keep . extract_options! actions_to_remove = Array ( options [ :except ] ) actions_to_remove += ACTIONS - actions_to_keep . map { | a |...
Defines wich actions will be inherited from the inherited controller . Syntax is borrowed from resource_controller .
4,936
def polymorphic_belongs_to ( * symbols , & block ) options = symbols . extract_options! options . merge! ( polymorphic : true ) belongs_to ( * symbols , options , & block ) end
A quick method to declare polymorphic belongs to .
4,937
def singleton_belongs_to ( * symbols , & block ) options = symbols . extract_options! options . merge! ( singleton : true ) belongs_to ( * symbols , options , & block ) end
A quick method to declare singleton belongs to .
4,938
def optional_belongs_to ( * symbols , & block ) options = symbols . extract_options! options . merge! ( optional : true ) belongs_to ( * symbols , options , & block ) end
A quick method to declare optional belongs to .
4,939
def custom_actions ( options ) self . resources_configuration [ :self ] [ :custom_actions ] = options options . each do | resource_or_collection , actions | [ * actions ] . each do | action | create_custom_action ( resource_or_collection , action ) end end create_resources_url_helpers! [ * options [ :resource ] ] . eac...
Defines custom restful actions by resource or collection basis .
4,940
def initialize_resources_class_accessors! self . resource_class ||= begin namespaced_class = self . name . sub ( / / , '' ) . singularize namespaced_class . constantize rescue NameError nil end self . resource_class ||= begin namespaced_classes = self . name . sub ( / / , '' ) . split ( '::' ) namespaced_class = [ name...
Initialize resources class accessors and set their default values .
4,941
def symbols_for_association_chain polymorphic_config = resources_configuration [ :polymorphic ] parents_symbols . map do | symbol | if symbol == :polymorphic params_keys = params . keys keys = polymorphic_config [ :symbols ] . map do | poly | params_keys . include? ( resources_configuration [ poly ] [ :param ] . to_s )...
Maps parents_symbols to build association chain .
4,942
def authorization_url ( requested_scopes = [ "public" ] ) @oauth . auth_code . authorize_url ( redirect_uri : Unsplash . configuration . application_redirect_uri , scope : requested_scopes . join ( " " ) ) end
Create a Connection object .
4,943
def reload! if links && links [ "self" ] attrs = JSON . parse ( connection . get ( links [ "self" ] ) . body ) @attributes = OpenStruct . new ( attrs ) self else raise Unsplash :: Error . new "Missing self link for #{self.class} with ID #{self.id}" end end
Build an Unsplash object with the given attributes .
4,944
def photos ( page = 1 , per_page = 10 ) params = { page : page , per_page : per_page } list = JSON . parse ( connection . get ( "/users/#{username}/photos" , params ) . body ) list . map do | photo | Unsplash :: Photo . new photo . to_hash end end
Get a list of photos uploaded by the user .
4,945
def collections ( page = 1 , per_page = 10 ) params = { page : page , per_page : per_page } list = JSON . parse ( connection . get ( "/users/#{username}/collections" , params ) . body ) list . map do | collection | Unsplash :: Collection . new collection . to_hash end end
Get a list of collections created by the user .
4,946
def update ( title : nil , description : nil , private : nil ) params = { title : title , description : description , private : private } . select { | k , v | v } updated = JSON . parse ( connection . put ( "/collections/#{id}" , params ) . body ) self . title = updated [ "title" ] self . description = updated [ "descr...
Update the collection s attributes .
4,947
def add ( photo ) response = JSON . parse ( connection . post ( "/collections/#{id}/add" , { photo_id : photo . id } ) . body ) { photo_id : response [ "photo" ] [ "id" ] , collection_id : response [ "collection" ] [ "id" ] , user_id : response [ "user" ] [ "id" ] , created_at : response [ "created_at" ] } end
Add a photo to the collection . If the photo is already in the collection this action has no effect .
4,948
def remove ( photo ) response = connection . delete ( "/collections/#{id}/remove" , photo_id : photo . id ) ( 200 .. 299 ) . include? ( response . status ) end
Remove a photo from the collection . If the photo is not in the collection this action has no effect .
4,949
def drop_seconds h = @h . dup h . delete ( :sec ) h [ :min ] = 0 if h . empty? self . class . allocate . init ( nil , { literal : true } , h ) end
Returns a copy of this duration omitting its seconds .
4,950
def rucaptcha_sesion_key_key session_id = session . respond_to? ( :id ) ? session . id : session [ :session_id ] warning_when_session_invalid if session_id . blank? [ 'rucaptcha-session' , session_id ] . join ( ':' ) end
session key of rucaptcha
4,951
def generate_rucaptcha res = RuCaptcha . generate ( ) session_val = { code : res [ 0 ] , time : Time . now . to_i } RuCaptcha . cache . write ( rucaptcha_sesion_key_key , session_val , expires_in : RuCaptcha . config . expires_in ) res [ 1 ] end
Generate a new Captcha
4,952
def verify_rucaptcha? ( resource = nil , opts = { } ) opts ||= { } store_info = RuCaptcha . cache . read ( rucaptcha_sesion_key_key ) RuCaptcha . cache . delete ( rucaptcha_sesion_key_key ) unless opts [ :keep_session ] if store_info . blank? return add_rucaptcha_validation_error end if ( Time . now . to_i - store_info...
Verify captcha code
4,953
def generate cert = OpenSSL :: X509 :: Certificate . new configure ( cert ) add_extensions ( cert ) cert . sign ( key , OpenSSL :: Digest :: SHA256 . new ) end
Generate a fresh new certificate for the configured domain .
4,954
def file contents = certificates . map { | cert | cert . to_pem } . join write_file ( "chain-#{domain}.pem" , contents ) end
Just pass all certificates into the new instance . We use the variadic argument feature here to ease the usage and improve the readability .
4,955
def connection_pool_name name = current_shard_selection . shard_name ( self ) if configurations [ name ] . nil? && on_slave? current_shard_selection . shard_name ( self , false ) else name end end
Name of the connection pool . Used by ConnectionHandler to retrieve the current connection pool .
4,956
def declare! ( inst , * args , & block ) _indent @target << "<!#{inst}" args . each do | arg | case arg when :: String @target << %{ "#{arg}"} when :: Symbol @target << " #{arg}" end end if :: Kernel :: block_given? @target << " [" _newline _nested_structures ( block ) @target << "]" end @target << ">" _newline end
Insert an XML declaration into the XML markup .
4,957
def instruct! ( directive_tag = :xml , attrs = { } ) _ensure_no_block :: Kernel :: block_given? if directive_tag == :xml a = { :version => "1.0" , :encoding => "UTF-8" } attrs = a . merge attrs @encoding = attrs [ :encoding ] . downcase end _special ( "<?#{directive_tag}" , "?>" , nil , attrs , [ :version , :encoding ,...
Insert a processing instruction into the XML markup . E . g .
4,958
def _special ( open , close , data = nil , attrs = nil , order = [ ] ) _indent @target << open @target << data if data _insert_attributes ( attrs , order ) if attrs @target << close _newline end
Insert special instruction .
4,959
def method_missing ( sym , * args , & block ) cache_method_call ( sym ) if :: Builder :: XmlBase . cache_method_calls tag! ( sym , * args , & block ) end
Create XML markup based on the name of the method . This method is never invoked directly but is called for each markup method in the markup block that isn t cached .
4,960
def cache_method_call ( sym ) class << self ; self ; end . class_eval do unless method_defined? ( sym ) define_method ( sym ) do | * args , & block | tag! ( sym , * args , & block ) end end end end
If XmlBase . cache_method_calls = true we dynamicly create the method missed as an instance method on the XMLBase object . Because XML documents are usually very repetative in nature the next node will be handled by the new method instead of method_missing . As method_missing is very slow this speeds up document genera...
4,961
def render_to_file ( output_path , context , properties = { } ) File . open ( output_path , 'wb' ) do | f | f . write render_to_string ( context , properties ) end end
Same as + render_to_string + but writes the processed template to + output_path + .
4,962
def register_html_tag ( tag_name , type = :inline , ** options ) tag = HTMLTag . new ( tag_name , type , ** options ) @permitted_html_tags [ tag . name ] = tag end
Adds a new tag to the permitted tags hash or replaces an existing one
4,963
def pool_link ( klass , config = { } , & block ) Supervision :: Container :: Pool . new_link ( pooling_options ( config , block : block , actors : klass ) ) end
Same as pool but links to the pool manager
4,964
def new_link ( * args , & block ) raise NotActorError , "can't link outside actor context" unless Celluloid . actor? proxy = Cell . new ( allocate , behavior_options , actor_options ) . proxy Actor . link ( proxy ) proxy . _send_ ( :initialize , * args , & block ) proxy end
Create a new actor and link to the current one
4,965
def wait ( timeout = nil ) raise ConditionError , "cannot wait for signals while exclusive" if Celluloid . exclusive? if actor = Thread . current [ :celluloid_actor ] task = Task . current if timeout bt = caller timer = actor . timers . after ( timeout ) do exception = ConditionError . new ( "timeout after #{timeout.in...
Wait for the given signal and return the associated value
4,966
def signal ( value = nil ) @mutex . synchronize do if waiter = @waiters . shift waiter << SignalConditionRequest . new ( waiter . task , value ) else Internals :: Logger . with_backtrace ( caller ( 3 ) ) do | logger | logger . debug ( "Celluloid::Condition signaled spuriously" ) end end end end
Send a signal to the first task waiting on this condition
4,967
def broadcast ( value = nil ) @mutex . synchronize do @waiters . each { | waiter | waiter << SignalConditionRequest . new ( waiter . task , value ) } @waiters . clear end end
Broadcast a value to all waiting tasks and threads
4,968
def execute ( receiver , method , args , block ) @mutex . synchronize do raise "already calling" if @call @call = Call :: Sync . new ( self , method , args , block ) end receiver << @call end
Execute the given method in future context
4,969
def value ( timeout = nil ) ready = result = nil begin @mutex . lock if @ready ready = true result = @result else case @forwards when Array @forwards << Celluloid . mailbox when NilClass @forwards = Celluloid . mailbox else @forwards = [ @forwards , Celluloid . mailbox ] end end ensure @mutex . unlock end unless ready ...
Obtain the value for this Future
4,970
def signal ( value ) return if @cancelled result = Result . new ( value , self ) @mutex . synchronize do raise "the future has already happened!" if @ready if @forwards @forwards . is_a? ( Array ) ? @forwards . each { | f | f << result } : @forwards << result end @result = result @ready = true end end
Signal this future with the given result value
4,971
def run while @running begin @timers . wait do | interval | interval = 0 if interval && interval < 0 if message = @mailbox . check ( interval ) handle_message ( message ) break unless @running end end rescue MailboxShutdown @running = false rescue MailboxDead @running = false end end shutdown rescue :: Exception => ex ...
Run the actor loop
4,972
def linking_request ( receiver , type ) Celluloid . exclusive do receiver . mailbox << LinkingRequest . new ( Actor . current , type ) system_events = [ ] Timers :: Wait . for ( LINKING_TIMEOUT ) do | remaining | begin message = @mailbox . receive ( remaining ) do | msg | msg . is_a? ( LinkingResponse ) && msg . actor ...
Perform a linking request with another actor
4,973
def receive ( timeout = nil , & block ) loop do message = @receivers . receive ( timeout , & block ) return message unless message . is_a? ( SystemEvent ) handle_system_event ( message ) end end
Receive an asynchronous message
4,974
def handle_message ( message ) Internals :: Logger . debug "Discarded message (unhandled): #{message}" if ! @handlers . handle_message ( message ) && ! @receivers . handle_message ( message ) && $CELLULOID_DEBUG message end
Handle standard low - priority messages
4,975
def handle_crash ( exception ) Internals :: Logger . crash ( "Actor crashed!" , exception ) shutdown ExitEvent . new ( behavior_proxy , exception ) rescue => ex Internals :: Logger . crash ( "Actor#handle_crash CRASHED!" , ex ) end
Handle any exceptions that occur within a running actor
4,976
def shutdown ( exit_event = ExitEvent . new ( behavior_proxy ) ) @behavior . shutdown cleanup exit_event ensure Thread . current [ :celluloid_actor ] = nil Thread . current [ :celluloid_mailbox ] = nil end
Handle cleaning up this actor after it exits
4,977
def cleanup ( exit_event ) Celluloid :: Probe . actor_died ( self ) if $CELLULOID_MONITORING @mailbox . shutdown @links . each do | actor | actor . mailbox << exit_event if actor . mailbox . alive? end tasks . to_a . each do | task | begin task . terminate rescue DeadTaskError end end rescue => ex Internals :: Logger ....
Clean up after this actor
4,978
def suspend ( status ) raise "Cannot suspend while in exclusive mode" if exclusive? raise "Cannot suspend a task from outside of itself" unless Task . current == self @status = status if $CELLULOID_DEBUG && @dangerous_suspend Internals :: Logger . with_backtrace ( caller [ 2 ... 8 ] ) do | logger | logger . warn "Dange...
Suspend the current task changing the status to the given argument
4,979
def resume ( value = nil ) guard "Cannot resume a task from inside of a task" if Thread . current [ :celluloid_task ] if running? deliver ( value ) else Internals :: Logger . warn "Attempted to resume a dead task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.inspect}" end nil end
Resume a suspended task giving it a value to return if needed
4,980
def terminate raise "Cannot terminate an exclusive task" if exclusive? if running? if $CELLULOID_DEBUG Internals :: Logger . with_backtrace ( backtrace ) do | logger | type = @dangerous_suspend ? :warn : :debug logger . send ( type , "Terminating task: type=#{@type.inspect}, meta=#{@meta.inspect}, status=#{@status.insp...
Terminate this task
4,981
def shutdown return unless @finalizer && @subject . respond_to? ( @finalizer , true ) task ( :finalizer , @finalizer , { call : @finalizer , subject : @subject } , dangerous_suspend : true , & Cell . shutdown ) end
Run the user - defined finalizer if one is set
4,982
def << ( message ) @mutex . lock begin if mailbox_full || @dead dead_letter ( message ) return end if message . is_a? ( SystemEvent ) @messages . unshift message else @messages << message end @condition . signal nil ensure begin @mutex . unlock rescue nil end end end
Add a message to the Mailbox
4,983
def check ( timeout = nil , & block ) message = nil @mutex . lock begin raise MailboxDead , "attempted to receive from a dead mailbox" if @dead message = nil Timers :: Wait . for ( timeout ) do | remaining | message = next_message ( & block ) break if message @condition . wait ( @mutex , remaining ) end ensure begin @m...
Receive a message from the Mailbox . May return nil and may return before the specified timeout .
4,984
def receive ( timeout = nil , & block ) message = nil Timers :: Wait . for ( timeout ) do | _remaining | message = check ( timeout , & block ) break if message end return message if message raise TaskTimeout , "receive timeout exceeded" end
Receive a letter from the mailbox . Guaranteed to return a message . If timeout is exceeded raise a TaskTimeout .
4,985
def shutdown raise MailboxDead , "mailbox already shutdown" if @dead @mutex . lock begin yield if block_given? messages = @messages @messages = [ ] @dead = true ensure begin @mutex . unlock rescue nil end end messages . each do | msg | dead_letter msg msg . cleanup if msg . respond_to? :cleanup end true end
Shut down this mailbox and clean up its contents
4,986
def next_message message = nil if block_given? index = @messages . index do | msg | yield ( msg ) || msg . is_a? ( SystemEvent ) end message = @messages . slice! ( index , 1 ) . first if index else message = @messages . shift end message end
Retrieve the next message in the mailbox
4,987
def merge ( * other_incidents ) merged_events = other_incidents . flatten . inject ( events ) do | events , incident | events += incident . events end Incident . new ( merged_events . sort , triggering_event ) end
Merge two incidents together . This may be useful if two incidents occur at the same time .
4,988
def handle_system_event ( event ) if handler = SystemEvent . handle ( event . class ) send ( handler , event ) else Internals :: Logger . debug "Discarded message (unhandled): #{message}" if $CELLULOID_DEBUG end end
Handle high - priority system event messages
4,989
def add ( severity , message = nil , progname = nil , & block ) progname ||= @progname severity ||= UNKNOWN return event . id if severity < @level if message . nil? && ! block_given? message = progname progname = @progname end event = LogEvent . new ( severity , message , progname , & block ) @buffers [ progname ] [ se...
Create a new IncidentLogger . add an event .
4,990
def decrypt payload , armor = false return unknown_status ( @not_working_reason ) unless @not_working_reason . nil? gpg_opts = { :protocol => GPGME :: PROTOCOL_OpenPGP } gpg_opts = HookManager . run ( "gpg-options" , { :operation => "decrypt" , :options => gpg_opts } ) || gpg_opts ctx = GPGME :: Ctx . new ( gpg_opts ) ...
returns decrypted_message status desc lines
4,991
def send_message m @mutex . synchronize do @sinks . each do | sink | sink << m sink . flush if sink . respond_to? ( :flush ) and level == "debug" end @buf << m end end
actually distribute the message
4,992
def each_raw_message_line offset @mutex . synchronize do ensure_open @f . seek offset until @f . eof? || MBox :: is_break_line? ( l = @f . gets ) yield l end end end
apparently it s a million times faster to call this directly if we re just moving messages around on disk than reading things into memory with raw_message .
4,993
def add_account hash , default = false raise ArgumentError , "no email specified for account" unless hash [ :email ] unless default [ :name , :sendmail , :signature , :gpgkey ] . each { | k | hash [ k ] ||= @default_account . send ( k ) } end hash [ :alternates ] ||= [ ] fail "alternative emails are not an array: #{has...
must be called first with the default account . fills in missing values from the default account .
4,994
def select t = nil , when_done = nil t ||= cursor_thread or return Redwood :: reporting_thread ( "load messages for thread-view-mode" ) do num = t . size message = "Loading #{num.pluralize 'message body'}..." BufferManager . say ( message ) do | sid | t . each_with_index do | ( m , * _ ) , i | next unless m BufferManag...
open up a thread view window
4,995
def multi_toggle_spam threads undos = threads . map { | t | actually_toggle_spammed t } threads . each { | t | HookManager . run ( "mark-as-spam" , :thread => t ) } UndoManager . register "marking/unmarking #{threads.size.pluralize 'thread'} as spam" , undos , lambda { regen_text } , lambda { threads . each { | t | In...
both spam and deleted have the curious characteristic that you always want to hide the thread after either applying or removing that label . in all thread - index - views except for label - search - results - mode when you mark a message as spam or deleted you want it to disappear immediately ; in LSRM you only see del...
4,996
def multi_toggle_deleted threads undos = threads . map { | t | actually_toggle_deleted t } UndoManager . register "deleting/undeleting #{threads.size.pluralize 'thread'}" , undos , lambda { regen_text } , lambda { threads . each { | t | Index . save_thread t } } regen_text threads . each { | t | Index . save_thread t }...
see comment for multi_toggle_spam
4,997
def multi_kill threads UndoManager . register "killing/unkilling #{threads.size.pluralize 'threads'}" do threads . each do | t | if t . toggle_label :killed add_or_unhide t . first else hide_thread t end end . each do | t | UpdateManager . relay self , :labeled , t . first Index . save_thread t end regen_text end threa...
m - m - m - m - MULTI - KILL
4,998
def thread_matches? t , query t . subj =~ query || t . snippet =~ query || t . participants . any? { | x | x . longname =~ query } end
used to tag threads by query . this can be made a lot more sophisticated but for right now we ll do the obvious this .
4,999
def author_names_and_newness_for_thread t , limit = nil new = { } seen = { } authors = t . map do | m , * o | next unless m && m . from new [ m . from ] ||= m . has_label? ( :unread ) next if seen [ m . from ] seen [ m . from ] = true m . from end . compact result = [ ] authors . each do | a | break if limit && result ...
preserve author order from the thread