when rails server start , how to Initialize some my own task - ruby-on-rails

eg: I wanna run something automatically when start the server
I get a not so clear view about that, is there something about rake?
...
I do remove the stupid example

You could create an initializer file in config/initializers folder for example task_scheduler.rb and then use Rufus scheduler to run tasks:
scheduler = Rufus::Scheduler.start_new
scheduler.in '4s' do
autocallprocess_method
end
scheduler.every '1m' do
autocallprocess_method
end

So you want to run a piece of code that in initialises something on server startup, rather than as a rake task/controller action etc? Simplest way is to create a file in config/initializers and put any ruby code in there.
Any file in this folder gets run on server startup.

Related

Does Rails initializers gets called when I run rails console

I want to put my chargify conf inside the initializer,
but I found the initializer won't execute in my rails c, is there a way to invoke my initializers so I can test in my console?
Chargify.configure do |c|
c.api_key = "keykey"
c.subdomain = "test-site"
end
The config/initializers will execute, but only once, on initial load. So if you're making changes to config/initializers while the console is running you won't see the results of those changes happening.
Your best option is to stop and restart rails c, or you can type the reload! command in the console.
Also, if you are using spring that will sometimes prevent changed initializers from reloading. in that case do spring stop before you restart the console.
Yes, every .rb file in config/initializers is run whenever you run the console, run a rake task, or run your tests. Additonally, the environment configuration (config/environments) is run before the initializers.
Apparently not anymore unless you disable spring:
export DISABLE_SPRING=1

Rake task during application initialization rails

I want to execute a rake task when the server of my application starts.
In config/application.rb i put the following:
if !Rails.env.production?
Rake::Task[ "init:db_records" ].invoke
end
The rake task is well defined, and runs without a problem if i invode it from terminal
rake init:db_records
But when placed in config/application.rb (or even in any initializers/*) i got the following error.
Don't know how to build task 'init:db_records'
What is the way to execute a rake task when the server starts ?
Thanks!
Rails already has a mechanism for setting up a development database -- rake db:seed. It does not run automatically when you start the app, but it does run as part of rake db:setup.
Unless you have a good reason, it's usually best to stick the conventions that Rails provides.
For those who encounter the same problem in the future.
I achieved this by creating a new file in the initializers directory, where i put the code of the rake task.
The advantage of this at this point, is that the application is already loaded, so you have access to ActiveRecord functions...
Putting the code directly in config/application.rb didn't work, since my models were not loaded yet.
Hope it will help!
Your Rake tasks are (likely) defined in a Rakefile. The initializer has no idea that file even exists, so it doesn't know about the tasks within.
The easiest way to circumvent this is by doing something like this:
Dir.chdir(Rails.root) do
`rake init:db_records`
end
That is, change the working directory to the root rails directory, then running the command.

Capistrano 3, using upload! in a task in lib/capistrano/tasks

I'm using Capistrano 3 and I want to create my own task. So I created a file my_new_thing.rake in lib/capistrano/tasks and I can see the task when I run cap -T. But... some of the methods aren't available. When I try to use upload! I get
cap aborted!
NoMethodError: undefined method `upload!' for main:Object
But if I move the same task into config/deploy.rb then then upload! method is available.
So what's going on? How do I create new Capistrano tasks put them in separate file and have them work?
I had the same problem, I created my own recipe in a separate file which I loaded in deploy but couldn't get upload! to work.
What fixed it for me was adding a role filter inside the task making my final recipe look something like this:
namespace :figaro do
desc "Transfer Figaro's application.yml to shared/config"
task :upload do
on roles(:all) do
upload! "config/application.yml", "#{shared_path}/config/application.yml"
end
end
end
before "deploy:check", "figaro:upload"
I hope that helps!
You can create a folder config/recipes for your capistrano recipes if you want to keep them in separate files.
Use the .rb extension since this isnt a regular rake task.
In config/deploy.rb add this line
load File.expand_path('../recipes/my_new_thing.rb', __FILE__)
If you want to use the rake tasks then you will need to create a task in the deploy file which calls that rake tasks which is not that smart of a move. So as #Sharagoz suggested the best route will be to create your own recipe file and include that in.

How to write and execute an individual rake task outside the Rails application folder

How do you write a rake task outside the Rails application directory and make it run.
For example, say write a sample rake task
task :dummy do
puts User.first.first_name
end
this task is under ~/fun/sample.rake
And my rails application is located at ~/my_app/
Now I need to run the sample.rake. I know i need to load the environment, DB etc., etc., how do i do that? Stuck at this for the past hour.
I tried the one below, obviously it did not work because it did not know how to build it.
rake -f ~/my_app/Rakefile dummy
Note: I should not touch the files inside the Rails application but I can write whatever I want inside the fun directory
You need to create a Rakefile and load the rake gem. See this answer: Ruby: Accessing rake task from a gem without Rails

Executing Ruby script in an Rails application

I can run the following commands in the console for my Rails application and import CSV file into my database.
require 'csv'
# row will be an array with the fields in the order they appear in the file
CSV.open('myfile.csv', 'r') do |row|
# assuming the fields in the CSV file are in order npa, nxxFrom, nxxTo, trnk
# create and save a Trunk model for each row
Trunk.create!(:npa => row[0], :nxxFrom => row[1], :nxxTo => row[2], :trnk => row[3])
end
However I'd like to facilitate the process by just creating a script for it. The problem is I don't know how to write a script that is application specific. In order for the above commands to run, I need to launch console in the application folder by the following:
ruby script/console
So simply copy/pasting the commands into an .rb file and executing won't work.
Any help will always be appreciated :)
Why not use script/runner "<code or filename here>? to run the script? The runner script executes the script in the give application context without having a console.
You could make it a rake task which inherits from environment. Place it into lib/tasks/your_task.rake:
task :your_task => :environment do
# code goes here
end
Then run it using rake your_task. It can be called anything you want.
You need to invoke the rails environment in the script.
Try adding this at the top of you file:
RAILS_ENV = ARGV[0] || "production"
require File.join(File.dirname(__FILE__), *%w[.. config environment])
# assumes script is placed one level below the root of the application
# second parameter is the relative path to the environment directory of your rails app

Resources