module Navo::Utils

A miscellaneous set of utility functions.

Public Instance Methods

camel_case(string) click to toggle source

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

@param [String] string @return [String]

# File lib/navo/utils.rb, line 13
def camel_case(string)
  string.split(/_|-| /)
        .map { |part| part.sub(/^\w/) { |c| c.upcase } }
        .join
end
human_time(time) click to toggle source

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

@param time [Time] @return [String]

# File lib/navo/utils.rb, line 24
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
path_hash(path) click to toggle source

Returns a hash of the contents of the given file/directory.

@param path [String] @return [String, nil]

# File lib/navo/utils.rb, line 44
def path_hash(path)
  if File.exist?(path)
    %x{
      { cd cookbooks;
       export LC_ALL=C;
       find #{path} -type f -exec md5sum {} + | sort; echo;
       find #{path} -type d | sort;
       find #{path} -type d | sort | md5sum;
      } | md5sum
    }.split(' ', 2).first
  end
end
snake_case(string) click to toggle source

Convert string containing camel case or spaces into snake case.

@see stackoverflow.com/questions/1509915/converting-camel-case-to-underscore-case-in-ruby

@param [String] string @return [String]

# File lib/navo/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