Using parameters with ruby ​​requires

Is it possible to require files with arguments / parameters?

for instance

resource.rb has

mode = ARGV.first if mode == "prod" #use prod db else #use test db end 

And main.rb requires it with parameters with something like

 require_relative './resource.rb prod' 

If this is not possible or bad practice, please let me know. I think I could use version control to switch between test and prod, but it's a bit backward.

(prod and test are used only for differentiation. This is a fairly easy project and is not commercial if it matters :))

Using Ruby 1.9.3 for Windows XP.

I am surprised that there were no answers to this. Only material on the use of precious stones and the use of ruby ​​with parameters, but not both at the same time.

+4
source share
5 answers

You cannot do this with require, but you can set the environment variable:

In main.rb :

 ENV["mode"] = ARGV.first require_relative './resource' 

In ./resource.rb :

 mode = ENV.fetch("mode") if mode == "prod" #use prod db else #use test db end 

The advantage of using environment variables for configurations is that you can have the same logic for multiple files. This is the way to do Heroku stuff.

See the Heroku 12 factor application .

+6
source

No, you cannot pass parameters with require .

I would suggest doing something like this:

 def use_mode(mode) # your if statements end 

and then

 require 'file' use_mode :development 

And end it in a class / module for cleaner code :)

+6
source

require_relative only accepts the relative path to the file relative to the path to the required files, you can do something like this:

 # in main.rb require_relative 'resource' # in cli ruby main.rb prod 
+1
source

No, you cannot pass parameters with a request. But you define the parameter before you require anything.

Example ressource.rb:

 RESOURCE_MODE = :prod unless defined? RESOURCE_MODE case RESOURCE_MODE when :prod #your productive settings when :test #your test settings else raise ArgumentError end 

When you invoke it with require 'resource' , you are productive.

When you call it in test mode, you can use:

 RESOURCE_MODE = :test require 'resource' 

Another possibility: you define resource_prod.rb and a resource_test.rb . Then you can choose which file you need.

+1
source

First of all, this will not work. Calling an application using a command is different from internal requirements, so there are no parameters passed to it. Require - read and evaluate the file in a nutshell. To support support functionality, you must use configuration and classes.

 # resource.rb class DB def initialize(db_config ={}) #connect to db end end # main.rb connection = DB.new(mode == "prod" ? prod_db_config : development_db_config) 
0
source

All Articles