Spandan Spandan - 3 months ago 8
Ruby Question

Ruby Project - Prevent a ruby file from directly being called from OS command line

I am doing a demo command line project in Ruby. The structure is like this:

/ROOT_DIR
init.rb
/SCRIPT_DIR
(other scripts and files)


I want users to only go into the application using
init.rb
, but as it stands, anyone can go into the sub-folder and call other ruby scripts directly.

Questions:


  1. What ways can above scenario be prevented?

  2. If I was to use directory permissions, would it get reset when running the code from a Windows machine to on Linux machine?

  3. Is there anything that can be included in Ruby files itself to prevent it from being directly called from OS command line?


Answer

You can't do this with file permissions, since the user needs to read the files; removing the read permission means you can't include it either. Removing the execute permission is useful to signal that these file aren't intended to be executed, but won't prevent people from typing ruby incl.rb.


The easiest way is probably to set a global variable in the init.rb script:

#!/usr/bin/env ruby

FROM_INIT = true
require './incl.rb'

puts 'This is init!'

And then check if this variable is defined in the included incl.rb file:

unless defined? FROM_INIT
    puts 'Must be called from init.rb'
    exit 0
end

puts 'This is incl!'

A second method might be checking the value of $PROGRAM_NAME in incl.rb; this stores the current program name (like argv[0] in many other languages):

unless $PROGRAM_NAME.end_with? 'init.rb'
    puts 'Must be called from init.rb'
    exit 0
end

I don't recommend this though, as it's not very future-proof; what if you want to rename init.rb or make a second script?

Comments