File

Upload a file

uploaded_io = params[:file]
#params[:file] is an ActionDispatch::Http::UploadedFile object
path_original = "#{Time.now.to_i}#{File.extname(uploaded_io.original_filename)}"
File.open(Rails.root.join('public', 'uploads', path_original), 'wb') do |file|
  file.write(uploaded_io.read)
end

Check if the file exists

File.exist?(file_path)

Get file extension

File.extname(uploaded_io.original_filename)

Get file name without extension

File.basename( "path1/path2/abc.png", ".*" )
#=> "abc"

Safe join pathname and filename

File.join("path1", "path2", "filename.abc")
#=> "path1/path2/filename.abc"

File.join("path1/", "/path2/", "/filename.abc")
#=> "path1/path2/filename.abc"

File.join vs. Rails.root.join

The difference between these two methods is as the path begin with a slash "/", for example:

# RAILS_ROOT_PATH: your local rails root path
File.join(Rails.root, '/path/ruby.png')
#=> RAILS_ROOT_PATH/path/ruby.png

Rails.root.join('/path/ruby.png')
#=> /path/ruby.png

Rails.root.join('path/ruby.png')
#=> RAILS_ROOT_PATH/path/ruby.png

File.open

  File.open("spec/support/data/something.txt", "r") { |file| file.read }

Create a new folder

FileUtils.mkdir_p(dir) unless File.directory?(dir)

save values into a yaml file

# before
# config/any.yml
---
one:
  a: 1
  b: 2
  c: 3
config = YAML::load_file 'config/any.yml' 
config['one'] = { "a" => "2", "b" => "3", "c" => "4" }
File.open(citrus_pay_config_file, "w") { |file| file.write config.to_yaml }
# after
# config/any.yml
---
one:
  a: 2
  b: 3
  c: 4

Reference

results matching ""

    No results matching ""