Module: Konjac::Utils

Defined in:
lib/konjac/utils.rb

Overview

A handful of functions and tools with no other home, primarily for manipulating file names and paths

Class Method Summary collapse

Class Method Details

.build_converted_file_name(source, from_lang, to_lang) ⇒ Object

Build converted file name by appending “_converted” to the file name



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/konjac/utils.rb', line 32

def build_converted_file_name(source, from_lang, to_lang)
  # Get components of filename
  dirname  = File.dirname(source)
  basename = File.basename(source, ".*")
  extname  = File.extname(source)

  # Blank out the from language
  basename.sub! Regexp.new("_#{from_lang}", "i"), ""
  
  "#{dirname}/#{basename}_#{to_lang}#{extname}"
end

.extract_language_code_from_filename(name) ⇒ Object

Extracts the two letter language code from a filename



7
8
9
10
11
12
13
14
15
# File 'lib/konjac/utils.rb', line 7

def extract_language_code_from_filename(name)
  match = File.basename(name, ".*").match(/_([a-z]{2})/i)

  if match.nil?
    nil
  else
    match[1]
  end
end

.parse_files(files, opts = {}) ⇒ Object

Parses a list of files



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/konjac/utils.rb', line 45

def parse_files(files, opts = {})
  opts = { :extension => nil, :directory => nil }.merge opts
  files = [files] unless files.is_a?(Array)
  search_text = files.join(" ")
  parsed_files = []
  while !files.empty?
    file = files.shift
    unless opts[:directory].nil?
      file = opts[:directory] + "/" + file
    end
    unless opts[:extension].nil?
      file = file.sub(/\.[^\\\/]*$/, "") + "." + opts[:extension].to_s.tr(".", "")
    end
    parsed_files += Dir.glob(File.expand_path(file))
  end
  puts I18n.t(:no_match) % search_text if parsed_files.empty?
  parsed_files.uniq
end

.user_allows_overwrite?(file, opts = {}) ⇒ Boolean

Prompts user whether to overwrite the specified file. Passing :force => true after the filename will cause this message to be ignored and always return true

Returns:

  • (Boolean)


20
21
22
23
24
25
26
27
28
29
# File 'lib/konjac/utils.rb', line 20

def user_allows_overwrite?(file, opts = {})
  if File.exist?(File.expand_path(file)) && !opts[:force]
    print I18n.t(:overwrite) % file
    answer = HighLine::SystemExtensions.get_character.chr
    puts answer
    return answer =~ /^y/i
  else
    return true
  end
end

.verify_file(path, initial_content = "") ⇒ Object

Verifies that a file exists, writing initial content to it if not



65
66
67
68
69
70
71
72
# File 'lib/konjac/utils.rb', line 65

def verify_file(path, initial_content = "")
  unless File.exists?(path)
    FileUtils.mkdir_p File.dirname(path)
    File.open(path, "w") do |file|
      file.puts initial_content
    end
  end
end