Ruby on Rails - Can I call a Controller:Method from a batch routine in windows? - ruby-on-rails

I'm relatively new to RoR working on Windows. I built a simple app in Rails that sends email using ActionMailer. I'd like to add a task to my windows scheduler to run a batch routine that calls my email method inside of my controller. The web app will not be running when I do this, so I can't do a CURL or something similar. Is there a way to run Ruby.exe with some args to launch a rails app (similar to irb) and call a controller:method?
Update: I took the advice in the answer I marked correct, but I thought I'd elaborate in case a RoR newbie like myself needs a bit more guidance.
I created a folder app\classes and I created a .rb file for my class
I had to create an initialize method to handle some setup
Created a few methods that simple return variables
I made sure I could run the steps in rails console
Created a file in lib\tasks with the code below
Ran this in DOS in the project folder - rake runMe --trace
task :runMe => :environment do
#s = ScrapeTools.new
#bears = #s.getBears
#bulls = #s.getBulls
UserMailer.stock_email(#bears,#bulls).deliver
end
Please let me know if you see any errors

There is. rails runner <path to script> will run the given script under your Rails app. Have some docs

This is a good example of why you don't want to put logic in your controller. Much better than putting that functionality in a controller method, refactor it to a method in a module or class. Then you call that method from your controller as well as from a rake task that is straight-forward to execute in your batch routine.

Related

Where do I put a recurring script that updates database from api in rails

I have a Rails app set up with a model Account that should be updated every morning with data coming from an external API I'm calling (a CRM). Basically either I create new accounts in my app that I find in the CRM and some of the fields that are mapped with my columns, either I find the account if it already exists and I update it.
So far, I've been putting this code into the seeds.rb file and from Heroku, where the app is hosted, I set up a scheduler with the command : rails db:seed that runs periodically.
My issue is that I'm sure there is a better way of doing this. I've read about rake tasks but I did not quite understand how that applied to my case. Otherwise I thought of putting my method in the models/account.rb file as a self method. But I don't really know how I can invoke it in a rake command to allow me to set up a scheduler in Heroku.
Any idea on where would be the best place to put this method, and how to call it from command line?
Thanks in advance.
You can create a script directory in your project, and put your script from db/seeds.rb into this directory, maybe called update_accounts.rb. Then you can run it with
rails runner script/update_accounts.rb
and schedule that task in heroku. More info about rails runner here.
I would suggest using a background processor such as Sidekiq: https://github.com/mperham/sidekiq
Once using Sidekiq, you need a scheduler like https://github.com/moove-it/sidekiq-scheduler to make sure it happens periodically as you require.
This will become easier to maintain as your application grows and you need more workers. It also moves your scheduling into version control.

Save and Run Rails Script

Is it possible to write a set of commands - similar to what you'd find in a controller - but save it as a standalone file in my rails app that I could call up and run from the console?
For instance, something to loop through my database and run some ActiveRecord commands to modify data that may need to be cleaned up from time to time, but I don't want to live inside a controller. It's large - too large for me to copy/paste it into the rails console - which is why I'm trying to make a file out of it.
You can write your code into a separate file, let's say myCode.rb and run it from the console with rails runner myCode.rb (run this command from the directory you saved the file to). rails runner gives you access to your rails environment.
Hope this helps.
I took your advice, Tony, and looked into making my own rake tasks and that seemed to do the trick!
I made a new .rake file inside my lib/tasks folder and just copied and pasted my block of code inside there. I had to set it to inherit from the environment, as stated in the post I read, but it seems to work fine now - thanks for the tip!

Writing a command line helper utility with access to a Rails application

I'm developing a standalone app that is self composed and has some data (task lists). I'm now looking to supplement this data with an outside source (the Asana API).
I was looking to implement this as a command-line tool that is invoked by cron. However, I can't seem to be able to figure out how to get access to my Rails environments from the script.
So, the question would be: how do I get the functionality to get and manipulate models from within a simple ruby script inside {app_root}/bin/.
You could do something like this:
require '/path/to/app/config/application'
MyApp::Application.instance.initialize!
# now you have access to your app environment
But usually this is solved by creating a rake task in your application that you can run by CRON.

Rails execute script

I am building a script in on of my controllers to fill a database with an excel files data. I would build the function, then access it through a route. (That i guess i can protect with cancan) But i thought about it, and it doesn't seem very ... 'Railsy'.
I know the scripts folder exists, and it is probably for these kinds of tasks. I've tried googling stuff like 'rails execute script' and other stuff, but i can't find any good advice for what to do next.
I'm sorry if this seems kind of stupid, but in my apps i've been kind of hacking around stuff to make it work, so any advice on this task would be appreciated.
If you need to upload the file in the app and process it, it should probably go in the "lib"directory and be accessed like any other Ruby library/module/etc.
If it's something you need to run locally, "on demand", "scripts" is fine. If you need access to your rails environment when running it like any Rails models, you can run it from "rails console" or "rails runner".
As Aln said, there are a variety of ways it could be scheduled as well.
You could simply do
#!/usr/bin/env ruby
require 'rubygems'
# regular ruby code here
and have it running just like any other util. Of course you can always call any *.rb with simply
ruby somescript.rb
If you need some scheduled script, check into rufus-scheduler gem.

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.

Resources