Raaz
Raaz

Reputation: 1771

Create a symlink using ruby

I am trying to create a symlink for the created file but I get an error like File exists - (/etc/nginx/sites-available/sushant.com, /etc/nginx/sites-enabled/sushant.com) (Errno::EEXIST)

Here is my code

    require 'fileutils'
open('/etc/hosts') do |f|
  matches = []
  vhosts = []
  f.readlines.each do |lines|
    matches << lines if lines =~ /.*.com/
  end
  matches.each do |val|
    val.split.each do |x|
      vhosts << x if x =~ /.*.com/
    end
  end
  vhosts.each do |domain|
#put the path to sites-enabled
    unless File.file? "/etc/nginx/sites-available/#{domain}"
      open("/etc/nginx/sites-available/#{domain}", 'w') do |g|
        g << "server { \n"
        g << "\tlisten 80 default_server;\n"
        g << "\tlisten [::]:80 default_server ipv6only=on;\n"
        g << "\troot /usr/share/nginx/html;\n"
        g << "\tindex index.html index.htm;\n"
        g << "\tserver_name localhost;\n"
        g << "\tlocation / {\n"
        g << "\t\ttry_files $uri $uri/ =404;\n"
        g << "\t}\n"
        g << "}\n"
        g << "server {\n"
        g << "\tpassenger_ruby /path/to/ruby;\n"
        g << "\trails_env development;\n"
        g << "\tlisten 80;\n"
        g << "\tserver_name #{domain};\n"
        g << "\troot /usr/share/nginx/html/#{domain}/public;\n"
        g << "\tpassenger_enabled on;\n"
        g << "}\n"
      end
      File.symlink  "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}"
    end
  end

  p vhosts
end

Why is the EEXIST error occurs after I run the script? Am I missing out on something?

Upvotes: 5

Views: 4653

Answers (1)

Raaz
Raaz

Reputation: 1771

I have found out that I should have placed File.symlink "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}" first then the action to create the file.

Upvotes: 5

Related Questions