The Rails Command Line — Ruby on Rails Guides (2024)

This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.

1 Creating a Rails App

First, let's create a simple Rails application using the rails new command.

We will use this application to play and discover all the commands described in this guide.

You can install the rails gem by typing gem install rails, if you don't have it already.

1.1 rails new

The first argument we'll pass to the rails new command is the application name.

$ rails new my_app create create README.md create Rakefile create config.ru create .gitignore create Gemfile create app ... create tmp/cache ... run bundle install

Rails will set up what seems like a huge amount of stuff for such a tiny command! We've got the entire Rails directory structure now with all the code we need to run our simple application right out of the box.

If you wish to skip some files from being generated or skip some libraries, you can append any of the following arguments to your rails new command:

ArgumentDescription
--skip-gitSkip git init, .gitignore, and .gitattributes
--skip-dockerSkip Dockerfile, .dockerignore and bin/docker-entrypoint
--skip-keepsSkip source control .keep files
--skip-action-mailerSkip Action Mailer files
--skip-action-mailboxSkip Action Mailbox gem
--skip-action-textSkip Action Text gem
--skip-active-recordSkip Active Record files
--skip-active-jobSkip Active Job
--skip-active-storageSkip Active Storage files
--skip-action-cableSkip Action Cable files
--skip-asset-pipelineSkip Asset Pipeline
--skip-javascriptSkip JavaScript files
--skip-hotwireSkip Hotwire integration
--skip-jbuilderSkip jbuilder gem
--skip-testSkip test files
--skip-system-testSkip system test files
--skip-bootsnapSkip bootsnap gem

These are just some of the options that rails new accepts. For a full list of options, type rails new --help.

1.2 Preconfigure a Different Database

When creating a new Rails application, you have the option to specify what kindof database your application is going to use. This will save you a few minutes,and certainly many keystrokes.

Let's see what a --database=postgresql option will do for us:

$ rails new petstore --database=postgresql create create app/controllers create app/helpers...

Let's see what it put in our config/database.yml:

# PostgreSQL. Versions 9.3 and up are supported.## Install the pg driver:# gem install pg# On macOS with Homebrew:# gem install pg -- --with-pg-config=/usr/local/bin/pg_config# On Windows:# gem install pg# Choose the win32 build.# Install PostgreSQL and put its /bin directory on your path.## Configure Using Gemfile# gem "pg"#default: &default adapter: postgresql encoding: unicode # For details on connection pooling, see Rails configuration guide # https://guides.rubyonrails.org/configuring.html#database-pooling pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>development: <<: *default database: petstore_development...

It generated a database configuration corresponding to our choice of PostgreSQL.

2 Command Line Basics

There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:

  • bin/rails console
  • bin/rails server
  • bin/rails test
  • bin/rails generate
  • bin/rails db:migrate
  • bin/rails db:create
  • bin/rails routes
  • bin/rails dbconsole
  • rails new app_name

You can get a list of rails commands available to you, which will often depend on your current directory, by typing rails --help. Each command has a description, and should help you find the thing you need.

$ rails --helpUsage: bin/rails COMMAND [options]You must specify a command. The most common commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") ...All commands can be run with -h (or --help) for more information.In addition to those commands, there are:about List versions of all Rails ...assets:clean[keep] Remove old compiled assetsassets:clobber Remove compiled assetsassets:environment Load asset compile environmentassets:precompile Compile all the assets ......db:fixtures:load Load fixtures into the ...db:migrate Migrate the database ...db:migrate:status Display status of migrationsdb:rollback Roll the schema back to ...db:schema:cache:clear Clears a db/schema_cache.yml filedb:schema:cache:dump Create a db/schema_cache.yml filedb:schema:dump Create a database schema file (either db/schema.rb or db/structure.sql ...db:schema:load Load a database schema file (either db/schema.rb or db/structure.sql ...db:seed Load the seed data ...db:version Retrieve the current schema ......restart Restart app by touching ...tmp:create Create tmp directories ...

2.1 bin/rails server

The bin/rails server command launches a web server named Puma which comes bundled with Rails. You'll use this any time you want to access your application through a web browser.

With no further work, bin/rails server will run our new shiny Rails app:

$ cd my_app$ bin/rails server=> Booting Puma=> Rails 7.0.0 application starting in development=> Run `bin/rails server --help` for more startup optionsPuma starting in single mode...* Version 3.12.1 (ruby 2.5.7-p206), codename: Llamas in Pajamas* Min threads: 5, max threads: 5* Environment: development* Listening on tcp://localhost:3000Use Ctrl-C to stop

With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open http://localhost:3000, you will see a basic Rails app running.

You can also use the alias "s" to start the server: bin/rails s.

The server can be run on a different port using the -p option. The default development environment can be changed using -e.

$ bin/rails server -e production -p 4000

The -b option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a -d option.

2.2 bin/rails generate

The bin/rails generate command uses templates to create a whole lot of things. Running bin/rails generate by itself gives a list of available generators:

You can also use the alias "g" to invoke the generator command: bin/rails g.

$ bin/rails generateUsage: bin/rails generate GENERATOR [args] [options]......Please choose a generator below.Rails: assets channel controller generator ... ...

You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!

Using generators will save you a large amount of time by writing boilerplate code, code that is necessary for the app to work.

Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:

All Rails console utilities have help text. As with most *nix utilities, you can try adding --help or -h to the end, for example bin/rails server --help.

$ bin/rails generate controllerUsage: bin/rails generate controller NAME [action action] [options]......Description: ... To create a controller within a module, specify the controller name as a path like 'parent_module/controller_name'. ...Example: `bin/rails generate controller CreditCards open debit credit close` Credit card controller with URLs like /credit_cards/debit. Controller: app/controllers/credit_cards_controller.rb Test: test/controllers/credit_cards_controller_test.rb Views: app/views/credit_cards/debit.html.erb [...] Helper: app/helpers/credit_cards_helper.rb

The controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.

$ bin/rails generate controller Greetings hello create app/controllers/greetings_controller.rb route get 'greetings/hello' invoke erb create app/views/greetings create app/views/greetings/hello.html.erb invoke test_unit create test/controllers/greetings_controller_test.rb invoke helper create app/helpers/greetings_helper.rb invoke test_unit

What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file, and a stylesheet file.

Check out the controller and modify it a little (in app/controllers/greetings_controller.rb):

class GreetingsController < ApplicationController def hello @message = "Hello, how are you today?" endend

Then the view, to display our message (in app/views/greetings/hello.html.erb):

<h1>A Greeting for You!</h1><p><%= @message %></p>

Fire up your server using bin/rails server.

$ bin/rails server=> Booting Puma...

The URL will be http://localhost:3000/greetings/hello.

With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.

Rails comes with a generator for data models too.

$ bin/rails generate modelUsage: bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options]...ActiveRecord options: [--migration], [--no-migration] # Indicates when to generate migration # Default: true...Description: Generates a new model. Pass the model name, either CamelCased or under_scored, and an optional list of attribute pairs as arguments....

For a list of available field types for the type parameter, refer to the API documentation for the add_column method for the SchemaStatements module. The index parameter generates a corresponding index for the column.

But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.

We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.

$ bin/rails generate scaffold HighScore game:string score:integer invoke active_record create db/migrate/20190416145729_create_high_scores.rb create app/models/high_score.rb invoke test_unit create test/models/high_score_test.rb create test/fixtures/high_scores.yml invoke resource_route route resources :high_scores invoke scaffold_controller create app/controllers/high_scores_controller.rb invoke erb create app/views/high_scores create app/views/high_scores/index.html.erb create app/views/high_scores/edit.html.erb create app/views/high_scores/show.html.erb create app/views/high_scores/new.html.erb create app/views/high_scores/_form.html.erb invoke test_unit create test/controllers/high_scores_controller_test.rb create test/system/high_scores_test.rb invoke helper create app/helpers/high_scores_helper.rb invoke test_unit invoke jbuilder create app/views/high_scores/index.json.jbuilder create app/views/high_scores/show.json.jbuilder create app/views/high_scores/_high_score.json.jbuilder

The generator creates the model, views, controller, resource route, and database migration (which creates the high_scores table) for HighScore. And it adds tests for those.

The migration requires that we migrate, that is, run some Ruby code (the 20190416145729_create_high_scores.rb file from the above output) to modify the schema of our database. Which database? The SQLite3 database that Rails will create for you when we run the bin/rails db:migrate command. We'll talk more about that command below.

$ bin/rails db:migrate== CreateHighScores: migrating ===============================================-- create_table(:high_scores) -> 0.0017s== CreateHighScores: migrated (0.0019s) ======================================

Let's talk about unit tests. Unit tests are code that tests and makes assertionsabout code. In unit testing, we take a little part of code, say a method of a model,and test its inputs and outputs. Unit tests are your friend. The sooner you makepeace with the fact that your quality of life will drastically increase when you unittest your code, the better. Seriously. Please visitthe testing guide for an in-depthlook at unit testing.

Let's see the interface Rails created for us.

$ bin/rails server

Go to your browser and open http://localhost:3000/high_scores, now we can create new high scores (55,160 on Space Invaders!)

2.3 bin/rails console

The console command lets you interact with your Rails application from the command line. On the underside, bin/rails console uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.

You can also use the alias "c" to invoke the console: bin/rails c.

You can specify the environment in which the console command should operate.

$ bin/rails console -e staging

If you wish to test out some code without changing any data, you can do that by invoking bin/rails console --sandbox.

$ bin/rails console --sandboxLoading development environment in sandbox (Rails 7.1.0)Any modifications you make will be rolled back on exitirb(main):001:0>

2.3.1 The app and helper Objects

Inside the bin/rails console you have access to the app and helper instances.

With the app method you can access named route helpers, as well as do requests.

irb> app.root_path=> "/"irb> app.get _Started GET "/" for 127.0.0.1 at 2014-06-19 10:41:57 -0300...

With the helper method it is possible to access Rails and your application's helpers.

irb> helper.time_ago_in_words 30.days.ago=> "about 1 month"irb> helper.my_custom_helper=> "my custom helper"

2.4 bin/rails dbconsole

bin/rails dbconsole figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL (including MariaDB), PostgreSQL, and SQLite3.

You can also use the alias "db" to invoke the dbconsole: bin/rails db.

If you are using multiple databases, bin/rails dbconsole will connect to the primary database by default. You can specify which database to connect to using --database or --db:

$ bin/rails dbconsole --database=animals

2.5 bin/rails runner

runner runs Ruby code in the context of Rails non-interactively. For instance:

$ bin/rails runner "Model.long_running_method"

You can also use the alias "r" to invoke the runner: bin/rails r.

You can specify the environment in which the runner command should operate using the -e switch.

$ bin/rails runner -e staging "Model.long_running_method"

You can even execute ruby code written in a file with runner.

$ bin/rails runner lib/code_to_be_run.rb

2.6 bin/rails destroy

Think of destroy as the opposite of generate. It'll figure out what generate did, and undo it.

You can also use the alias "d" to invoke the destroy command: bin/rails d.

$ bin/rails generate model Oops invoke active_record create db/migrate/20120528062523_create_oops.rb create app/models/oops.rb invoke test_unit create test/models/oops_test.rb create test/fixtures/oops.yml
$ bin/rails destroy model Oops invoke active_record remove db/migrate/20120528062523_create_oops.rb remove app/models/oops.rb invoke test_unit remove test/models/oops_test.rb remove test/fixtures/oops.yml

2.7 bin/rails about

bin/rails about gives information about version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version. It is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.

$ bin/rails aboutAbout your application's environmentRails version 7.0.0Ruby version 2.7.0 (x86_64-linux)RubyGems version 2.7.3Rack version 2.0.4JavaScript Runtime Node.js (V8)Middleware: Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETagApplication root /home/foobar/my_appEnvironment developmentDatabase adapter sqlite3Database schema version 20180205173523

2.8 bin/rails assets:

You can precompile the assets in app/assets using bin/rails assets:precompile, and remove older compiled assets using bin/rails assets:clean. The assets:clean command allows for rolling deploys that may still be linking to an old asset while the new assets are being built.

If you want to clear public/assets completely, you can use bin/rails assets:clobber.

2.9 bin/rails db:

The most common commands of the db: rails namespace are migrate and create, and it will pay off to try out all of the migration rails commands (up, down, redo, reset). bin/rails db:version is useful when troubleshooting, telling you the current version of the database.

More information about migrations can be found in the Migrations guide.

2.10 bin/rails notes

bin/rails notes searches through your code for comments beginning with a specific keyword. You can refer to bin/rails notes --help for information about usage.

By default, it will search in app, config, db, lib, and test directories for FIXME, OPTIMIZE, and TODO annotations in files with extension .builder, .rb, .rake, .yml, .yaml, .ruby, .css, .js, and .erb.

$ bin/rails notesapp/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deploylib/school.rb: * [ 13] [OPTIMIZE] refactor this code to make it faster * [ 17] [FIXME]

2.10.1 Annotations

You can pass specific annotations by using the --annotations argument. By default, it will search for FIXME, OPTIMIZE, and TODO.Note that annotations are case sensitive.

$ bin/rails notes --annotations FIXME RELEASEapp/controllers/admin/users_controller.rb: * [101] [RELEASE] We need to look at this before next release * [132] [FIXME] high priority for next deploylib/school.rb: * [ 17] [FIXME]

2.10.2 Tags

You can add more default tags to search for by using config.annotations.register_tags. It receives a list of tags.

config.annotations.register_tags("DEPRECATEME", "TESTME")
$ bin/rails notesapp/controllers/admin/users_controller.rb: * [ 20] [TODO] do A/B testing on this * [ 42] [TESTME] this needs more functional tests * [132] [DEPRECATEME] ensure this method is deprecated in next release

2.10.3 Directories

You can add more default directories to search from by using config.annotations.register_directories. It receives a list of directory names.

config.annotations.register_directories("spec", "vendor")
$ bin/rails notesapp/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deploylib/school.rb: * [ 13] [OPTIMIZE] Refactor this code to make it faster * [ 17] [FIXME]spec/models/user_spec.rb: * [122] [TODO] Verify the user that has a subscription worksvendor/tools.rb: * [ 56] [TODO] Get rid of this dependency

2.10.4 Extensions

You can add more default file extensions to search from by using config.annotations.register_extensions. It receives a list of extensions with its corresponding regex to match it up.

config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
$ bin/rails notesapp/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deployapp/assets/stylesheets/application.css.sass: * [ 34] [TODO] Use pseudo element for this classapp/assets/stylesheets/application.css.scss: * [ 1] [TODO] Split into multiple componentslib/school.rb: * [ 13] [OPTIMIZE] Refactor this code to make it faster * [ 17] [FIXME]spec/models/user_spec.rb: * [122] [TODO] Verify the user that has a subscription worksvendor/tools.rb: * [ 56] [TODO] Get rid of this dependency

2.11 bin/rails routes

bin/rails routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.

2.12 bin/rails test

A good description of unit testing in Rails is given in A Guide to Testing Rails Applications

Rails comes with a test framework called minitest. Rails owes its stability to the use of tests. The commands available in the test: namespace helps in running the different tests you will hopefully write.

2.13 bin/rails tmp:

The Rails.root/tmp directory is, like the *nix /tmp directory, the holding place for temporary files like process id files and cached actions.

The tmp: namespaced commands will help you clear and create the Rails.root/tmp directory:

  • bin/rails tmp:cache:clear clears tmp/cache.
  • bin/rails tmp:sockets:clear clears tmp/sockets.
  • bin/rails tmp:screenshots:clear clears tmp/screenshots.
  • bin/rails tmp:clear clears all cache, sockets, and screenshot files.
  • bin/rails tmp:create creates tmp directories for cache, sockets, and pids.

2.14 Miscellaneous

  • bin/rails initializers prints out all defined initializers in the order they are invoked by Rails.
  • bin/rails middleware lists Rack middleware stack enabled for your app.
  • bin/rails stats is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
  • bin/rails secret will give you a pseudo-random key to use for your session secret.
  • bin/rails time:zones:all lists all the timezones Rails knows about.

2.15 Custom Rake Tasks

Custom rake tasks have a .rake extension and are placed inRails.root/lib/tasks. You can create these custom rake tasks with thebin/rails generate task command.

desc "I am short, but comprehensive description for my cool task"task task_name: [:prerequisite_task, :another_task_we_depend_on] do # All your magic here # Any valid Ruby code is allowedend

To pass arguments to your custom rake task:

task :task_name, [:arg_1] => [:prerequisite_1, :prerequisite_2] do |task, args| argument_1 = args.arg_1end

You can group tasks by placing them in namespaces:

namespace :db do desc "This task does nothing" task :nothing do # Seriously, nothing endend

Invocation of the tasks will look like:

$ bin/rails task_name$ bin/rails "task_name[value 1]" # entire argument string should be quoted$ bin/rails "task_name[value 1,value2,value3]" # separate multiple args with a comma$ bin/rails db:nothing

If you need to interact with your application models, perform database queries, and so on, your task should depend on the environment task, which will load your application code.

task task_that_requires_app_code: [:environment] do User.create!end

Feedback

You're encouraged to help improve the quality of this guide.

Please contribute if you see any typos or factual errors. To get started, you can read our documentation contributions section.

You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check Edge Guides first to verify if the issues are already fixed or not on the main branch. Check the Ruby on Rails Guides Guidelines for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please open an issue.

And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the official Ruby on Rails Forum.

The Rails Command Line — Ruby on Rails Guides (2024)

FAQs

How do I run a Ruby method from the command line? ›

Run a script
  1. Press Ctrl twice to invoke the Run Anything popup.
  2. Type the ruby script. rb command and press Enter . ...
  3. (Optional) To run scratch files or scripts outside the project root, hold down the Alt key before running the command (in this case, the dialog title is changed to Run in Context).
Oct 28, 2021

How to start Rails server in command line? ›

To run the Rails server for the first time without any configuring, do the following:
  1. Press Ctrl twice.
  2. Type the rails server command in the invoked popup and press Enter .
  3. Wait until RubyMine starts the Rails server. The Run tool window shows the application's output.
Sep 6, 2022

What are Rails commands? ›

Each command has a description, and should help you find the thing you need. $ rails --help Usage: rails COMMAND [ARGS] The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") ...

How do I run a rake task in Rails terminal? ›

Run Rake tasks
  1. To run a default task, run the rake utility without any parameters: rake .
  2. To run a task with environment variables, specify the values of the variables in the form [variable=value] before the task name: rake RAILS_ENV=production SECRET_KEY_BASE=my-secret-key about .

How to run command from cli? ›

Executing CLI Commands
  1. On a map, select Execute CLI Commands from the right-click menu, or select Actions > Execute CLI Commands from the map toolbar.
  2. Select the target devices. By default, this action applies to the existing devices on the map. ...
  3. Enter the CLI command. ...
  4. Click Run.

How do I run a Ruby file in Rails console? ›

RubyMine allows you to run source code from the editor in the Rails console. To do this, perform the following steps: Open the required Ruby file in the editor (if necessary, select a fragment of code to be executed). From the main menu, choose Tools | Load file/selection into IRB/Rails console.

How to connect to a server using command line? ›

How to Connect via SSH
  1. Open the SSH terminal on your machine and run the following command: ssh your_username@host_ip_address. ...
  2. Type in your password and hit Enter. ...
  3. When you are connecting to a server for the very first time, it will ask you if you want to continue connecting.
Sep 24, 2018

What is the command to install Rails? ›

  1. Step 1: Type the following command in the ruby terminal: $ gem install rails. ...
  2. Step 2: To verify that rails have been installed, type the following command and it should report its version. ...
  3. Step 3: To make your first web application in rails type the following command in the command line: $ rails new project.
Oct 6, 2021

How to test Ruby code in terminal? ›

Ruby
  1. Open a script in the editor and press ⌃⇧R / Ctrl+Shift+F10.
  2. Right-click a script in the editor or Project view and select Run 'script' from the context menu.
  3. Press Ctrl twice to invoke the Run Anything popup and execute the ruby script. rb command.
Sep 13, 2020

What is Ruby command? ›

Ruby command is a free and open source programming language; it is flexible and is feature rich. As the name suggests, ruby indeed is a jewel language which comes at a very low entry cost. Its plug and play capability and also easily readable syntax makes it very user-friendly.

How does Rails console work? ›

Rails console is an irb session that is built into the rails environment and is accessed by typing rails c into the terminal. It can be used to test association methods, validations and check error messages when building a rails app.

How do I view routes in Rails console? ›

The rails routes command is a cli command that outputs all available routes in your application. Along with the cli command, you can also access a list of your routes in the browser by navigating to “https://localhost:3000/rails/info/routes."

How do I run a file in Rails? ›

The simplest way is with rails runner because you don't need to modify your script. runner runs Ruby code in the context of Rails non-interactively. If you make the script executable by running chmod +x script. rb , you can add #!/usr/bin/env rails runner to the top of the script, and then simply run it with ./script.

How to reload command Rails? ›

Reload: This command will allow you to make changes to your code, and continue to use the same console session without having to restart. Simply type in the “reload!” command after making changes and the console will reload the session.

How do I get to the command line in terminal? ›

Click Start and search for "Command Prompt." Alternatively, you can also access the command prompt by pressing Ctrl + r on your keyboard, type "cmd" and then click OK.

How do CLI commands work? ›

CLIs accept as input commands that are entered by keyboard; the commands invoked at the command prompt are then run by the computer. Today, most vendors offer the graphical user interface (GUI) as the default for operating systems (OSes) such as Windows, Linux and macOS.

How do I find the command line? ›

Click the Windows Start Button. In the search box type cmd. In the search results, Right-Click on cmd and select Run as administrator (Figure 2).

How do I run a Ruby file in terminal VS code? ›

In the Debug view (Ctrl+Shift+D), select the create a launch. json file link.
  1. Open a Ruby file and click the left gutter in the editor to set a break point. ...
  2. Start debugging by selecting the desired task under Run and Debug and clicking the start debugging button (default keyboard shortcut F5).
Mar 23, 2023

How do I run a Ruby project? ›

Select a project root in the Project tool window and press Alt+Insert . In the invoked popup, select Ruby File/Class and press Enter . In the invoked popup, specify a script name (script in our case) and click OK.

How to load Ruby file in console? ›

If you only need to load one file into IRB you can invoke it with irb -r ./your_file. rb if it is in the same directory. This automatically requires the file and allows you to work with it immediately. If you want to add more than just -r between each file, well that's what I do and it works.

How to use SSH command in cmd? ›

You can start an SSH session in your command prompt by executing ssh user@machine and you will be prompted to enter your password. You can create a Windows Terminal profile that does this on startup by adding the commandline setting to a profile in your settings.json file inside the list of profile objects.

How to connect to SSH using cmd? ›

Connect
  1. Open a Command prompt window on your technician PC.
  2. Connect to the device: To connect using a username and password: Windows Command Prompt Copy. ssh user@192. 168. ...
  3. Enter the password for your user if you're connecting with a username and password, or if you configured your key to require a password.
Jun 24, 2021

How to check server connection in cmd? ›

For Windows 10, go to Search in the taskbar and:
  1. Type “cmd” to bring up the Command Prompt.
  2. Open the Command Prompt.
  3. Type “ping” in the black box and hit the space bar.
  4. Type the IP address you'd like to ping (e.g., 192.XXX.X.X).
  5. Review the ping results displayed.

How to install Ruby on Rails in terminal? ›

Follow the steps given below for installing Ruby on Rails.
  1. Step 1: Check Ruby Version. First, check if you already have Ruby installed. ...
  2. Step 2: Install Ruby. ...
  3. Step 3: Install Rails. ...
  4. Step 4: Check Rails Version. ...
  5. Step 1: Install Prerequisite Dependencies. ...
  6. Step 2: Install rbenv. ...
  7. Step 3: Install Ruby. ...
  8. Step 4: Install Rails.

What is the command for Ruby version? ›

How to View your Ruby Version in SSH
  • Login to your server via SSH.
  • Run the following command: ruby -v.
Jan 26, 2022

How to install Ruby Rails? ›

Ruby and Rails Installation
  1. Install Ruby. In the Windows Explorer, double click on the rubyinstaller-1.9. ...
  2. Open a Command Prompt Window: ...
  3. Check Ruby Version. ...
  4. Install DevKit. ...
  5. Check Rails Version. ...
  6. Download SQLite. ...
  7. Install SQLite. ...
  8. Check that SQLite is correctly installed:

How to run tests Ruby on Rails? ›

We can run all of our tests at once by using the bin/rails test command. Or we can run a single test file by passing the bin/rails test command the filename containing the test cases. This will run all test methods from the test case.

How to check Ruby code? ›

You can easily check the syntax of your Ruby code using the `ruby` command with the `-c` option. If your code has a syntax error, the `ruby` interpreter will print an error message indicating the location and type of error.

How do I open a Ruby shell? ›

Interactive Ruby Shell (IRB)
  1. Go to the Terminal (or Command Prompt) and type the following command: $ irb >_
  2. Once the shell is open, you can type commands and get instant results. Try a simple puts command in Ruby using IRB: puts "Hello World" The output should be as follows:

How to install Ruby on command? ›

Downloading and Installing Ruby
  1. All the versions of Ruby for Windows can be downloaded from rubyinstaller.org. Download the latest version and follow the further instructions for its Installation.
  2. Using command-line, run the irb command. After this we can write the ruby code and it will run on command line.
Oct 6, 2021

How to install Ruby in command prompt? ›

Windows
  1. Download Ruby Installer. If your machine does not have Ruby, install it. ...
  2. Install Ruby. Once the installer is downloaded: ...
  3. Download Ruby DevKit. Download DevKit from the RubyInstaller page.
  4. Install Ruby DevKit. After the download is finished: ...
  5. Open cmd.exe.
  6. Initialize Ruby DevKit.
Nov 18, 2022

Where is Ruby command? ›

Open a command line window and navigate to your Ruby scripts directory using the cd command. Once there, you can list files, using the dir command on Windows or the ls command on Linux or OS X. Your Ruby files will all have the . rb file extension.

What is the Rails controller? ›

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.

How to create a database from Rails console? ›

To create a new MySQL database for a Rails application:
  1. Start the MySQL command line client, as shown below. Enter the password for the MySQL root user. ...
  2. At the MySQL prompt, run the following commands. ...
  3. Edit the config/database.yml file in your Rails project directory and update the database configuration.

What is Rails web console? ›

Web Console is a debugging tool for your Ruby on Rails applications. Installation. Configuration. Usage.

What is a controller command? ›

The controller command must parse the input properties and set each individual property explicitly within this method. This explicit setting of properties by the controller command itself promotes the concept of type safe properties.

How to create model in Rails command? ›

Writing a Rails Model
  1. rails generate model ModelName ColumnOneName:ColumnOneType ColumnTwoName:ColumnTwoType. ...
  2. rails generate model User username:string password:string. ...
  3. create db/migrate/20130518173035_create_users.rb create app/models/user.rb create test/unit/user_test.rb create test/fixtures/users.yml. ...
  4. rake db:migrate.

What is the command to create a Rails API? ›

To do this, we will run the following command to create a new Rails API application.
  1. rails new my_api --api.
  2. gem "rack-cors"
  3. bundle install.
  4. Rails. application. config. ...
  5. Rails. application. ...
  6. class ApplicationController < ActionController::API def creditscore render json: { creditscore: rand(500.. 900) } end end.
  7. rails server.
Apr 3, 2023

How to create controller in Ruby on Rails? ›

To generate a controller and optionally its actions, do the following: Press Ctrl twice and start typing rails g controller. Select rails g controller and press Enter . In the invoked Add New Controller dialog, specify the controller name.

How to get the URL in Rails? ›

How to Get the Current Absolute URL in Rails
  1. # Returns the original request URL as a `String` # get "/articles? page=2" request. ...
  2. def original_url base_url + original_fullpath end. ...
  3. # get "/articles" request.
Sep 7, 2022

How to show data in Rails? ›

Rails View Record from Database
  1. Step 1 Create a new Rails application.
  2. Step 2 Change your directory to save.
  3. Step 3 Create a controller from the console.
  4. Step 4 Create a model from the console.
  5. Step 5 Go to app/controllers/products_controller. ...
  6. Step 6 Run the following command:
  7. Step 7 Go to app/views/products/index.

How do I run a file in terminal? ›

How to run a file in command prompt
  1. Open command prompt. There are several ways to open the command prompt app. ...
  2. Open the file pathway. To open the correct file, direct the command prompt app to the correct file path in your Windows by using this command template: cd [file path]. ...
  3. Execute the file. ...
  4. Launch and use your file.
Jun 24, 2022

How to pass command-line arguments in Ruby? ›

How to Provide Command-Line Arguments. Ruby script arguments are passed to the Ruby program by the shell, the program that accepts commands (such as bash) on the terminal. On the command-line, any text following the name of the script is considered a command-line argument.

How can we write a Ruby script? ›

Task 1: My first Ruby script
  1. Exit irb by running the exit command.
  2. Create a file in your text editor (we recommended Visual Studio Code in lesson 1) called hello.rb.
  3. Confirm you can see the file in the command line by running ls.
  4. From the command line, use Ruby to run your file by typing ruby hello.rb and pressing enter.

What is the command to exit rails console? ›

To exit the console, type: quit .

How do I restart a rails server? ›

You can restart the application by creating or modifying the file tmp/restart. txt in the Rails application's root folder. Passenger will automatically restart the application during the next request. Depending on the version of Passenger installed on the server, restart.

How to reset db in rails command? ›

You can use db:reset - for run db:drop and db:setup or db:migrate:reset - which runs db:drop, db:create and db:migrate. Save this answer. Show activity on this post. Save this answer.

How do you run a method in Ruby? ›

12 ways to call a method in Ruby
  1. class User def initialize(name) @name = name end def hello puts "Hello, #{@name}!" end def method_missing(_) hello end end user = User. ...
  2. user. method(:hello). ...
  3. method = user. ...
  4. class User def method_missing(_) hello end end user. ...
  5. require 'method_source' # external gem method_source = user.
Aug 13, 2020

How do I run a Ruby class in terminal? ›

Ruby
  1. Open a script in the editor and press ⌃⇧R / Ctrl+Shift+F10.
  2. Right-click a script in the editor or Project view and select Run 'script' from the context menu.
  3. Press Ctrl twice to invoke the Run Anything popup and execute the ruby script. rb command.
Sep 13, 2020

How to call a method in Ruby module? ›

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.

How do you run a method? ›

To call a method, you just need to type the method name followed by open and closed parentheses on the line you want to execute the method. Make sure you only call a method within a class that has access to it.

What is method key in Ruby? ›

In Ruby, the key() method of a hash returns the key for the first-found entry with the given value. The given value is passed as an argument to this method.

How do I run an IRB command? ›

Usage Syntax. To invoke it, type irb at a shell or command prompt, and begin entering Ruby statements and expressions. Use exit or quit to exit irb.

What is terminal in Ruby? ›

The terminal is a basic tool in any operating system, also called a console or a command line. Every time you hear one of these terms, you'll know it's about that. It allows for the communication with the system shell, for example, with bass (the default shell for Ubuntu).

How do I run something in terminal VS Code? ›

You can open a terminal as follows:
  1. From the menu, use the Terminal > New Terminal or View > Terminal menu commands.
  2. From the Command Palette (Ctrl+Shift+P), use the View: Toggle Terminal command.
  3. In the Explorer, you can use the Open in Integrated Terminal context menu command to open a new terminal from a folder.

How to access command-line arguments in Ruby? ›

In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV special variable. ARGV is an Array variable which holds, as strings, each argument passed by the shell.

How to call an array in Ruby? ›

The at() method of an array in Ruby is used to access elements of an array. It accepts an integer value and returns the element. This element is the one in which the index position is the value passed in.

How to dynamically call a method in Ruby? ›

Fortunately, Ruby's metaprogramming feature allows us to call methods dynamically by just passing the method name into public_send(method_name) or send(method_name) . We can call the make_noise method by calling Duck. new. public_send("make_noise") , this is equivalent to calling Duck.

How do you access a method inside a module in Ruby? ›

The module methods & instance methods can be accessed by both extend & include keyword. Regardless of which keyword you use extend or include : the only way to access the module methods is by Module_name::method_name.

References

Top Articles
Latest Posts
Article information

Author: Allyn Kozey

Last Updated:

Views: 6471

Rating: 4.2 / 5 (63 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Allyn Kozey

Birthday: 1993-12-21

Address: Suite 454 40343 Larson Union, Port Melia, TX 16164

Phone: +2456904400762

Job: Investor Administrator

Hobby: Sketching, Puzzles, Pet, Mountaineering, Skydiving, Dowsing, Sports

Introduction: My name is Allyn Kozey, I am a outstanding, colorful, adventurous, encouraging, zealous, tender, helpful person who loves writing and wants to share my knowledge and understanding with you.