Class: Psychic::Util

Inherits:
Object
  • Object
show all
Defined in:
lib/psychic/util.rb

Defined Under Namespace

Modules: Hashable

Class Method Summary collapse

Class Method Details

.find_file_by_alias(file_alias, search_path, ignored_patterns = nil) ⇒ Object



59
60
61
# File 'lib/psychic/util.rb', line 59

def self.find_file_by_alias(file_alias, search_path, ignored_patterns = nil)
  FileFinder.new(search_path, ignored_patterns).find_file(file_alias)
end

.relativize(file, base_path) ⇒ Object



47
48
49
50
51
# File 'lib/psychic/util.rb', line 47

def self.relativize(file, base_path)
  absolute_file = File.absolute_path(file)
  absolute_base_path = File.absolute_path(base_path)
  Pathname.new(absolute_file).relative_path_from Pathname.new(absolute_base_path)
end

.replace_tokens(template, variables, token_regexp = nil, token_replacement = nil) ⇒ Object



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

def self.replace_tokens(template, variables, token_regexp = nil, token_replacement = nil)
  if token_regexp.nil?
    MustacheTokenHandler.new(template).render(variables)
  else
    RegexpTokenHandler.new(template, token_regexp, token_replacement).render(variables)
  end
end

.slugify(*labels) ⇒ Object



53
54
55
56
57
# File 'lib/psychic/util.rb', line 53

def self.slugify(*labels)
  labels.map do |label|
    label.downcase.gsub(/[\.\s-]/, '_')
  end.join('-')
end

.stringified_hash(obj) ⇒ Object

Returns a new Hash with all key values coerced to strings. All keys within a Hash are coerced by calling #to_s and hashes with arrays and other hashes are traversed.

Parameters:

  • obj (Object)

    the hash to be processed. While intended for hashes, this method safely processes arbitrary objects

Returns:

  • (Object)

    a converted hash with all keys as strings



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/psychic/util.rb', line 19

def self.stringified_hash(obj)
  if obj.is_a?(Hash)
    obj.each_with_object({}) do |(k, v), h|
      h[k.to_s] = stringified_hash(v)
    end
  elsif obj.is_a?(Array)
    obj.each_with_object([]) do |e, a|
      a << stringified_hash(e)
    end
  else
    obj
  end
end

.symbolized_hash(obj) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/psychic/util.rb', line 33

def self.symbolized_hash(obj)
  if obj.is_a?(Hash)
    obj.each_with_object({}) do |(k, v), h|
      h[k.to_sym] = symbolized_hash(v)
    end
  elsif obj.is_a?(Array)
    obj.each_with_object([]) do |e, a|
      a << symbolized_hash(e)
    end
  else
    obj
  end
end