Standalone ruby — How to load different environments from database.yml

前端 未结 2 943
眼角桃花
眼角桃花 2021-02-08 10:24

I have a background process that modifies records in a database. The models connect to the database using something like this:

dbconfig = YAML::load(File.open(\'         


        
2条回答
  •  攒了一身酷
    2021-02-08 10:33

    I'd recommend looking into using rails runner.

    Runner scripts have access to everything, including the database, but without all the view stuff from the MVC model. They are great for back-end tasks or jobs that work on the database but don't have any interface.

    You can also use rails rake instead, but I feel rake tasks are targeted at maintenance of the files and directories and for building structure, and runner scripts better for regular tasks, such as something you'd run from cron periodically.

    I have one I use for retrieving logs from a site, parsing them, then injecting them into one of my databases. There's no reason to run the job as part of the Rails app because there was no need for an interface. Running as a runner script fit nicely.

    The built-in help says:

    Usage: runner [options] ('Some.ruby(code)' or a filename)
    
        -e, --environment=name           Specifies the environment for the runner to operate under (test/development/production).
                                         Default: development
    
        -h, --help                       Show this help message.
    
    You can also use runner as a shebang line for your scripts like this:
    -------------------------------------------------------------
    #!/path/to/your/rails/app/script/rails runner
    
    Product.find(:all).each { |p| p.price *= 2 ; p.save! }
    -------------------------------------------------------------
    

    That last line:

    Product.find(:all).each { |p| p.price *= 2 ; p.save! }
    

    shows how easy it is.

提交回复
热议问题