简体   繁体   中英

run ruby script in rails application

This may be a stupid question but I was just wondering where, or if its possible to run a ruby script which is kind of unrelated to the rails application I would like it to run in. To clarify, I am working on an automation test suite that is written mainly in bash, but I want to create a front end (my rails application) that allows other users to run automated tests not through the command line. So I guess basically I want a user to select certain parameters, from a database or form fields, then take those parameters and pass them to a ruby script which calls my bash automation script. I hope this is clear. Thanks!

If you want to call a script from a rails app it gets complex. You would want to use a background job or some sort of queue to run these jobs because they do block the server and your users would be waiting for the call to complete and the results to load, most likely hitting a timeout.

See delayed_job and you might want to try creating a small wrapper script in ruby that can interface with your application.

Good luck!

for short tasks you should use system or popen

when tasks are longer then they are still needed in case of delayed_job

You can add a script to your scripts folder in the root of your rails app. Start your script like this:

your script can be [name here].rb

The reason why we load in the environment is so we can use rails models and rails related things in your script:

#!/bin/env ruby

ENV['RAILS_ENV'] = "production" # Set to your desired Rails environment name
require '/[path to your rails app on your server]/config/environment.rb'
require 'active_record'

If you want to run this on your server, then you have to edit your crontab on your server. Or you can use the whenever gem (which I''m having trouble with, but the entire universe doesn't). Conversely, if you have heroku, then there's the heroku scheduler that makes running scripts easy.

You can run Ruby code with rails runner .

… let us suppose that you have a model called “Report”. The Report model has a class method called generate_rankings , which you can call from the command line using

$ rails runner 'Report.generate_rankings'

Since we have access to all of Rails, we can even use the Active Record finder method to extract data from our application.

 $ rails runner 'User.pluck(:email).each { |e| puts e }' charles.quinn@highgroove.com me@seebq.com bill.gates@microsoft.com obie@obiefernandet.com

Example taken from The Rails 5 Way by Obie Fernandez .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM