code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def truncate! return if truncated? update_column :metadata, nil end
Truncates this Occurrence and saves it. Does nothing if the occurrence has already been truncated. All metadata will be erased to save space.
truncate!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def redirect_to!(occurrence) update_column :redirect_target_id, occurrence.id truncate! # if all occurrences for this bug redirect, mark the bug as unimportant if bug.occurrences.where(redirect_target_id: nil).none? bug.update_attribute :irrelevant, true end end
Redirects this Occurrence to a given Occurrence. See the class docs for a description of redirection. Also truncates the Occurrence and saves the record. If this is the last remaining Occurrence under a Bug to be redirected, the Bug is marked as irrelevant. This removes from the list Bugs with unsymbolicated Occurrences once the Symbolication is uploaded. @param [Occurrence] occurrence The Occurrence to redirect this Occurrence to.
redirect_to!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def symbolicate(symb=nil) symb ||= symbolication return unless symb return if truncated? return if symbolicated? (bt = backtraces).each do |bt| bt['backtrace'].each do |elem| next unless elem['type'] == 'address' symbolicated = symb.symbolicate(elem['address']) elem.replace(symbolicated) if symbolicated end end self.backtraces = bt # refresh the actual JSON end
Symbolicates this Occurrence's backtrace. Does nothing if there is no linked {Symbolication} or if there is nothing to symbolicate. @param [Symbolication] symb A Symbolication to use (by default, it's the linked Symbolication). @see #symbolicate!
symbolicate
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def symbolicate!(symb=nil) symb ||= symbolication return unless symb return if truncated? return if symbolicated? symbolicate symb save! end
Like {#symbolicate}, but saves the record. @param [Symbolication] symb A Symbolication to use (by default, it's the linked Symbolication).
symbolicate!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def symbolicated? return true if truncated? backtraces.all? do |bt| bt['backtrace'].none? { |elem| elem['type'] == 'address' } end end
@return [true, false] Whether all lines of every stack trace have been symbolicated. (Truncated Occurrences will return `true`.)
symbolicated?
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def sourcemap(*sourcemaps) return if truncated? return if sourcemapped? sourcemaps = bug.environment.source_maps.where(revision: revision) if sourcemaps.empty? return if sourcemaps.empty? sourcemaps = sourcemaps.group_by(&:from) (bt = backtraces).each do |bt| bt['backtrace'].each do |elem| found_at_least_one_applicable_sourcemap = true # repeat until there's no more sourcemapping we can do on this line while found_at_least_one_applicable_sourcemap # assume we haven't found one found_at_least_one_applicable_sourcemap = false next unless elem['type'].start_with?('js:') type = elem['type'][3..-1] # try every valid source map on this line sourcemapped = nil Array.wrap(sourcemaps[type]).each do |map| file = (map.from == 'hosted' ? elem['url'] : elem['file']) sourcemapped = map.resolve(file, elem['line'], elem['column']) if sourcemapped sourcemapped['type'] = "js:#{map.to}" # stop when we find one that applies break end end if !sourcemapped && elem['type'] == 'js:hosted' && bug.environment.project.digest_in_asset_names? # It's possible the most recent version of this asset was generated # in a previous deploy. Search all source maps for one that can # resolve our file name. if (matching_sourcemap = bug.environment.source_maps.where(filename: elem['url'], from: 'hosted').first) sourcemapped = matching_sourcemap.resolve(elem['url'], elem['line'], elem['column']) if sourcemapped sourcemapped['type'] = "js:#{matching_sourcemap.to}" # Since this digest was generated in a previous deploy, we need # to add all the sourcemaps generated in that deploy to our list sourcemaps.merge! bug.environment.source_maps.where(revision: matching_sourcemap.revision).group_by(&:from) end end end # if we found one that applies if sourcemapped # change the backtrace elem.replace sourcemapped # and make sure we try sourcemapping the line again found_at_least_one_applicable_sourcemap = true end end # clear out the type if we were able to sourcemap at least once elem.delete('type') if elem['type'] != 'js:hosted' end end self.backtraces = bt # refresh the actual JSON end
@overload sourcemap(source_map, ...) Apply one or more source maps to this Occurrence's backtrace. Any matching un-sourcemapped lines will be converted. Source maps will be searched and applied in until no further lines can be converted (see {SourceMap}). Does not save the record. @param [SourceMap] source_map A source map to apply. @see #sourcemap!
sourcemap
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def sourcemap!(*sourcemaps) return if truncated? return if sourcemapped? sourcemaps = bug.environment.source_maps.where(revision: revision) if sourcemaps.empty? return if sourcemaps.empty? sourcemap *sourcemaps save! end
Same as {#sourcemap}, but also `save!`s the record.
sourcemap!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def sourcemapped? return true if truncated? backtraces.all? do |bt| bt['backtrace'].none? { |elem| elem['type'] && elem['type'] == 'js:hosted' } end end
@return [true, false] Whether all lines of every stack trace have been sourcemapped. (Truncated Occurrences will return `true`.)
sourcemapped?
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def deobfuscate(map=nil) map ||= bug.deploy.try!(:obfuscation_map) return unless map return if truncated? return if deobfuscated? (bt = backtraces).each do |bt| bt['backtrace'].each do |elem| next unless elem['type'] == 'obfuscated' klass = map.namespace.obfuscated_type(elem['class_name']) next unless klass && klass.path meth = map.namespace.obfuscated_method(klass, elem['symbol']) elem.replace( 'file' => klass.path, 'line' => elem['line'], 'symbol' => meth.try!(:full_name) || elem['symbol'] ) end end self.backtraces = bt # refresh the actual JSON end
De-obfuscates this Occurrence's backtrace. Does nothing if the linked Deploy has no {ObfuscationMap} or if there are no obfuscated backtrace elements. @param [ObfuscationMap] map An ObfuscationMap to use (by default, it's the linked Deploy's ObfuscationMap). @see #deobfuscate!
deobfuscate
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def deobfuscate!(map=nil) map ||= bug.deploy.try!(:obfuscation_map) return unless map return if truncated? return if deobfuscated? deobfuscate map save! end
Like {#deobfuscate}, but saves the record. @param [ObfuscationMap] map An ObfuscationMap to use (by default, it's the linked Deploy's ObfuscationMap).
deobfuscate!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def deobfuscated? return true if truncated? backtraces.all? do |bt| bt['backtrace'].none? { |elem| elem['type'] == 'obfuscated' } end end
@return [true, false] Whether all lines of every stack trace have been deobfuscated. (Truncated Occurrences will return `true`.)
deobfuscated?
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def recategorize! blamer = bug.environment.project.blamer.new(self) new_bug = blamer.find_or_create_bug! if new_bug.id != bug_id copy = new_bug.occurrences.build copy.assign_attributes attributes.except('number', 'id', 'bug_id') copy.save! blamer.reopen_bug_if_necessary! new_bug redirect_to! copy end end
Recalculates the blame for this Occurrence and re-determines which Bug it should be a member of. If different from the current Bug, creates a duplicate Occurrence under the new Bug and redirects this Occurrence to it. Saves the record.
recategorize!
ruby
SquareSquash/web
app/models/occurrence.rb
https://github.com/SquareSquash/web/blob/master/app/models/occurrence.rb
Apache-2.0
def repo repo_mutex.synchronize do @repo ||= begin exists = File.exist?(repo_path) || clone_repo exists ? Git.bare(repo_path) : nil end end if block_given? repo_mutex.synchronize { yield @repo } else @repo end end
Returns a `Git::Repository` proxy object that allows you to work with the local checkout of this Project's repository. The repository will be checked out if it hasn't been already. Any Git errors that occur when attempting to clone the repository are swallowed, and `nil` is returned. @overload repo @return [Git::Repository, nil] The proxy object for the repository. @overload repo(&block) If passed a block, this method will lock a mutex and yield the repository, giving you exclusive access to the repository. This is recommended when performing any repository-altering operations (e.g., fetches). The mutex is freed when the block completes. @yield A block that is given exclusive control of the repository. @yieldparam [Git::Repository] repo The proxy object for the repository.
repo
ruby
SquareSquash/web
app/models/project.rb
https://github.com/SquareSquash/web/blob/master/app/models/project.rb
Apache-2.0
def create_api_key self.api_key = SecureRandom.uuid end
Generates a new API key for the Project. Does not save the Project.
create_api_key
ruby
SquareSquash/web
app/models/project.rb
https://github.com/SquareSquash/web/blob/master/app/models/project.rb
Apache-2.0
def path_type(file) return :library if file.start_with?('/') # not within project root return :library if META_FILE_NAMES.include?(file) # file names that aren't really file names # in filter paths and not in whitelist paths return :filtered if filter_paths.any? { |filter_line| file.start_with? filter_line } && whitelist_paths.none? { |filter_line| file.start_with? filter_line } # everything else is a project file return :project end
Determines if a file is project source code, filtered project source code, or library code. The project root must have already been stripped from the path for this to work. @param [String] file A path to a file. @return [Symbol] `:project` if this a project file, `:filtered` if this is a project file that should be filtered from the backtrace, and `:library` if this is a library file.
path_type
ruby
SquareSquash/web
app/models/project.rb
https://github.com/SquareSquash/web/blob/master/app/models/project.rb
Apache-2.0
def pagerduty @pagerduty ||= (pagerduty_service_key? ? Service::PagerDuty.new(pagerduty_service_key) : nil) end
@return [Service::PagerDuty, nil] A module for interacting with this Project's PagerDuty integration, or `nil` if PagerDuty is not enabled.
pagerduty
ruby
SquareSquash/web
app/models/project.rb
https://github.com/SquareSquash/web/blob/master/app/models/project.rb
Apache-2.0
def activate! self.class.transaction do Slug.for(sluggable_type, sluggable_id).update_all(active: false) update_attribute :active, true end end
Marks a slug as active and deactivates all other slugs assigned to the record.
activate!
ruby
SquareSquash/web
app/models/slug.rb
https://github.com/SquareSquash/web/blob/master/app/models/slug.rb
Apache-2.0
def resolve(route, line, column) return nil unless column # firefox doesn't support column numbers return nil unless map.filename == route || begin uri = URI.parse(route) rescue nil if uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS) uri.path == map.filename else false end end mapping = map.bsearch(GemSourceMap::Offset.new(line, column)) return nil unless mapping { 'file' => mapping.source, 'line' => mapping.original.line, 'column' => mapping.original.column } end
Given a line of code within a file in the `from` format, attempts to resolve it to a line of code within a file in the `to` format. @param [String] route The URL of the generated JavaScript file. @param [Fixnum] line The line of code @param [Fixnum] column The character number within the line. @return [Hash, nil] If found, a hash consisting of the source file path, line number, and method name.
resolve
ruby
SquareSquash/web
app/models/source_map.rb
https://github.com/SquareSquash/web/blob/master/app/models/source_map.rb
Apache-2.0
def symbolicate(address) line = lines.for(address) if lines symbol = symbols.for(address) if line && symbol { 'file' => line.file, 'line' => line.line, 'symbol' => symbol.ios_method } elsif line { 'file' => line.file, 'line' => line.line } elsif symbol { 'file' => symbol.file, 'line' => symbol.line, 'symbol' => symbol.ios_method } else nil end end
Returns the file path, line number, and method name corresponding to a program counter address. The result is formatted for use as part of an {Occurrence}'s backtrace element. If `lines` is provided, the line number will be the specific corresponding line number within the method. Otherwise it will be the line number of the method declaration. @param [Fixnum] address A stack return address (decimal number). @return [Hash, nil] The file path, line number, and method name containing that address, or `nil` if that address could not be symbolicated.
symbolicate
ruby
SquareSquash/web
app/models/symbolication.rb
https://github.com/SquareSquash/web/blob/master/app/models/symbolication.rb
Apache-2.0
def name return username unless first_name.present? || last_name.present? I18n.t('models.user.name', first_name: first_name, last_name: last_name).strip end
@return [String] The user's full name, or as much of it as available, or the `username`.
name
ruby
SquareSquash/web
app/models/user.rb
https://github.com/SquareSquash/web/blob/master/app/models/user.rb
Apache-2.0
def email @email ||= (emails.loaded? ? emails.detect(&:primary).email : emails.primary.first.email) end
@return [String] The user's company email address.
email
ruby
SquareSquash/web
app/models/user.rb
https://github.com/SquareSquash/web/blob/master/app/models/user.rb
Apache-2.0
def gravatar "http://www.gravatar.com/avatar/#{Digest::MD5.hexdigest email}" end
@return [String] The URL to the user's Gravatar.
gravatar
ruby
SquareSquash/web
app/models/user.rb
https://github.com/SquareSquash/web/blob/master/app/models/user.rb
Apache-2.0
def role(object) object = object.environment.project if object.kind_of?(Bug) case object when Project return :owner if object.owner_id == id membership = memberships.where(project_id: object.id).first return nil unless membership return :admin if membership.admin? return :member when Comment return :creator if object.user_id == id return :owner if object.bug.environment.project.owner_id == id membership = memberships.where(project_id: object.bug.environment.project_id).first return :admin if membership.try!(:admin?) return nil else return nil end end
Returns a symbol describing a user's role in relation to a model object; used for strong attribute roles. @param [ActiveRecord::Base] object A model instance. @return [Symbol, nil] The user's role, or `nil` if the user has no permissions. Possible values are `:creator`, `:owner`, `:admin`, `:member`, and `nil`.
role
ruby
SquareSquash/web
app/models/user.rb
https://github.com/SquareSquash/web/blob/master/app/models/user.rb
Apache-2.0
def watches?(bug) watches.where(bug_id: bug.id).first end
Returns whether or not a User is watching a {Bug}. @param [Bug] bug A Bug. @return [Watch, false] Whether or not the User is watching that Bug. @see Watch
watches?
ruby
SquareSquash/web
app/models/user.rb
https://github.com/SquareSquash/web/blob/master/app/models/user.rb
Apache-2.0
def authentic?(password) encrypt(password) == crypted_password end
Validates a password against this user. Not applicable for LDAP authenticating installs. @param [String] password A proposed password. @return [true, false] Whether it is the User's password.
authentic?
ruby
SquareSquash/web
app/models/additions/password_authentication.rb
https://github.com/SquareSquash/web/blob/master/app/models/additions/password_authentication.rb
Apache-2.0
def accordion(id, options={}) options[:class] = "#{options[:class]} accordion" div(options.merge(id: id)) { yield AccordionBuilder.new(id, self) } end
Creates a new accordion. Yields an {AccordionBuilder} that allows you to add items to the accordion. @param [String] id The unique ID of the DOM element to create. @param [Hash<Symbol, String>] options Additional attributes to apply to the DIV tag. @yield [builder] A block in which to build accordion items. @yieldparam [AccordionBuilder] builder The object that builds the accordion items.
accordion
ruby
SquareSquash/web
app/views/additions/accordion.rb
https://github.com/SquareSquash/web/blob/master/app/views/additions/accordion.rb
Apache-2.0
def accordion_item(id, title, visible=false, &block) @receiver.div(id: id, class: "accordion-pair #{visible ? 'shown' : nil}") do @receiver.h5 { @receiver.a title, rel: 'accordion', href: "##{id}" } @receiver.div({style: (visible ? nil : 'display: none')}, &block) end end
Creates a collapsible accordion item. @param [String] id The unique ID of the DOM element to create. @param [String] title The text of the item's title bar. @param [true, false] visible Whether or not this accordion item is visible initially. @yield The markup to place into the accordion item's body.
accordion_item
ruby
SquareSquash/web
app/views/additions/accordion.rb
https://github.com/SquareSquash/web/blob/master/app/views/additions/accordion.rb
Apache-2.0
def render_backtrace(backtrace) backtrace.map { |e| render_backtrace_element(e) }.join("\n") end
Renders a backtrace. @param [Array] backtrace The backtrace to render, in the format used by {Occurrence}. @return [String] The rendered backtrace.
render_backtrace
ruby
SquareSquash/web
app/views/additions/text_backtrace_rendering.rb
https://github.com/SquareSquash/web/blob/master/app/views/additions/text_backtrace_rendering.rb
Apache-2.0
def body_content raise NotImplementedError end
Override this method with your web page content.
body_content
ruby
SquareSquash/web
app/views/layouts/application.html.rb
https://github.com/SquareSquash/web/blob/master/app/views/layouts/application.html.rb
Apache-2.0
def full_width_section(alt=false) div(class: "content-container#{alt ? '-alt' : ''}") do div(class: 'container') do div(class: 'row') { div(class: 'sixteen columns') { yield } } end end end
Call as part of {#body_content} to generate a full-width (sixteen-column) content area with a white background. Yields to render content.
full_width_section
ruby
SquareSquash/web
app/views/layouts/application.html.rb
https://github.com/SquareSquash/web/blob/master/app/views/layouts/application.html.rb
Apache-2.0
def tabbed_section(tabs_proc, content_proc) div(class: 'tab-header-container') do div(class: 'container') do div(class: 'row') { div(class: 'sixteen columns') { tabs_proc.() } } end end div(class: 'tab-container') do div(class: 'container') do div(class: 'row') { div(class: 'sixteen columns') { content_proc.() } } end end end
Call as part of {#body_content} to generate a full-width (sixteen-column) content area with a shaded background below a tabbed header portion. The `tabs_proc` should render a `<UL>` with your tab headers, and the `content_proc` should render the tab bodies. See tabs.js.coffee for how to organize it.
tabbed_section
ruby
SquareSquash/web
app/views/layouts/application.html.rb
https://github.com/SquareSquash/web/blob/master/app/views/layouts/application.html.rb
Apache-2.0
def modal_section div(class: 'content-container') do div(class: 'container modal-container') do div(class: 'row row-modal') do div(class: 'two columns') { text! '&nbsp;' } div(class: 'twelve columns') { yield } div(class: 'two columns') { text! '&nbsp;' } end end end end
Call as part of {#body_content} to generate an inset, shaded twelve-column content area simulating the appearance of a modal. Yields to render content.
modal_section
ruby
SquareSquash/web
app/views/layouts/application.html.rb
https://github.com/SquareSquash/web/blob/master/app/views/layouts/application.html.rb
Apache-2.0
def button_to(name, location, overrides={}) button name, overrides.reverse_merge(href: location) end
## HELPERS Like link_to, but makes a button. This much simpler version does not wrap it in a form, but instead uses the buttons.js.coffee file to add `<A>` behavior to it.
button_to
ruby
SquareSquash/web
app/views/layouts/application.html.rb
https://github.com/SquareSquash/web/blob/master/app/views/layouts/application.html.rb
Apache-2.0
def touch(name = nil) attributes = timestamp_attributes_for_update_in_model attributes << name if name unless attributes.empty? current_time = current_time_from_proper_timezone changes = {} attributes.each do |column| changes[column.to_s] = write_attribute(column.to_s, current_time) end changes[self.class.locking_column] = increment_lock if locking_enabled? @changed_attributes.except!(*changes.keys) primary_key = self.class.primary_key #CPK #self.class.unscoped.update_all(changes, {primary_key => self[primary_key]}) == 1 where_clause = Array.wrap(self.class.primary_key).inject({}) { |hsh, key| hsh[key] = self[key]; hsh } self.class.unscoped.where(where_clause).update_all(changes) == 1 end end
Apparently CPK forgot to override this method
touch
ruby
SquareSquash/web
config/initializers/active_record.rb
https://github.com/SquareSquash/web/blob/master/config/initializers/active_record.rb
Apache-2.0
def find_in_batches(options = {}) relation = self unless arel.orders.blank? && arel.taken.blank? ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be #{batch_order} and batch size") end if (finder_options = options.except(:start, :batch_size)).present? raise "You can't specify an order, it's forced to be #{batch_order}" if options[:order].present? raise "You can't specify a limit, it's forced to be the batch_size" if options[:limit].present? relation = apply_finder_options(finder_options) end start = options.delete(:start) start ||= [1]*primary_key.size start = [start] unless start.kind_of?(Enumerable) start[-1] = start.last - 1 batch_size = options.delete(:batch_size) || 1000 relation = relation.reorder(batch_order).limit(batch_size) pkey = Array.wrap(primary_key) id_constraints, key_vals = build_id_constraints(pkey.dup, start.dup) records = relation.where(id_constraints, *key_vals).to_a while records.any? records_size = records.size yield records break if records_size < batch_size unless pkey.all? { |key| records.last.send(key) } raise "Primary key not included in the custom select clause" end pkey.each_with_index { |key, index| start[index] = records.last.send(key) } if records.any? id_constraints, key_vals = build_id_constraints(pkey.dup, start.dup) records = relation.where(id_constraints, *key_vals).to_a end end
Reimplementation of find_in_batches that fixes bugs and works with composite_primary_keys.
find_in_batches
ruby
SquareSquash/web
config/initializers/find_in_batches.rb
https://github.com/SquareSquash/web/blob/master/config/initializers/find_in_batches.rb
Apache-2.0
def sql_for_insert(sql, pk, id_value, sequence_name, binds) unless pk # Extract the table from the insert sql. Yuck. table_ref = extract_table_ref_from_insert_sql(sql) pk = primary_key(table_ref) if table_ref end # CPK #sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk sql = "#{sql} RETURNING #{quote_column_names(pk)}" if pk [sql, binds] end
AR::JDBC overwrites CPK's patched sql_for_insert method; over-overwrite it.
sql_for_insert
ruby
SquareSquash/web
config/initializers/jdbc_fixes.rb
https://github.com/SquareSquash/web/blob/master/config/initializers/jdbc_fixes.rb
Apache-2.0
def initialize(path) @path = path end
Creates a new file-based mutex. @param [String] path The path to the lockfile (can be any file; will be created if it doesn't exist).
initialize
ruby
SquareSquash/web
lib/file_mutex.rb
https://github.com/SquareSquash/web/blob/master/lib/file_mutex.rb
Apache-2.0
def lock!(timeout_duration = DEFAULT_TIMEOUT) result = nil File.open(@path, File::CREAT|File::EXCL|File::WRONLY, 0644) do |f| f.puts contents f.flush Timeout.timeout(timeout_duration) do begin result = yield ensure unlock! end end end return result rescue Errno::EEXIST sleep 1 retry ensure unlock! end
Attempts to acquire an exclusive lock on the resource. Blocks until a lock is available. Once a lock is available, acquires it, executes the provided block, and then releases the lock. @yield The code to run in the lock. @return The result of the block.
lock!
ruby
SquareSquash/web
lib/file_mutex.rb
https://github.com/SquareSquash/web/blob/master/lib/file_mutex.rb
Apache-2.0
def unlock! FileUtils.rm_f @path end
Forces this lock to be unlocked. Does nothing if the lock is already unlocked.
unlock!
ruby
SquareSquash/web
lib/file_mutex.rb
https://github.com/SquareSquash/web/blob/master/lib/file_mutex.rb
Apache-2.0
def matched_substring(class_name, message) format_iterator(class_name) do |rx, _| match = message.scan(rx).first return match if match end return message end
Given an error message like ```` Duplicate entry '[email protected]' for key 'index_users_on_email': UPDATE `users` SET `name` = 'Sancho Sample', `crypted_password` = '349857346384697346', `updated_at` = '2012-09-23 21:18:37', `email` = '[email protected]' WHERE `id` = 123456 -- app/controllers/api/v1/user_controller.rb:35 ```` this method returns only the error portion of the message, without replacing query-specific information: ```` Duplicate entry '[email protected]' for key 'index_users_on_email' ```` This method is useful for removing PII that would appear in a full query but not an error message. Returns `message` unmodified if there is no match. @param [String] class_name The name of the exception class. @param [String] message The exception message. @return [String] The exception message, error portion only, or the original message if no match was found.
matched_substring
ruby
SquareSquash/web
lib/message_template_matcher.rb
https://github.com/SquareSquash/web/blob/master/lib/message_template_matcher.rb
Apache-2.0
def sanitized_message(class_name, message) format_iterator(class_name) do |rx, replacement| return replacement if message =~ rx end return nil end
Given an error message like ```` Duplicate entry '[email protected]' for key 'index_users_on_email': UPDATE `users` SET `name` = 'Sancho Sample', `crypted_password` = '349857346384697346', `updated_at` = '2012-09-23 21:18:37', `email` = '[email protected]' WHERE `id` = 123456 -- app/controllers/api/v1/user_controller.rb:35 ```` this method returns only the error portion of the message, with all query-specific information filtered: ```` Duplicate entry '[STRING]' for key '[STRING]' ```` This method is useful for removing PII and grouping similar exceptions under the same filtered message. Returns `nil` if there is no match. @param [String] class_name The name of the exception class. @param [String] message The exception message. @return [String] The filtered exception message, or `nil` if no match was found.
sanitized_message
ruby
SquareSquash/web
lib/message_template_matcher.rb
https://github.com/SquareSquash/web/blob/master/lib/message_template_matcher.rb
Apache-2.0
def spinoff(name, priority, user_data={}) if Squash::Application.config.allow_concurrency @queue.enq(name, priority) { with_connection { with_dogfood(user_data) { yield } } } else yield end end
Spins off a new thread to perform a task. This thread will grab a new connection from the ActiveRecord connection pool and close it when it completes. Any exceptions raised in the thread will be sent to `Squash::Ruby`. Executes the block immediately in the current thread if `allow_concurrency` is `false`. @param [String, nil] name A name that uniquely identifies this job; used to prevent redundant duplicate jobs. If `nil`, the job is assumed to be unique. @param [Fixnum] priority The job priority as a number between 0 and 100. All jobs of a greater priority are executed before those of a lower priority. @param [Hash] user_data Additional user data to give to `Squash::Ruby.notify` in the event of an exception. @yield The code to run in a separate thread.
spinoff
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def start @queue = PriorityQueue.new(Squash::Configuration.concurrency.multithread.priority_threshold, Squash::Configuration.concurrency.multithread.max_threads) return unless Squash::Application.config.allow_concurrency @pool = Squash::Configuration.concurrency.multithread.pool_size.times.map do |i| Thread.new { catch(:exit) { loop { @queue.deq.() } } } end end
Spawns threads for the pool and begins executing jobs as they are pushed. You should call this method at the start of your process. Does nothing if `allow_concurrency` is `false`.
start
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def stop return unless Squash::Application.config.allow_concurrency Squash::Configuration.concurrency.multithread.pool_size.times { |i| spinoff(nil, 100) { throw :exit } } @pool.map &:join # make this a synchronous call end
Schedules a kill job for each thread in the pool. Once the thread processes that job, it will die. This method will block until all threads have died. Does nothing if `allow_concurrency` is `false`.
stop
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def initialize(priority_threshold, max_size) @operation_names = Set.new @priority_threshold = priority_threshold @max_size = max_size @mutex = Mutex.new @waiting = [] @jobs = [] end
@private Creates a new queue with specified concurrency options.
initialize
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def enq(name, priority=50, &block) raise ArgumentError, "Invalid priority" unless priority >= 0 && priority <= 100 if name && @operation_names.include?(name) Rails.logger.warn "[Multithread] Dropping operation #{name}: duplicate" return end if priority < @priority_threshold && saturated? Rails.logger.warn "[Multithread] Dropping operation #{name}: at capacity" return end @mutex.synchronize do @operation_names << name if name push Job.new(block, -1, name) escalate size - 1, priority begin @waiting.shift.try!(:wakeup) rescue ThreadError retry end end return self end
@private Adds a job onto the array.
enq
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def deq(block=true) @mutex.synchronize do begin loop do if empty? raise ThreadError, "queue empty" unless block @waiting.push(Thread.current) unless @waiting.include?(Thread.current) @mutex.sleep else max = first if size > 1 self[0] = pop root 0 else clear end @operation_names.delete(max.name) if max.name return max.operation end end ensure @waiting.delete Thread.current end end end
@private Returns and removes the highest-priority job. See Ruby's Queue object.
deq
ruby
SquareSquash/web
lib/multithread.rb
https://github.com/SquareSquash/web/blob/master/lib/multithread.rb
Apache-2.0
def initialize(object, *method_path) @method_path = method_path @project = object method_path.each { |m| @project = @project.send(m) } end
@overload initialize(object, method, ...) Creates a new repository proxy. @param object An object associated in some way with a {Project}. @param [Symbol] method The method to call that will return the Project. Multiple method names can be passed to make a call chain.
initialize
ruby
SquareSquash/web
lib/repo_proxy.rb
https://github.com/SquareSquash/web/blob/master/lib/repo_proxy.rb
Apache-2.0
def method_missing(meth, *args, &block) project.repo.send meth, *args, &block end
Delegates all other methods to {#project}.
method_missing
ruby
SquareSquash/web
lib/repo_proxy.rb
https://github.com/SquareSquash/web/blob/master/lib/repo_proxy.rb
Apache-2.0
def authorized?(request) return false unless request.session[:user_id] user = User.find(request.session[:user_id]) !user.nil? end
Determines whether a user can access the Sidekiq admin page. @param [ActionDispatch::Request] request A request. @return [true, false] Whether the user can access the Sidekiq admin page.
authorized?
ruby
SquareSquash/web
lib/sidekiq_auth_constraint.rb
https://github.com/SquareSquash/web/blob/master/lib/sidekiq_auth_constraint.rb
Apache-2.0
def initialize(occurrence) @occurrence = occurrence @special = false end
Creates a new instance suitable for placing a given Occurrence. @param [Occurrence] occurrence The Occurrence to find a Bug for.
initialize
ruby
SquareSquash/web
lib/blamer/base.rb
https://github.com/SquareSquash/web/blob/master/lib/blamer/base.rb
Apache-2.0
def find_or_create_bug! criteria = bug_search_criteria bug = if deploy # for distributed projects, we need to find either # * a bug associated with the exact deploy specified in the build attribute # * or, if the exact deploy specified does not have such a bug: # * find any open (not fixed) bug matching the criteria; # * if such a bug exists, use that bug and alter its deploy_id to # the given deploy; # * otherwise, a new bug is created. b = Bug.transaction do environment.bugs.where(criteria.merge(deploy_id: deploy.id)).first || environment.bugs.where(criteria.merge(fixed: false)). find_or_create!(bug_attributes) end b.deploy = deploy b else # for hosted projects, we search for any bug matching the criteria under # our current environment environment.bugs.where(criteria). find_or_create!(bug_attributes) end # If this code works as it should, there should only be one open record of # a Bug at any time. A bug occurs, a new Bug is created. A new release is # out, but it doesn't fix the bug, and that same Bug is reused. A new # release is out that DOES fix the bug, and the bug is closed. The bug # recurs, and a new open Bug is created. # Lastly, we need to resolve the bug if it's a duplicate. bug = bug.duplicate_of(true) if bug.duplicate? return bug end
@return [Bug] A Bug the Occurrence should belong to. Does not assign the Occurrence to the Bug. If no suitable Bug is found, saves and returns a new one.
find_or_create_bug!
ruby
SquareSquash/web
lib/blamer/base.rb
https://github.com/SquareSquash/web/blob/master/lib/blamer/base.rb
Apache-2.0
def reopen_bug_if_necessary!(bug) return if bug.deploy # now that things are saved, reopen the bug if we need to # this is so the occurrence has an id we can write into the reopen event occurrence_deploy = bug.environment.deploys.where(revision: occurrence.revision).order('deployed_at DESC').first latest_deploy = bug.environment.deploys.order('deployed_at DESC').first if bug.fix_deployed? && occurrence_deploy.try!(:id) == latest_deploy.try!(:id) # reopen the bug if it was purportedly fixed and deployed, and the occurrence # we're seeing is on the latest deploy -- or if we don't have any deploy # information bug.reopen occurrence bug.save! elsif !bug.fix_deployed? && bug.fixed? && bug.fixed_at < STALE_TIMEOUT.ago # or, if it was fixed but never marked as deployed, and is more than 30 days old, reopen it bug.reopen occurrence bug.save! end end
This method determines if the Bug should be reopened. You should pass in the Bug returned from {#find_or_create_bug!}, after it has been linked to the Occurrence and saved. This method will reopen the Bug if necessary. The Bug is only reopened if it recurs after being fixed and after the fix is deployed. A fix is considered deployed if the fix has been marked `fix_deployed` or if the fix is over 30 days old. Bugs of distributed Projects are never reopened. @param [Bug] bug The bug that was returned from {#find_or_create_bug!}.
reopen_bug_if_necessary!
ruby
SquareSquash/web
lib/blamer/base.rb
https://github.com/SquareSquash/web/blob/master/lib/blamer/base.rb
Apache-2.0
def bug_search_criteria raise NotImplementedError end
@abstract @return [Hash<Symbol, Object>] A hash of search criteria to be used in a `WHERE` clause to locate a Bug to file an Occurrence under.
bug_search_criteria
ruby
SquareSquash/web
lib/blamer/base.rb
https://github.com/SquareSquash/web/blob/master/lib/blamer/base.rb
Apache-2.0
def blame(project, revision, file, line) cached_blame(project, revision, file, line) || write_blame(project, revision, file, line, git_blame(project, revision, file, line)) end
Returns the cached result of a blame operation, or performs the blame on a cache miss. `nil` blame results are never cached. @param [Project] project The project whose repository will be used for the blame operation. @param [String] revision The SHA1 revision at which point to run the blame. @param [String] file The file to run the blame on. @param [Integer] line The line number in the file to run the blame at. @return [String, nil] The SHA of the blamed revision, or `nil` if blame could not be determined for some reason.
blame
ruby
SquareSquash/web
lib/blamer/cache.rb
https://github.com/SquareSquash/web/blob/master/lib/blamer/cache.rb
Apache-2.0
def new_issue_link(properties) return nil if Squash::Configuration.jira.disabled? url "#{Squash::Configuration.jira.create_issue_details}?#{properties.to_query}" end
Returns the link to a new issue page with pre-filled values. See the JIRA `CreateIssueDetails` action documentation for more information on possible values. @param [Hash<String, String>] properties Values to pre-fill. @return [String, nil] A URL to the uncreated JIRA issue, or `nil` if JIRA integration is disabled.
new_issue_link
ruby
SquareSquash/web
lib/service/jira.rb
https://github.com/SquareSquash/web/blob/master/lib/service/jira.rb
Apache-2.0
def issue(key) return nil if Squash::Configuration.jira.disabled? begin client.Issue.find(key) rescue ::JIRA::HTTPError nil end end
Locates an issue by its key. @param [String] key The issue key (e.g., "PROJ-123"). @return [JIRA::Resource::Issue, nil] The issue with that key, if found.
issue
ruby
SquareSquash/web
lib/service/jira.rb
https://github.com/SquareSquash/web/blob/master/lib/service/jira.rb
Apache-2.0
def trigger(description, incident_key=nil, details=nil) request 'service_key' => service_key, 'incident_key' => incident_key, 'event_type' => 'trigger', 'description' => description, 'details' => details end
Triggers a new incident in PagerDuty. See the PagerDuty API for more details. @param [String] description A short description of the incident. @param [String] incident_key A key shared by all duplicates of the same incident (used for de-duping). Its format is left to the programmer. @param [Hash] details A JSON-serializable hash of user data to send along. @return [Service::PagerDuty::Response] The API response.
trigger
ruby
SquareSquash/web
lib/service/pager_duty.rb
https://github.com/SquareSquash/web/blob/master/lib/service/pager_duty.rb
Apache-2.0
def acknowledge(incident_key, description=nil, details=nil) request 'service_key' => service_key, 'event_type' => 'acknowledge', 'incident_key' => incident_key, 'description' => description, 'details' => details end
Acknowledges an incident in PagerDuty. See the PagerDuty API for more details. @param [String] incident_key The incident key returned by PagerDuty when the incident was created. @param [String] description A short description of the acknowledgement. @param [Hash] details A JSON-serializable hash of user data to send along. @return [Service::PagerDuty::Response] The API response.
acknowledge
ruby
SquareSquash/web
lib/service/pager_duty.rb
https://github.com/SquareSquash/web/blob/master/lib/service/pager_duty.rb
Apache-2.0
def resolve(incident_key, description=nil, details=nil) request 'service_key' => service_key, 'event_type' => 'resolve', 'incident_key' => incident_key, 'description' => description, 'details' => details end
Resolves an incident in PagerDuty. See the PagerDuty API for more details. @param [String] incident_key The incident key returned by PagerDuty when the incident was created. @param [String] description A short description of the resolution. @param [Hash] details A JSON-serializable hash of user data to send along. @return [Service::PagerDuty::Response] The API response.
resolve
ruby
SquareSquash/web
lib/service/pager_duty.rb
https://github.com/SquareSquash/web/blob/master/lib/service/pager_duty.rb
Apache-2.0
def success? status == 'success' end
@return [true, false] Whether the `status` field is "success".
success?
ruby
SquareSquash/web
lib/service/pager_duty.rb
https://github.com/SquareSquash/web/blob/master/lib/service/pager_duty.rb
Apache-2.0
def initialize(comment) @comment = comment end
Creates a new worker instance. @param [Comment] comment A Comment that was just posted.
initialize
ruby
SquareSquash/web
lib/workers/comment_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/comment_notification_mailer.rb
Apache-2.0
def perform recipients = @comment.bug.comments.select('user_id').uniq.pluck(:user_id) recipients << @comment.bug.assigned_user_id recipients.delete @comment.user_id recipients.uniq! User.where(id: recipients).each { |user| NotificationMailer.comment(@comment, user).deliver_now } end
Emails all relevant Users about the new Comment.
perform
ruby
SquareSquash/web
lib/workers/comment_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/comment_notification_mailer.rb
Apache-2.0
def initialize(deploy) @deploy = deploy end
Creates a new instance. @param [Deploy] deploy A deploy to process.
initialize
ruby
SquareSquash/web
lib/workers/deploy_fix_marker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/deploy_fix_marker.rb
Apache-2.0
def initialize(bug) @bug = bug end
Creates a new worker instance. @param [Bug] bug A Bug that a Deploy just fixed.
initialize
ruby
SquareSquash/web
lib/workers/deploy_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/deploy_notification_mailer.rb
Apache-2.0
def perform User.where(id: @bug.notify_on_deploy).each do |user| NotificationMailer.deploy(@bug, user).deliver_now end end
Emails all Users who enabled fix-deployed notifications.
perform
ruby
SquareSquash/web
lib/workers/deploy_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/deploy_notification_mailer.rb
Apache-2.0
def perform Bug.where(fixed: false).cursor.each do |bug| next unless bug.jira_issue && bug.jira_status_id issue = Service::JIRA.issue(bug.jira_issue) next unless issue next unless issue.status.id.to_i == bug.jira_status_id bug.modifier = issue bug.update_attribute :fixed, true end end
Iterates through all open bugs that are linked to JIRA issues. Checks the JIRA issue status for each such bug, and marks the bug as fixed as appropriate.
perform
ruby
SquareSquash/web
lib/workers/jira_status_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/jira_status_worker.rb
Apache-2.0
def initialize(params) @params = params end
Creates a new instance with the given parameters. @param [Hash] params Parameters passed to the API controller.
initialize
ruby
SquareSquash/web
lib/workers/obfuscation_map_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/obfuscation_map_creator.rb
Apache-2.0
def perform map = YAML.load(Zlib::Inflate.inflate(Base64.decode64(@params['namespace'])), safe: true, deserialize_symbols: false) return unless map.kind_of?(Squash::Java::Namespace) project = Project.find_by_api_key(@params['api_key']) or raise(API::UnknownAPIKeyError) deploy = project. environments.with_name(@params['environment']).first!. deploys.find_by_build!(@params['build']) deploy.obfuscation_map.try! :destroy deploy.create_obfuscation_map!(namespace: map) end
Decodes parameters and creates the ObfuscationMap.
perform
ruby
SquareSquash/web
lib/workers/obfuscation_map_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/obfuscation_map_creator.rb
Apache-2.0
def initialize(map) @map = map end
Creates a new worker instance. @param [ObfuscationMap] map An obfuscation map to process.
initialize
ruby
SquareSquash/web
lib/workers/obfuscation_map_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/obfuscation_map_worker.rb
Apache-2.0
def perform @map.deploy.bugs.cursor.each do |bug| bug.occurrences.cursor.each do |occ| begin occ.deobfuscate! @map occ.recategorize! rescue => err # for some reason the cursors gem eats exceptions Squash::Ruby.notify err, occurrence: occ end end end end
Locates relevant Occurrences and attempts to deobfuscate them.
perform
ruby
SquareSquash/web
lib/workers/obfuscation_map_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/obfuscation_map_worker.rb
Apache-2.0
def initialize(attrs) @attrs = attrs.deep_clone raise API::InvalidAttributesError, "Missing required keys: #{(REQUIRED_KEYS - @attrs.select { |k, v| v.present? }.keys).to_sentence}" unless REQUIRED_KEYS.all? { |key| @attrs[key].present? } raise API::InvalidAttributesError, "revision or build must be specified" unless @attrs.include?('revision') || @attrs.include?('build') begin @project = Project.find_by_api_key!(@attrs.delete('api_key')) rescue ActiveRecord::RecordNotFound raise API::UnknownAPIKeyError, "Unknown API key" end env_name = @attrs.delete('environment') @environment = project.environments.with_name(env_name).find_or_create!(name: env_name) rescue ActiveRecord::RecordInvalid => err raise API::InvalidAttributesError, err.to_s end
Creates a new worker ready to process an incoming notification. @param [Hash<String, Object>] attrs The queue item properties. @raise [API::InvalidAttributesError] If the attributes are invalid. @raise [API::UnknownAPIKeyError] If the API key is invalid.
initialize
ruby
SquareSquash/web
lib/workers/occurrences_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/occurrences_worker.rb
Apache-2.0
def perform # First make an occurrence to perform a blame on commit = set_deploy_and_commit class_name = @attrs.delete('class_name') occurrence = build_occurrence(commit) # In order to use Blamer, we need to create a new, unsaved bug with the # class name and environment specified in @attrs. If blamer finds a matching # existing Bug, it will return that Bug, and the unsaved Bug will never be # saved. If however no matching bug is found, a new bug is created, saved, # and returned. In no case is the bug we create below saved. occurrence.bug = build_temporary_bug(class_name) blamer = project.blamer.new(occurrence) bug = blamer.find_or_create_bug! # these must be done after Blamer runs add_user_agent_data occurrence filter_pii(occurrence, class_name) unless project.disable_message_filtering? occurrence.message = occurrence.message.truncate(1000) occurrence.message ||= occurrence.class_name # hack for Java # hook things up and save occurrence.bug = bug Bug.transaction do bug.save! occurrence.save! end blamer.reopen_bug_if_necessary! bug occurrence rescue ActiveRecord::StatementInvalid => err if err.to_s.start_with?("ActiveRecord::JDBCError: ERROR: could not serialize access due to read/write dependencies among transactions") @retry_count ||= 0 if @retry_count > 5 Rails.logger.error "[OccurrencesWorker] Too many retries: #{err.to_s}" raise else @retry_count += 1 Rails.logger.error "[OccurrencesWorker] Retrying: #{err.to_s}" retry end else raise end rescue Object => err # don't get into an infinite loop of notifying Squash Rails.logger.error "-- ERROR IN OccurrencesWorker #{err.object_id} --" Rails.logger.error err Rails.logger.error err.backtrace.join("\n") Rails.logger.error @attrs.inspect Rails.logger.error "-- END ERROR #{err.object_id} --" raise if Rails.env.test? end
Processes an exception notification. Builds an {Occurrence} and possibly a {Bug}.
perform
ruby
SquareSquash/web
lib/workers/occurrences_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/occurrences_worker.rb
Apache-2.0
def initialize(occurrence) @occurrence = occurrence end
Creates a new worker instance. @param [Occurrence] occurrence A new Occurrence.
initialize
ruby
SquareSquash/web
lib/workers/occurrence_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/occurrence_notification_mailer.rb
Apache-2.0
def perform if @occurrence.bug.occurrences_count == @occurrence.bug.environment.project.critical_threshold && [email protected]? && [email protected]? NotificationMailer.critical(@occurrence.bug).deliver_now end User.where(id: @occurrence.bug.notify_on_occurrence).each do |user| NotificationMailer.occurrence(@occurrence, user).deliver_now end @occurrence.bug.notification_thresholds.cursor.each do |thresh| begin if thresh.tripped? NotificationMailer.threshold(@occurrence.bug, thresh.user).deliver_now thresh.touch :last_tripped_at end rescue => err # for some reason the cursors gem eats exceptions Squash::Ruby.notify err, occurrence: @occurrence, notification_threshold: thresh end end end
Emails all Users who enabled per-occurrence notifications, and all frequency-based notifications as appropriate.
perform
ruby
SquareSquash/web
lib/workers/occurrence_notification_mailer.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/occurrence_notification_mailer.rb
Apache-2.0
def initialize(bug) @bug = bug end
Creates a new worker instance. @param [Bug] bug A Bug that was assigned.
initialize
ruby
SquareSquash/web
lib/workers/pager_duty_acknowledger.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/pager_duty_acknowledger.rb
Apache-2.0
def perform @bug.environment.project.pagerduty.acknowledge @bug.pagerduty_incident_key, description, details end
Sends a PagerDuty API call acknowledging an incident.
perform
ruby
SquareSquash/web
lib/workers/pager_duty_acknowledger.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/pager_duty_acknowledger.rb
Apache-2.0
def initialize(occurrence) @occurrence = occurrence end
Creates a new worker instance. @param [Occurrence] occurrence A new Occurrence.
initialize
ruby
SquareSquash/web
lib/workers/pager_duty_notifier.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/pager_duty_notifier.rb
Apache-2.0
def perform if should_notify_pagerduty_of_new_occurrence? || should_notify_pagerduty_when_tripped? @occurrence.bug.environment.project.pagerduty.trigger description, @occurrence.bug.pagerduty_incident_key, details @occurrence.bug.update_attribute :page_last_tripped_at, Time.now end end
Sends a PagerDuty API call creating a new incident (if appropriate).
perform
ruby
SquareSquash/web
lib/workers/pager_duty_notifier.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/pager_duty_notifier.rb
Apache-2.0
def perform @bug.environment.project.pagerduty.resolve @bug.pagerduty_incident_key, description end
Sends a PagerDuty API call resolving an incident.
perform
ruby
SquareSquash/web
lib/workers/pager_duty_resolver.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/pager_duty_resolver.rb
Apache-2.0
def initialize(project) @project = project end
Creates a new instance. @param [Project] project A Project whose repository should be updated.
initialize
ruby
SquareSquash/web
lib/workers/project_repo_fetcher.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/project_repo_fetcher.rb
Apache-2.0
def initialize(params) @params = params end
Creates a new instance with the given parameters. @param [Hash] params Parameters passed to the API controller.
initialize
ruby
SquareSquash/web
lib/workers/source_map_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/source_map_creator.rb
Apache-2.0
def perform project = Project.find_by_api_key(@params['api_key']) or raise(API::UnknownAPIKeyError) project. environments.with_name(@params['environment']).find_or_create!(name: @params['environment']). source_maps.create(raw_map: @params['sourcemap'], revision: @params['revision'], from: @params['from'], to: @params['to']) end
Decodes parameters and creates the SourceMap.
perform
ruby
SquareSquash/web
lib/workers/source_map_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/source_map_creator.rb
Apache-2.0
def initialize(map) @map = map end
Creates a new worker instance. @param [SourceMap] map A source map to process.
initialize
ruby
SquareSquash/web
lib/workers/source_map_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/source_map_worker.rb
Apache-2.0
def perform @map.environment.bugs.cursor.each do |bug| bug.occurrences.where(revision: @map.revision).cursor.each do |occurrence| begin occurrence.sourcemap! @map occurrence.recategorize! rescue => err # for some reason the cursors gem eats exceptions Squash::Ruby.notify err, occurrence: occurrence end end end end
Locates relevant Occurrences and attempts to sourcemap them.
perform
ruby
SquareSquash/web
lib/workers/source_map_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/source_map_worker.rb
Apache-2.0
def initialize(params) @params = params end
Creates a new instance with the given parameters. @param [Hash] params Parameters passed to the API controller.
initialize
ruby
SquareSquash/web
lib/workers/symbolication_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/symbolication_creator.rb
Apache-2.0
def perform @params['symbolications'].each do |attrs| Symbolication.where(uuid: attrs['uuid']).create_or_update do |symbolication| symbolication.send :write_attribute, :symbols, attrs['symbols'] symbolication.send :write_attribute, :lines, attrs['lines'] end end end
Decodes parameters and creates the Symbolication.
perform
ruby
SquareSquash/web
lib/workers/symbolication_creator.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/symbolication_creator.rb
Apache-2.0
def initialize(sym) @symbolication = sym end
Creates a new worker instance. @param [Symbolication] sym A symbolication to process.
initialize
ruby
SquareSquash/web
lib/workers/symbolication_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/symbolication_worker.rb
Apache-2.0
def perform @symbolication.occurrences.cursor.each do |occ| begin occ.symbolicate! @symbolication occ.recategorize! rescue => err # for some reason the cursors gem eats exceptions Squash::Ruby.notify err, occurrence: occ end end end
Locates relevant Occurrences and attempts to symbolicate them.
perform
ruby
SquareSquash/web
lib/workers/symbolication_worker.rb
https://github.com/SquareSquash/web/blob/master/lib/workers/symbolication_worker.rb
Apache-2.0
def login_as(user) allow(controller).to receive(:current_user).and_return(user) end
see comments in this file for more info Logs a user in for spec purposes. @params [User] user A user.
login_as
ruby
SquareSquash/web
spec/rails_helper.rb
https://github.com/SquareSquash/web/blob/master/spec/rails_helper.rb
Apache-2.0
def polymorphic_params(object, nested, overrides={}) hsh = case object when Occurrence {project_id: object.bug.environment.project.to_param, environment_id: object.bug.environment.to_param, bug_id: object.bug.to_param, occurrence_id: object.to_param} when Bug {project_id: object.environment.project.to_param, environment_id: object.environment.to_param, bug_id: object.to_param} when Environment {project_id: object.project.to_param, environment_id: object.to_param} when Comment {project_id: object.bug.environment.project.to_param, environment_id: object.bug.environment.to_param, bug_id: object.bug.to_param, comment_id: object.to_param} when Event {project_id: object.bug.environment.project.to_param, environment_id: object.bug.environment.to_param, bug_id: object.bug.to_param, event_id: object.to_param} when Project {project_id: object.to_param} when Membership {project_id: object.project.to_param, membership_id: object.user.to_param} when Email {id: object.to_param} when User {user_id: object.to_param} else raise ArgumentError, "Unknown model type #{object.class}" end unless nested id_key = hsh.keys.last hsh[:id] = hsh[id_key] hsh.delete id_key end return hsh.reverse_merge(overrides) end
Returns the parameters that would be created when a polymorphic route is hit corresponding to the given model object. @param [ActiveRecord::Base] object A model object. @param [true, false] nested Whether or not there are further route components nested beneath this one. @param [Hash<Symbol, String>] overrides Additional items to merge into the result hash. @return [Hash<Symbol, String>] The URL parameters. @example polymorphic_params(some_comment, false) #=> {project_id: 'foo', environment_id: 'development', bug_id: 123, id: 3} polymorphic_params(some_bug, true) #=> {project_id: 'bar', environment_id: 'test', id: 123}
polymorphic_params
ruby
SquareSquash/web
spec/rails_helper.rb
https://github.com/SquareSquash/web/blob/master/spec/rails_helper.rb
Apache-2.0
def jira_url(path) host = Squash::Configuration.jira.api_host root = Squash::Configuration.jira.api_root user = Squash::Configuration.jira.authentication.user password = Squash::Configuration.jira.authentication.password host = host.gsub('://', "://#{user}:#{password}@") host + root + path end
Builds a JIRA API URL as used by JIRA-Ruby.
jira_url
ruby
SquareSquash/web
spec/rails_helper.rb
https://github.com/SquareSquash/web/blob/master/spec/rails_helper.rb
Apache-2.0
def random_sha 40.times.map { rand(16).to_s(16) }.join end
@return [String] A random 40-digit hex number.
random_sha
ruby
SquareSquash/web
spec/rails_helper.rb
https://github.com/SquareSquash/web/blob/master/spec/rails_helper.rb
Apache-2.0
def deep_merge!(other_hash) other_hash.each_pair do |k, v| tv = self[k] self[k] = if v.kind_of?(::Hash) then if tv.kind_of?(::Hash) then Configoro::Hash.new(tv).deep_merge!(v) else Configoro::Hash.new(v) end else v end end self end
Recursively merges this hash with another hash. All nested hashes are forced to be `Configoro::Hash` instances. @param [::Hash] other_hash The hash to merge into this one. @return [Configoro::Hash] This object.
deep_merge!
ruby
SquareSquash/web
vendor/configoro/hash.rb
https://github.com/SquareSquash/web/blob/master/vendor/configoro/hash.rb
Apache-2.0
def method_missing(meth, *args) if include?(meth.to_s) then if args.empty? then create_getter meth else raise ArgumentError, "wrong number of arguments (#{args.size} for 0)" end elsif meth.to_s =~ /^(.+)\?$/ and include?(root_meth = $1) then if args.empty? then !!create_getter(root_meth) #TODO duplication of logic else raise ArgumentError, "wrong number of arguments (#{args.size} for 0)" end else super end end
@private To optimize access, we create a getter method every time we encounter a key that exists in the hash. If the key is later deleted, the method will be removed.
method_missing
ruby
SquareSquash/web
vendor/configoro/hash.rb
https://github.com/SquareSquash/web/blob/master/vendor/configoro/hash.rb
Apache-2.0
def transform(&block) copy = __adamantium_dup__ copy.instance_eval(&block) self.class.freezer.freeze(copy) end
Transform the object with the provided block @return [Object] @api public
transform
ruby
dkubb/adamantium
lib/adamantium.rb
https://github.com/dkubb/adamantium/blob/master/lib/adamantium.rb
MIT
def transform_unless(condition, &block) condition ? self : transform(&block) end
Transform the object with the provided block if the condition is false @param [Boolean] condition @return [Object] @api public
transform_unless
ruby
dkubb/adamantium
lib/adamantium.rb
https://github.com/dkubb/adamantium/blob/master/lib/adamantium.rb
MIT
def memoize(*methods) options = methods.last.kind_of?(Hash) ? methods.pop : {} method_freezer = Freezer.parse(options) || freezer methods.each { |method| memoize_method(method, method_freezer) } self end
Memoize a list of methods @example memoize :hash @param [Array<#to_s>] methods a list of methods to memoize @return [self] @api public
memoize
ruby
dkubb/adamantium
lib/adamantium/module_methods.rb
https://github.com/dkubb/adamantium/blob/master/lib/adamantium/module_methods.rb
MIT
def included(descendant) super descendant.module_eval { include Adamantium } end
Hook called when module is included @param [Module] descendant the module including ModuleMethods @return [undefined] @api private
included
ruby
dkubb/adamantium
lib/adamantium/module_methods.rb
https://github.com/dkubb/adamantium/blob/master/lib/adamantium/module_methods.rb
MIT
def memoize_method(method_name, freezer) memoized_methods[method_name] = Memoizable::MethodBuilder .new(self, method_name, freezer).call end
Memoize the named method @param [Symbol] method_name a method name to memoize @param [#call] freezer a callable object to freeze the value @return [undefined] @api private
memoize_method
ruby
dkubb/adamantium
lib/adamantium/module_methods.rb
https://github.com/dkubb/adamantium/blob/master/lib/adamantium/module_methods.rb
MIT