Rails console: Run a Ruby file several times - ruby-on-rails

Rails provides a very useful console ('script/console').
I write a ruby file and run it in the console using require foo.rb.
It works fine the first time, but the second and next require foo.rb does not run my script (require does not reload it).
Do you have any tips/tricks?

require is used to load extensions - so the code will execute once, to get the extensions to be present in your environment, but subsequent requires won't do anything, because the job has already been done.
load, on the other hand, loads and executes the code every time.
As already mentioned, if you just want to run your script and you need the Rails environment, then consider using script/runner

You should probably try either loading your rails environment in a script or using rake. Also consider using script/runner.
Here is an old and possibly outdated example of using your rails environment in a script. A more recent and detailed version here.
A stack overflow answer

Related

change rails environment from within ruby file then change back

I have a test-automation app that runs tests against user params against a rails app.
The tests execution in the Ruby app looks like this:
config = RSpec.configuration
json_formatter = RSpec::Core::Formatters::JsonFormatter.new(config.out)
reporter = RSpec::Core::Reporter.new(json_formatter)
config.instance_variable_set(:#reporter, reporter)
RSpec::Core::Runner.run(["#{Rails.root}/spec/features/example_spec.rb"])
puts json_formatter.output_hash
This works great but runs in the current environment, i.e. development.
I want to change the Rails environment so that this code is executed in the test environment and then change it back.
Does anyone know how to do this?
thanks
Richard
You can always change the environment for a single (or set of) commands like this in unix-like environments:
RAILS_ENV=testing bundle exec rspec
or whatever you need to execute. You could, for example, define a custom rake task that contains your spec-running logic and call that as I outlined above.
Using this concept and taking it a step further, you could execute shell commands directly from Ruby and have a custom environment variable set for only this command. In this shell commands you could execute arbitrary Ruby code (e.g. via ruby -e ...) or even call another Ruby file that properly initializes whatever you need within your desired environment.
I think it would be really bad practice to try to change the current environment from within your code, even if it is somehow possible. I would personally stick with a custom, dedicated, rake task which I can call from my command line with whatever environment I need.

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.

How can I run Ruby specs and/or tests in MacVim without locking up MacVim?

About 6 months ago I switched from TextMate to MacVim for all of my development work, which primarily consists of coding in Ruby, Ruby on Rails and JavaScript.
With TextMate, whenever I needed to run a spec or a test, I could just command+R on the test or spec file and another window would open and the results would be displayed with the 'pretty' format applied. If the spec or test was a lengthy one, I could just continue working with the codebase since the test/spec was running in a separate process/window. After the test ran, I could click through the results directly to the corresponding line in the spec file.
Tim Pope's excellent rails.vim plugin comes very close to emulating this behavior within the MacVim environment. Running :Rake when the current buffer is a test or spec runs the file then splits the buffer to display the results. You can navigate through the results and key through to the corresponding spot in the file.
The problem with the rails.vim approach is that it locks up the MacVim window while the test runs. This can be an issue with big apps that might have a lot of setup/teardown built into the tests. Also, the visual red/green html results that TextMate displays (via --format pretty, I'm assuming) is a bit easier to scan than the split window.
This guy came close about 18 mos ago: http://cassiomarques.wordpress.com/2009/01/09/running-rspec-files-from-vim-showing-the-results-in-firefox/ The script he has worked with a bit of hacking, but the tests still ran within MacVim and locked up the current window.
Any ideas on how to fully replicate the TextMate behavior described above in MacVim?
Thanks!
There is a plugin called vim-addon-background-cmd that can allow you to run tasks in the background instead of locking up the vim interface. You would have to create the call to run through the background command. See the docs for more information on how to do that.
A few months back I was looking for this same exact thing. Then I discovered autotest with rspec. Now I keep a separate terminal window open which shows my last run tests. If I change any relavent code files my tests are automatically run for me (the files are watched and if they change the tests run).
If you want the same autotest type behavior in a non-rails project you can look at the watchr gem. It's functionality is similar to autotest but you can use it in ANY framework.

Gems slowing down Rails test startup, can I selectively disable these?

I have a terrible Rails test startup time. When running a single functional test that may take 2 seconds to run, the total time from execution to returning to the command line could be up to 10-15 seconds.
There are two gems I know are definitely getting in the way. A Facebook and Flickr gem (Facebooker, Flickraw).
Facebooker will always print the following message when any test is run:
/vendor/gems/facebooker-0.9.5/lib/facebooker.rb:23: warning: already initialized constant VERSION
And Flickraw appears to be making a network connection every single time to retrieve a list of what I believe are API calls it can make.
Can I selectively turn these gems off during test time? I'd really like to get my test run as close to how long the actual test takes to run as possible. Also, I have tried the rails_test_server gem and am having some difficulties as this is a very large project and the gem is hitting some conflicts somewhere in the project that I haven't resolved. But I believe this Facebook and Flickr gem problem should have a resolution somewhere.
How do you use those gems? Do you have a require somewhere in your config/environment.rb? If so you could add those requires to the development and production environment files, but not to the test environment file.
If you're able to run your application without loading all of the gems, that's probably a good indication that either you didn't really use the gem in the first place, or your tests are insufficient.
But yeah, the right way of doing this would be to move the gem loading into the development and production specific environment files.

Resources