Ben
Ben

Reputation: 3357

Rails creating a simple function to run in console for system wide

I want to do something as simple as:

rails c
> ping
=> pong

So I can write an action like:

def ping puts "pong" end

But where do I put it? How do I make it work without having to instantiate a new model? application_helper.rb doesn't work, nor does application_controller.rb

Upvotes: 0

Views: 172

Answers (2)

JohnStep
JohnStep

Reputation: 26

In case you would like to run custom methods in Rails specifically, you can define you helper methods in a module in lib directory

# lib/custom_console_methods.rb

module CustomConsoleMethods
  def ping
    puts 'pong'
  end
end

Then in the application.rb file, pass a block to console that includes your module into Rails::ConsoleMethods

# config/application.rb

module YourRailsApp
  class Application < Rails::Application
    console do
      require 'custom_console_methods'
      Rails::ConsoleMethods.include(CustomConsoleMethods)
    end
  end
end

If you would like to run it in system wide, just put the methods in ~/.irbrc file. It gets loaded every time you run irb or rails console

def ping
  puts 'pong'
end

Upvotes: 1

BTL
BTL

Reputation: 4656

You can create a folder services and in it you create a file ping_service.rb

class PingService
 def ping
  puts 'pong'
 end
end

and then in your console :

rails c
> PingService.new.ping
=> "pong"

Upvotes: 2

Related Questions