1

Edit: The console should remain open afterwards. I don't want to run a console command outside of the console.

I open a Rails Console like this from a Bash prompt: bundle exec rails console

Every time I open it, I need to run a command like this: SomeModule::SomeClass.someMethod('myString')

I'd like to combine these two commands into a single one that looks something like this: bundle exec rails console -s myString (or more likely a compact Bash function).

I tried bundle exec rails console && SomeModule::SomeClass.someMethod('myString') and bundle exec rails console; SomeModule::SomeClass.someMethod('myString') but those did not work.

abc123
  • 8,043
  • 7
  • 49
  • 80

2 Answers2

1

Why you want this in rails console? Rails have rake task to do so, which can be defined as below

namespace :pick do
  desc "Pick a random user as the winner"
  task :winner => :environment do
    puts "Winner: #{pick(User).name}"
  end

  desc "Pick a random product as the prize"
  task :prize => :environment do
    puts "Prize: #{pick(Product).name}"
  end

  desc "Pick a random prize and winner"
  task :all => [:prize, :winner]

  def pick(model_class)
    model_class.find(:first, :order => 'RAND()')
  end
end

and executed by rake pick:winner. You can write any ruby code inside task :prize => :environment do and end

Check out more at http://railscasts.com/episodes/66-custom-rake-tasks

Or

you can write initializer to do so inside config/initializers/ and conditionally specify code to run like,

if defined?(Rails::Console)
 # in Rails Console
else
 # Not in Rails Console
end 
maximus ツ
  • 7,949
  • 3
  • 25
  • 54
0

I am using marco-polo gem for this purpose. Add the gem to the Gemfile, create .irbrc.rb and add SomeModule::SomeClass.someMethod('myString') to it.

UPD: Also, if you don't want to leave the console opened after you ran the command, just rails runner:

bundle exec rails runner "SomeModule::SomeClass.someMethod('myString')"
DNNX
  • 6,215
  • 2
  • 27
  • 33