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.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With