Pass Ruby Script File to Rails Console

Pass ruby script file to rails console

In the meantime, this solution has been supported.

rails r PATH_TO_RUBY_FILE

Much simpler now.

Pass an argument when calling a script in Rails console with load command

It is dirty hack but seems like you can assign array to ARGV and use it from loaded scripts as you wanted in question:

$  Temp  cat argv.rb
p ARGV
$ Temp irb
2.1.0 :001 > ARGV
=> []
2.1.0 :002 > load 'argv.rb'
[]
=> true
2.1.0 :003 > ARGV = ['A', 'B']
(irb):3: warning: already initialized constant ARGV
=> ["A", "B"]
2.1.0 :004 > load 'argv.rb'
["A", "B"]
=> true
2.1.0 :005 >

How to run script before every Rails console invocation?

Put the code you want to execute into .irbrc file in the root folder of your project:

echo 'ActsAsTenant.current_tenant = User.find(1).account' >> .irbrc
bundle exec rails c # ⇐ the code in .irbrc got executed

Sidenote: Use Pry instead of silly IRB. Try it and you’ll never roll back.

How to pass text file as an argument in Ruby

On your shell, invoke the ruby script followed by the name of the .txt file, like this:

ruby foo.rb test_list.txt

The variable ARGV will contain references to all the arguments you've passed when invoking the ruby interpreter. In particular, ARGV[0] = "test_list.txt", so you can use this instead of hardcoding the name of the file:

File.open(ARGV[0]).each do |line|
puts line
end


On the other hand, if you want to pass the content of the file to your program, you can go with:

cat test_list.txt | ruby foo.rb

and in the program:

STDIN.each_line do |line|
puts line
end

Pass variables to Ruby script via command line

Something like this:

ARGV.each do|a|
puts "Argument: #{a}"
end

then

$ ./test.rb "test1 test2"

or

v1 = ARGV[0]
v2 = ARGV[1]
puts v1 #prints test1
puts v2 #prints test2

How can I start a Rails console with command line arguments?

You should specify the arguments like below,

➜  test_app git:(master) ✗ RAILS_E=rails_test rails c -- --rails_env_test test
Loading development environment (Rails 4.2.1)
[1] pry(main)> ARGV
=> ["--rails_env_test", "test"]
[2] pry(main)>

or

➜  test_app git:(master) ✗ RAILS_E=rails_test rails c -- --rails_env_test=test               
Loading development environment (Rails 4.2.1)
[1] pry(main)> ARGV
=> ["--rails_env_test=test"]
[2] pry(main)>

Then you can process the ARGV to get the passed values. Please let me know if you need more on this.

Running rails console command from nodejs

I think what you want is rails runner instead of console. Either pass it a line of ruby code or a filename. It will run in the rails environment, not just the ruby irb environment.

Run ruby file in rails console

You can run the code in the file in the context of your rails app with

rails runner

http://guides.rubyonrails.org/command_line.html#rails-runner

Pass arguments to Ruby when running Rails

Try this:

  jruby --args -S rails ...


Related Topics



Leave a reply



Submit