branch14
branch14

Reputation: 1262

Setting file permissions in Ruby with File.open

I wrote this to survey the permissions of files created with varying perm values

[0644, 0664, 0755, 0775].each do |perm|
  filename = "file#{perm}"
  File.open(filename, 'wb', perm) { |f| f.puts 'test' }
  puts '%o' % File::Stat.new(filename).mode
end

When run this will output:

100644
100644
100755
100755

Which is not what I expected. Why is the group write permission on the 2nd and 4th file not set?

Upvotes: 2

Views: 3026

Answers (1)

Jordan Samuels
Jordan Samuels

Reputation: 997

According to http://www.ruby-doc.org/core-2.1.2/File.html#method-c-new, Ruby simply uses the open(2) system call. That respects the umask settings (removing any bits that are set in umask before actually setting permission bits).

Thus, you can achieve group writability by setting your umask to clear the group writable bit. E.g. set it to 0002. More details here.

Upvotes: 4

Related Questions