Module: Magma::Utils
Instance Method Summary collapse
-
#pipe(object, methods = []) ⇒ Object
Applies methods/procs to an object in order.
-
#read_file_or_stdin(filename = nil) ⇒ Object
Reads a file or from STDIN if piped.
-
#run(*args, &block) ⇒ Object
Delegates to Open3.
-
#symbolize_keys(hash) ⇒ Object
Symbolizes a hash’s keys.
-
#uuid?(uuid) ⇒ Boolean
Returns whether a string is a UUID.
-
#which(cmd) ⇒ Object
Cross-platform way of finding an executable in the $PATH Reference: stackoverflow.com/a/5471032/3557448.
Instance Method Details
#pipe(object, methods = []) ⇒ Object
Applies methods/procs to an object in order
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/magma/utils.rb', line 17 def pipe(object, methods = []) methods.reduce(object) do |acc, method| case method when Proc || method.respond_to?(:call) method.call(acc) when Symbol send(method, acc) when String raise "must start with '.'" unless method[0] == '.' acc.send(method[1..-1].to_sym) else raise "unexpected pipe #{method}" end end end |
#read_file_or_stdin(filename = nil) ⇒ Object
Reads a file or from STDIN if piped
6 7 8 |
# File 'lib/magma/utils.rb', line 6 def read_file_or_stdin(filename = nil) filename.nil? ? !STDIN.tty? && STDIN.read : File.read(filename) end |
#run(*args, &block) ⇒ Object
Delegates to Open3
34 35 36 37 |
# File 'lib/magma/utils.rb', line 34 def run(*args, &block) return Open3.popen3(*args, &block) if block_given? Open3.popen3(*args) end |
#symbolize_keys(hash) ⇒ Object
Symbolizes a hash’s keys
40 41 42 |
# File 'lib/magma/utils.rb', line 40 def symbolize_keys(hash) hash.each_with_object({}) { |(k, v), memo| memo[k.to_sym] = v } end |
#uuid?(uuid) ⇒ Boolean
Returns whether a string is a UUID
11 12 13 14 |
# File 'lib/magma/utils.rb', line 11 def uuid?(uuid) uuid_regex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ uuid_regex =~ uuid.to_s.downcase end |
#which(cmd) ⇒ Object
Cross-platform way of finding an executable in the $PATH Reference: stackoverflow.com/a/5471032/3557448
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/magma/utils.rb', line 46 def which(cmd) return cmd if File.exist?(cmd) && File.executable?(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each do |ext| exe = File.join(path, "#{cmd}#{ext}") return exe if File.executable?(exe) && !File.directory?(exe) end end nil end |