Module: Gerrit::Utils

Included in:
Command::Base
Defined in:
lib/gerrit/utils.rb

Overview

A miscellaneous set of utility functions.

Class Method Summary collapse

Class Method Details

.camel_case(string) ⇒ String

Converts a string containing underscores/hyphens/spaces into CamelCase.

Parameters:

  • string (String)

Returns:

  • (String)


12
13
14
15
16
# File 'lib/gerrit/utils.rb', line 12

def camel_case(string)
  string.split(/_|-| /)
        .map { |part| part.sub(/^\w/) { |c| c.upcase } }
        .join
end

.commit_hash?(string) ⇒ Boolean

Returns whether a string appears to be a commit SHA1 hash.

Parameters:

  • string (String)

Returns:

  • (Boolean)


22
23
24
# File 'lib/gerrit/utils.rb', line 22

def commit_hash?(string)
  string =~ /^\h{7,40}$/
end

.human_time(time) ⇒ String

Returns the given Time as a human-readable string based on that time relative to the current time.

Parameters:

  • time (Time)

Returns:

  • (String)


31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/gerrit/utils.rb', line 31

def human_time(time)
  date = time.to_date

  if date == Date.today
    time.strftime('%l:%M %p')
  elsif date == Date.today - 1
    'Yesterday'
  elsif date > Date.today - 7
    time.strftime('%A') # Sunday
  elsif date.year == Date.today.year
    time.strftime('%b %e') # Jun 22
  else
    time.strftime('%b %e, %Y') # Jun 22, 2015
  end
end

.map_in_parallel(items, &block) ⇒ Array

Executing a block on each item in parallel.

Parameters:

  • items (Enumerable)

Returns:

  • (Array)


51
52
53
54
55
# File 'lib/gerrit/utils.rb', line 51

def map_in_parallel(items, &block)
  Parallel.map(items, in_threads: Parallel.processor_count) do |item|
    block.call(item)
  end
end

.snake_case(string) ⇒ String

Convert string containing camel case or spaces into snake case.

Parameters:

  • string (String)

Returns:

  • (String)

See Also:

  • Gerrit::Utils.stackoverflowstackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby


63
64
65
66
67
68
69
# File 'lib/gerrit/utils.rb', line 63

def snake_case(string)
  string.gsub(/::/, '/')
        .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
        .gsub(/([a-z\d])([A-Z])/, '\1_\2')
        .tr('-', '_')
        .downcase
end