Pass ruby script file to rails console

后端 未结 7 1076
醉梦人生
醉梦人生 2021-01-29 20:51

Is there a way to pass ruby file, foo.rb to rails console. Expected results would be after console starts rails environment to run file.

Or any other way which

7条回答
  •  余生分开走
    2021-01-29 21:30

    Of these approaches mentioned earlier, none seemed clean and ideal like you would expect a standalone script to run (not get eval-ed or piped via < redirection), but finally this works perfect for me:

    (for Rails 3)

    Insert at the top of your script:

    #!/usr/bin/env ruby
    
    APP_PATH = File.expand_path(appdir = '/srv/staging/strat/fundmgr/config/application',  __FILE__)
    require File.expand_path(appdir + '/../boot',  __FILE__)
    require APP_PATH
    # set Rails.env here if desired
    Rails.application.require_environment!
    
    # your code here...
    

    Of course, set your own Rails app path in the APP_PATH line.

    That way, I can avoid having to enter any interactive irb or rails c and can test my script.rb from the shell prompt, before eg. scheduling it in crontab.

    It smoothly supports command-line parameters, too, and minimizes the levels of wrappers before getting to your code.

    CREDIT (also shows a Rails 2 example)

    http://zerowidth.com/2011/03/18/standalone-script-runner-bin-scripts-in-rails.html

提交回复
热议问题