Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using parameters with ruby require

Is it possible to require files with arguments / parameters?

For example

resource.rb has

mode = ARGV.first

if mode == "prod"
  #use prod db
else
  #use test db
end

And main.rb requires it with params with something like

require_relative './resource.rb prod'

If this is not possible or bad practice please let me know. I guess I could use version control to switch between test and prod but it seems a little retarded.

(prod and test used only to differentiate. This is a pretty lightweight project and is not commercial if it makes any difference :) )

Using Ruby 1.9.3 on Windows XP thanks.

I am surprised that there were no answers on this already. Only stuff on using gems and using ruby with parameters but not both at the same time.

like image 374
JoeyC Avatar asked Dec 27 '12 08:12

JoeyC


People also ask

How do you pass parameters in Ruby on Rails?

Inside of your button_to, you can add attributes (much like in HTML). In the code snippet above, I added a class attribute as well. In a button_to, you simply have to add an attribute called “params:” with the params passed as a hash. The params will then be accessible in your controller.

How do you accept number of arguments in Ruby?

A method defined as def some_method(**args) can accept any number of key:value arguments. The args variable will be a hash of the passed in arguments.


2 Answers

You cannot do that via a require, but you could set an 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 across multiple files. That's the Heroku way of doing things.

See Heroku's 12 factor app.

like image 71
Jean-Louis Giordano Avatar answered Oct 14 '22 09:10

Jean-Louis Giordano


No, you cannot pass parameters with require.

I'd suggest doing something like this:

def use_mode(mode)
  # your if statements
end

and then

require 'file'
use_mode :development

And wrap it up in a Class / Module for cleaner code :)

like image 33
Dogbert Avatar answered Oct 14 '22 07:10

Dogbert