user6589814 user6589814 - 1 month ago 9
Ruby Question

Ruby on Rail - Create a folder and .txt file when create new record

I am building a application where companies can add many domains under their account.

What I want to achieve is: When a domains is

created
, in my
public/domains
folder I want to create a new folder with folder name =>
domain id
and add a
.txt
file with same naming convention.

Example:

Public // This is public folder in Rails
--- domains
---- 2 // This is domain ID
--- 2.txt


What I have now:

class Domain < ActiveRecord::Base
def create_folder
dir = Dir.mkdir("#{Rails.root}/public/domains/#{self.id}")
file = File.dirname("#{Rails.root}/public/domains/#{self.id}/#{self.id}.txt")
end
end


This does create the folder but doesn't creates the
.txt
file.

Answer

File.dirname does not create a file.

You want:

filename = Rails.root.join("/public/domains/#{id}/#{id}.txt")

File.open(filename, 'wb') do |file|
  file << "My content"
  file << "More content"
end

Be sure to create the directory before

As for your use case:

Don't use a file. Don't store it public. Use Redis or similar if needed. But first just try if your DB can't cope with the load. Or did you try and hit a limit?

Be aware that everything in /public is public which means that one can access it through your webserver.

A non Rails example:

require 'fileutils'
id = 123
filename = "/tmp/public/domains/#{id}/#{id}.txt"
FileUtils.mkdir_p(File.dirname(filename))
File.open(filename, 'wb') do |file|
  file << "My content"
  file << "More content"
end