Pass ruby script file to rails console

后端 未结 7 1137
醉梦人生
醉梦人生 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:33

    Here's the hack I'm using:

    rr() {
        rails_root="$(bundle exec rails runner "puts Rails.root")"
        rp="$(relpath "$1" "$rails_root")"
        bundle exec rails runner "eval(File.read '$rp')"
    }
    relpath() {python -c "import os.path; print os.path.relpath('$1','${2:-$PWD}')";}
    

    Example:

    cd ~/rails_project/app/helpers
    rr my_script.rb
    

    Based on @moritz's answer here. I changed it, since the working directory for File.read is the Rails project root.

    I know this is some serious heresy, using python to help a ruby script. But I couldn't find a relpath method built into ruby.

    Credit: relpath() was taken from @MestreLion, Convert absolute path into relative path given a current directory using Bash

提交回复
热议问题