user2462805
user2462805

Reputation: 1069

Rails, Create a Task in multiple environment?

I actually have few custom rake tasks. What I want to do is to create a task that will execute itself on two environments when you simply call it. I mean, when I run this :

rake initialize_global_settings

I want this to be executed on development and test environment.

Actually I'm constrained doing this :

rake initialize_global_settings (This will be executed in development environment by default, I don't really know why) and then I do this : rake initialize_global_settings RAILS_ENV=test

Is it possible to make a task doing both ?

Here's my task :

task :initialize_global_settings => :environment do
  puts "Generating all global settings parameters..."
  parameters = ["few", "parameters", "here"]

  parameters.each do |param|
    glob_set = GlobalSetting.new(:field_name => param,
                                  :field_value => "")
    if glob_set.save
      puts "#{param} created"
    else
      puts "#{param} already exist"
    end
  end

  puts "done."
end

Upvotes: 0

Views: 66

Answers (1)

user2462805
user2462805

Reputation: 1069

I found a solution doing this :

task :initialize_global_settings => :environment do
   puts "Generating all global settings parameters..."
   parameters = ["few", "parameters", "here"]
   environments = ['development', 'test']

   environments.each do |environment|
     Rails.env = environment
     puts "\nRunning Task in "+environment+" environment \n\n"
     parameters.each do |param|
       glob_set = GlobalSetting.new(:field_name => param,
                                     :field_value => "")
       if glob_set.save
         puts "#{param} created"
       else
         puts "#{param} already exist"
       end
     end
     puts "\nParameters have been set"
    end
 end

It works but I've got a conflict between same variables set in test and development environment and I don't know why.

Upvotes: 1

Related Questions