Class: AbideDevUtils::Files::Writer

Inherits:
Object
  • Object
show all
Defined in:
lib/abide_dev_utils/files.rb

Constant Summary collapse

MSG_EXT_APPEND =
'Appending %s extension to file'

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, **kwargs, &_block) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/abide_dev_utils/files.rb', line 48

def method_missing(m, *args, **kwargs, &_block)
  if m.to_s.match?(/^write_/)
    ext = m.to_s.split('_')[-1]
    write(args[0], **kwargs, file_ext: ext)
  else
    super
  end
end

Instance Method Details

#append_ext(file_path, ext) ⇒ Object



61
62
63
64
65
66
67
68
69
70
# File 'lib/abide_dev_utils/files.rb', line 61

def append_ext(file_path, ext)
  return file_path if ext.nil?

  s_ext = ".#{ext}"
  unless File.extname(file_path) == s_ext
    puts MSG_EXT_APPEND % s_ext
    file_path << s_ext
  end
  file_path
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/abide_dev_utils/files.rb', line 57

def respond_to_missing?(method_name, include_private = false)
  method_name.to_s.start_with?('write_') || super
end

#verify_write(file_path) ⇒ Object



72
73
74
75
76
77
78
# File 'lib/abide_dev_utils/files.rb', line 72

def verify_write(file_path)
  if File.file?(file_path)
    puts "Successfully wrote to #{file_path}"
  else
    puts "Something went wrong! Failed writing to #{file_path}!"
  end
end

#write(content, file: nil, add_ext: true, file_ext: nil) ⇒ Object



42
43
44
45
46
# File 'lib/abide_dev_utils/files.rb', line 42

def write(content, file: nil, add_ext: true, file_ext: nil)
  valid_file = add_ext ? append_ext(file, file_ext) : file
  File.open(valid_file, 'w') { |f| f.write(content) }
  verify_write(valid_file)
end