Rails 명령줄
이 가이드를 읽고 나면 다음을 알게 될 것입니다:
- Rails 애플리케이션을 생성하는 방법
- 모델, 컨트롤러, 데이터베이스 마이그레이션, 단위 테스트를 생성하는 방법
- 개발 서버를 시작하는 방법
- 대화형 셸을 통해 객체를 실험하는 방법
주의: 이 튜토리얼은 Rails 시작하기 가이드를 읽고 기본적인 Rails 지식이 있다고 가정합니다.
Rails 앱 생성하기
먼저 rails new
명령어를 사용하여 간단한 Rails 애플리케이션을 생성해 보겠습니다.
이 애플리케이션을 사용하여 이 가이드에 설명된 모든 명령을 실험하고 발견할 것입니다.
정보: gem install rails
명령어를 사용하여 rails gem을 설치할 수 있습니다.
rails new
rails new
명령어의 첫 번째 인수는 애플리케이션 이름입니다.
$ 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는 이렇게 작은 명령어로 엄청난 양의 것들을 설정합니다! 이제 우리는 기본적인 Rails 디렉토리 구조와 우리의 간단한 애플리케이션을 실행하는 데 필요한 모든 코드를 가지고 있습니다.
일부 파일 생성을 건너뛰거나 일부 라이브러리를 건너뛰고 싶다면 rails new
명령어에 다음과 같은 인수를 추가할 수 있습니다:
인수 | 설명 |
---|---|
--skip-git |
git init, .gitignore, .gitattributes 건너뛰기 |
--skip-docker |
Dockerfile, .dockerignore, bin/docker-entrypoint 건너뛰기 |
--skip-keeps |
소스 제어 .keep 파일 건너뛰기 |
--skip-action-mailer |
Action Mailer 파일 건너뛰기 |
--skip-action-mailbox |
Action Mailbox gem 건너뛰기 |
--skip-action-text |
Action Text gem 건너뛰기 |
--skip-active-record |
Active Record 파일 건너뛰기 |
--skip-active-job |
Active Job 건너뛰기 |
--skip-active-storage |
Active Storage 파일 건너뛰기 |
--skip-action-cable |
Action Cable 파일 건너뛰기 |
--skip-asset-pipeline |
Asset Pipeline 건너뛰기 |
--skip-javascript |
JavaScript 파일 건너뛰기 |
--skip-hotwire |
Hotwire 통합 건너뛰기 |
--skip-jbuilder |
jbuilder gem 건너뛰기 |
--skip-test |
테스트 파일 건너뛰기 |
--skip-system-test |
시스템 테스트 파일 건너뛰기 |
--skip-bootsnap |
bootsnap gem 건너뛰기 |
--skip-dev-gems |
개발 gem 추가 건너뛰기 |
--skip-rubocop |
RuboCop 설정 건너뛰기 |
이것들은 rails new
가 허용하는 옵션 중 일부입니다. 전체 옵션 목록을 보려면 rails new --help
를 입력하세요.
다른 데이터베이스 사전 구성하기
새 Rails 애플리케이션을 만들 때 애플리케이션이 사용할 데이터베이스 종류를 지정할 수 있습니다. 이렇게 하면 몇 분을 절약할 수 있고 확실히 많은 키 입력을 줄일 수 있습니다.
--database=postgresql
옵션이 어떤 일을 하는지 살펴봅시다:
$ rails new petstore --database=postgresql create create app/controllers create app/helpers ...
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 ...
PostgreSQL을 선택했기 때문에 데이터베이스 구성이 그에 맞게 생성되었습니다.
명령줄 기본
매일 사용하게 될 몇 가지 중요한 명령어가 있습니다. 사용 빈도 순으로 나열하면 다음과 같습니다:
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
사용 가능한 rails 명령어 목록을 보려면 rails --help
를 입력하세요. 각 명령어에는 설명이 있어 필요한 것을 찾는 데 도움이 될 것입니다.
$ rails --help Usage: bin/rails COMMAND [options] 명령어를 지정해야 합니다. 가장 일반적인 명령어는 다음과 같습니다: generate 새 코드 생성 (별칭: "g") console Rails 콘솔 시작 (별칭: "c") server Rails 서버 시작 (별칭: "s") ... 모든 명령어에 -h (또는 --help)를 사용하면 더 자세한 정보를 볼 수 있습니다. 이 명령어 외에도 다음과 같은 것들이 있습니다: about 모든 Rails 버전 정보 표시 assets:clean[keep] 오래된 컴파일된 자산 제거 assets:clobber 컴파일된 자산 제거 assets:environment 자산 컴파일 환경 로드 assets:precompile 모든 자산 컴파일 ... ... db:fixtures:load 데이터베이스에 고정 데이터 로드 db:migrate 데이터베이스 마이그레이션 실행 db:migrate:status 마이그레이션 상태 표시 db:rollback 스키마를 이전 버전으로 롤백 db:schema:cache:clear db/schema_cache.yml 파일 지우기 db:schema:cache:dump db/schema_cache.yml 파일 생성 db:schema:dump 데이터베이스 스키마 파일 생성 (db/schema.rb 또는 db/structure.sql ... db:schema:load 데이터베이스 스키마 파일 로드 (db/schema.rb 또는 db/structure.sql ... db:seed 데이터베이스 시드 데이터 로드 db:version 현재 스키마 버전 가져오기 ... restart 파일 변경으로 앱 재시작 tmp:create tmp 디렉토리 생성
bin/rails server
bin/rails server
명령어는 Rails와 함께 제공되는 Puma 웹 서버를 실행합니다. 웹 브라우저를 통해 애플리케이션에 액세스할 때마다 이 명령어를 사용할 것입니다.
추가 작업 없이도 bin/rails server
를 실행하면 새로운 Rails 앱이 실행됩니다:
$ cd my_app $ bin/rails server => Booting Puma => Rails 7.2.0 application starting in development => Run `bin/rails server --help` for more startup options Puma starting in single mode... * Puma version: 6.4.0 (ruby 3.1.3-p185) ("The Eagle of Durango") * Min threads: 5 * Max threads: 5 * Environment: development * PID: 5295 * Listening on http://127.0.0.1:3000 * Listening on http://[::1]:3000 Use Ctrl-C to stop
단 세 개의 명령어로 포트 3000에서 듣는 Rails 서버를 실행했습니다. 브라우저에서 http://localhost:3000을 열면 기본 Rails 앱이 실행되는 것을 볼 수 있습니다.
정보: bin/rails s
별칭을 사용하여 서버를 시작할 수도 있습니다.
서버는 -p
옵션을 사용하여 다른 포트에서 실행할 수 있습니다. 기본 개발 환경은 -e
옵션을 사용하여 변경할 수 있습니다.
$ bin/rails server -e production -p 4000
-b
옵션을 사용하면 Rails를 지정된 IP에 바인딩할 수 있습니다. 기본적으로 localhost입니다. -d
옵션을 전달하면 데몬으로 서버를 실행할 수 있습니다.
bin/rails generate
bin/rails generate
명령어는 템플릿을 사용하여 많은 것들을 생성합니다. bin/rails generate
를 단독으로 실행하면 사용 가능한 생성기 목록이 표시됩니다:
정보: bin/rails g
별칭을 사용하여 생성기 명령을 실행할 수도 있습니다.
$ bin/rails generate Usage: bin/rails generate GENERATOR [args] [options] ... ... 아래 생성기 중 하나를 선택하세요. Rails: assets channel controller generator ... ...
주의: 생성기 gem을 통해 더 많은 생성기를 설치할 수 있고, 당신이 분명히 설치할 플러그인의 일부분이 될 수 있으며, 심지어 자신만의 생성기를 만들 수도 있습니다!
생성기를 사용하면 보일러플레이트 코드를 작성하는 데 많은 시간을 절약할 수 있습니다. 보일러플레이트 코드는 앱이 작동하는 데 필요한 코드입니다.
우리만의 컨트롤러를 만들어 보겠습니다. 어떤 명령어를 사용해야 할까요? 생성기에 물어봅시다:
정보: 모든 Rails 콘솔 유틸리티에는 도움말 텍스트가 있습니다. 대부분의 *nix 유틸리티와 마찬가지로 --help
또는 -h
를 끝에 추가하면 됩니다. 예: bin/rails server --help
.
$ bin/rails generate controller Usage: bin/rails generate controller NAME [action action] [options] ... ... 설명: ... 모듈 내에 컨트롤러를 생성하려면 'parent_module/controller_name'과 같이 컨트롤러 이름을 경로로 지정하세요. ... 예시: `bin/rails generate controller CreditCards open debit credit close` 신용카드 컨트롤러로 /credit_cards/debit과 같은 URL이 생성됩니다. 컨트롤러: app/controllers/credit_cards_controller.rb 테스트: test/controllers/credit_cards_controller_test.rb 뷰: app/views/credit_cards/debit.html.erb [...] 헬퍼: app/helpers/credit_cards_helper.rb
컨트롤러 생성기는 generate controller ControllerName action1 action2
형식의 매개변수를 기대합니다. hello 액션이 있는 Greetings
컨트롤러를 만들어 보겠습니다.
$ 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
이렇게 생성된 것은 무엇일까요? 애플리케이션에 필요한 디렉토리를 만들고, 컨트롤러 파일, 뷰 파일, 기능 테스트 파일, 뷰를 위한 헬퍼, JavaScript 파일, 스타일시트 파일을 생성했습니다.
컨트롤러를 살펴보고 약간 수정해 보겠습니다 (app/controllers/greetings_controller.rb
):
class GreetingsController < ApplicationController def hello @message = "Hello, how are you today?" end end
그리고 메시지를 표시하는 뷰 (app/views/greetings/hello.html.erb
):
<h1>A Greeting for You!</h1> <p><%= @message %></p>
bin/rails server
를 사용하여 서버를 시작합니다.
$ bin/rails server => Booting Puma...
URL은 http://localhost:3000/greetings/hello입니다.
정보: 일반적인 일반 Rails 애플리케이션에서 URL은 http://(host)/(controller)/(action) 패턴을 따르며, http://(host)/(controller)와 같은 URL은 해당 컨트롤러의 index 액션을 호출합니다.
Rails에는 데이터 모델을 위한 생성기도 있습니다.
$ bin/rails generate model Usage: bin/rails generate model NAME [field[:type][:index] field[:type][:index]] [options] ... Active Record 옵션: [--migration], [--no-migration] # 마이그레이션 생성 여부 지정 # 기본값: true ... 설명: 새 모델을 생성합니다. 모델 이름을 CamelCased 또는 under_scored로 전달하고 선택적으로 속성 쌍 목록을 인수로 전달할 수 있습니다. ...
주의: type
매개변수에 사용할 수 있는 사용 가능한 필드 유형 목록은 SchemaStatements
모듈의 add_column
메서드에 대한 API 문서를 참조하세요. index
매개변수는 해당 열에 대한 해당 인덱스를 생성합니다.
대신 모델을 직접 생성하는 것(나중에 할 것)보다는 스캐폴드를 설정해 보겠습니다. Rails의 스캐폴드는 모델, 해당 모델의 데이터베이스 마이그레이션, 데이터를 조작하는 컨트롤러, 데이터를 보고 조작하는 뷰, 그리고 위의 각각에 대한 테스트 스위트를 제공합니다.
“HighScore"라는 간단한 리소스를 설정할 것입니다. 이 리소스는 우리가 플레이하는 비디오 게임의 최고 점수를 추적할 것입니다.
$ 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
생성기는 HighScore 모델, 뷰, 컨트롤러, 리소스 경로, 그리고 high_scores
테이블을 생성하는 데이터베이스 마이그레이션(20190416145729createhigh_scores.rb 파일)을 만듭니다. 그리고 이에 대한 테스트도 추가합니다.
마이그레이션을 마이그레이트해야 합니다. 즉, Ruby 코드(위의 출력에서 20190416145729createhigh_scores.rb 파일)를 실행하여 데이터베이스 스키마를 수정해야 합니다. 어떤 데이터베이스일까요? Rails가 bin/rails db:migrate
명령을 실행할 때 생성할 SQLite3 데이터베이스입니다. 이 명령에 대해서는 아래에서 더 자세히 설명하겠습니다.
$ bin/rails db:migrate == CreateHighScores: migrating =============================================== -- create_table(:high_scores) -> 0.0017s == CreateHighScores: migrated (0.0019s) ======================================
정보: 단위 테스트에 대해 이야기해 봅시다. 단위 테스트는 코드를 테스트하고 코드에 대한 어설션을 하는 코드입니다. 단위 테스트에서는 모델의 메서드와 같은 코드의 작은 부분을 가져와 입력과 출력을 테스트합니다. 단위 테스트는 여러분의 친구입니다. 코드를 단위 테스트하면 삶의 질이 크게 향상된다는 사실을 받아들이는 것이 좋습니다. 진지하게. 테스팅 가이드를 방문하여 단위 테스트에 대해 자세히 알아보세요.
Rails가 우리를 위해 만든 인터페이스를 살펴봅시다.
$ bin/rails server
브라우저에서 http://localhost:3000/high_scores를 열면 새 최고 점수를 만들 수 있습니다(Space Invaders에서 55,160점!)
bin/rails console
console
명령어를 사용하면 명령줄에서 Rails 애플리케이션과 상호 작용할 수 있습니다. 내부적으로 bin/rails console
은 IRB를 사용하므로 IRB를 사용해 본 적이 있다면 금방 익숙해질 것입니다. 이는 코드로 빠르게 아이디어를 테스트하고 웹 사이트를 건드리지 않고도 서버 측 데이터를 변경할 수 있어 유용합니다.
정보: bin/rails c
별칭을 사용하여 콘솔을 실행할 수도 있습니다.
원하는 환경에서 console
명령어를 실행할 수 있습니다.
$ bin/rails console -e staging
데이터를 변경하지 않고 코드를 테스트하고 싶다면 bin/rails console --sandbox
를 실행할 수 있습니다.
$ bin/rails console --sandbox Loading development environment in sandbox (Rails 7.2.0) Any modifications you make will be rolled back on exit irb(main):001:0>
app
및 helper
객체
bin/rails console
내에서 app
및 helper
인스턴스에 액세스할 수 있습니다.
app
메서드를 사용하면 명명된 경로 헬퍼에 액세스하고 요청을 수행할 수 있습니다.
irb> app.root_path => "/" irb> app.get _ Started GET "/" for 127.0.0.1 at 2014-06-19 10:41:57 -0300 ...
helper
메서드를 사용하면 Rails 및 애플리케이션의 헬퍼에 액세스할 수 있습니다.
irb> helper.time_ago_in_words 30.days.ago => "about 1 month" irb> helper.my_custom_helper => "my custom helper"
bin/rails dbconsole
bin/rails dbconsole
는 사용 중인 데이터베이스를 파악하고 해당 명령줄 인터페이스를 실행합니다(그리고 필요한 명령줄 매개변수도 찾아냅니다!). MySQL(MariaDB 포함), PostgreSQL, SQLite3를 지원합니다.
정보: bin/rails db
별칭을 사용하여 dbconsole을 실행할 수도 있습니다.
여러 데이터베이스를 사용하는 경우 bin/rails dbconsole
는 기본적으로 기본 데이터베이스에 연결됩니다. --database
또는 --db
를 사용하여 연결할 데이터베이스를 지정할 수 있습니다:
$ bin/rails dbconsole --database=animals
bin/rails runner
runner
는 Rails 콘솔을 열지 않고도 Rails 애플리케이션 컨텍스트에서 Ruby 코드를 실행합니다. 예를 들면 다음과 같습니다:
$ bin/rails runner "Model.long_running_method"
정보: bin/rails r
별칭을 사용하여 runner를 실행할 수도 있습니다.
runner
명령에 -e
스위치를 사용하여 실행 환경을 지정할 수 있습니다.
$ bin/rails runner -e staging "Model.long_running_method"
파일에 작성된 Ruby 코드를 실행할 수도 있습니다.
$ bin/rails runner lib/code_to_be_run.rb
bin/rails destroy
destroy
는 generate
의 반대라고 생각하면 됩니다. generate가 무엇을 했는지 파악하고 그것을 되돌립니다.
정보: bin/rails d
별칭을 사용하여 destroy 명령을 실행할 수도 있습니다.
$ 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
bin/rails about
bin/rails about
는 Ruby, RubyGems, Rails, Rails 하위 구성 요소, 애플리케이션 폴더, 현재 Rails 환경 이름, 데이터베이스 어댑터, 스키마 버전에 대한 버전 번호 정보를 제공합니다. 도움을 요청할 때, 보안 패치가 귀하에게 영향을 미칠지 확인할 때, 기존 Rails 설치에 대한 통계가 필요할 때 유용합니다.
$ bin/rails about About your application's environment Rails version 7.2.0 Ruby version 3.1.0 (x86_64-linux) RubyGems version 3.3.7 Rack version 3.0.8 JavaScript Runtime Node.js (V8) Middleware: ActionDispatch::HostAuthorization, Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActionDispatch::ServerTiming, 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::ActionableExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ContentSecurityPolicy::Middleware, ActionDispatch::PermissionsPolicy::Middleware, Rack::Head, Rack::ConditionalGet, Rack::ETag, Rack::TempfileReaper Application root /home/foobar/my_app Environment development Database adapter sqlite3 Database schema version 20180205173523계속해서 한국어 번역본을 제공합니다: ### `bin/rails assets:` `app/assets`의 자산을 `bin/rails assets:precompile`를 사용하여 사전 컴파일할 수 있으며, `bin/rails assets:clean`을 사용하여 오래된 컴파일된 자산을 제거할 수 있습니다. `assets:clean` 명령어를 사용하면 새 자산이 빌드되는 동안 이전 자산을 여전히 링크할 수 있는 롤링 배포가 가능합니다. `public/assets`를 완전히 지우려면 `bin/rails assets:clobber`를 사용할 수 있습니다. ### `bin/rails db:` `db:` rails 네임스페이스의 가장 일반적인 명령어는 `migrate`와 `create`이며, 모든 마이그레이션 rails 명령어(`up`, `down`, `redo`, `reset`)를 시도해 보는 것이 좋습니다. `bin/rails db:version`은 문제 해결 시 현재 데이터베이스 버전을 알려주어 유용합니다. 마이그레이션에 대한 자세한 내용은 [마이그레이션](active_record_migrations.html) 가이드를 참조하세요. ### `bin/rails notes` `bin/rails notes`는 특정 키워드로 시작하는 주석을 찾습니다. `bin/rails notes --help`를 참조하여 사용 방법에 대해 알아볼 수 있습니다. 기본적으로 `.builder`, `.rb`, `.rake`, `.yml`, `.yaml`, `.ruby`, `.css`, `.js`, `.erb` 확장자가 있는 파일의 `app`, `config`, `db`, `lib`, `test` 디렉토리에서 FIXME, OPTIMIZE, TODO 주석을 검색합니다. ```bash $ bin/rails notes app/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deploy lib/school.rb: * [ 13] [OPTIMIZE] refactor this code to make it faster * [ 17] [FIXME]
주석
--annotations
인수를 사용하여 특정 주석을 전달할 수 있습니다. 기본적으로 FIXME, OPTIMIZE, TODO를 검색합니다.
주석은 대소문자를 구분한다는 점에 유의하세요.
$ bin/rails notes --annotations FIXME RELEASE app/controllers/admin/users_controller.rb: * [101] [RELEASE] We need to look at this before next release * [132] [FIXME] high priority for next deploy lib/school.rb: * [ 17] [FIXME]
태그
config.annotations.register_tags
를 사용하여 기본적으로 검색할 태그를 더 추가할 수 있습니다. 태그 목록을 받습니다.
config.annotations.register_tags("DEPRECATEME", "TESTME")
$ bin/rails notes app/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
디렉토리
config.annotations.register_directories
를 사용하여 기본적으로 검색할 디렉토리를 더 추가할 수 있습니다. 디렉토리 이름 목록을 받습니다.
config.annotations.register_directories("spec", "vendor")
$ bin/rails notes app/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deploy lib/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 works vendor/tools.rb: * [ 56] [TODO] Get rid of this dependency
확장자
config.annotations.register_extensions
를 사용하여 기본적으로 검색할 파일 확장자를 더 추가할 수 있습니다. 확장자와 일치하는 정규식을 받습니다.
config.annotations.register_extensions("scss", "sass") { |annotation| /\/\/\s*(#{annotation}):?\s*(.*)$/ }
$ bin/rails notes app/controllers/admin/users_controller.rb: * [ 20] [TODO] any other way to do this? * [132] [FIXME] high priority for next deploy app/assets/stylesheets/application.css.sass: * [ 34] [TODO] Use pseudo element for this class app/assets/stylesheets/application.css.scss: * [ 1] [TODO] Split into multiple components lib/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 works vendor/tools.rb: * [ 56] [TODO] Get rid of this dependency
bin/rails routes
bin/rails routes
는 정의된 모든 경로를 나열하므로 앱의 경로 문제를 추적하거나 익숙하지 않은 앱의 URL을 개요로 파악할 때 유용합니다.
bin/rails test
정보: Rails 애플리케이션 테스팅에 대한 좋은 설명은 Rails 애플리케이션 테스팅 가이드에 나와 있습니다.
Rails에는 minitest라는 테스트 프레임워크가 포함되어 있습니다. Rails의 안정성은 테스트 사용에 힘입은 바 큽니다. test:
네임스페이스의 명령어는 작성할 다양한 테스트를 실행하는 데 도움이 됩니다.
bin/rails tmp:
Rails.root/tmp
디렉토리는 프로세스 ID 파일 및 캐시된 작업과 같은 임시 파일을 보관하는 *nix의 /tmp 디렉토리와 같은 역할을 합니다.
tmp:
네임스페이스 명령어는 Rails.root/tmp
디렉토리를 정리하고 생성하는 데 도움이 됩니다:
bin/rails tmp:cache:clear
는tmp/cache
를 지웁니다.bin/rails tmp:sockets:clear
는tmp/sockets
를 지웁니다.bin/rails tmp:screenshots:clear
는tmp/screenshots
를 지웁니다.bin/rails tmp:clear
는 모든 캐시, 소켓, 스크린샷 파일을 지웁니다.bin/rails tmp:create
는 캐시, 소켓, pid용 tmp 디렉토리를 생성합니다.
기타
bin/rails initializers
는 Rails에 의해 호출되는 순서대로 정의된 모든 초기화기를 출력합니다.bin/rails middleware
는 앱에 활성화된 Rack 미들웨어 스택을 나열합니다.bin/rails stats
는 코드 통계를 보는 데 좋습니다. KLOC(코드 천 줄) 및 코드 대 테스트 비율과 같은 것을 표시합니다.bin/rails secret
은 세션 비밀 키로 사용할 의사 난수 키를 제공합니다.bin/rails time:zones:all
은 Rails가 알고 있는 모든 시간대를 나열합니다.
사용자 정의 Rake 작업
사용자 정의 rake 작업은 .rake
확장자를 가지며 Rails.root/lib/tasks
에 배치됩니다. bin/rails generate task
명령을 사용하여 이러한 사용자 정의 rake 작업을 만들 수 있습니다.
desc "I am short, but comprehensive description for my cool task" task task_name: [:prerequisite_task, :another_task_we_depend_on] do # 모든 매직이 여기에 # 유효한 Ruby 코드는 어디에나 허용됩니다 end
사용자 정의 rake 작업에 인수를 전달하려면:
task :task_name, [:arg_1] => [:prerequisite_1, :prerequisite_2] do |task, args| argument_1 = args.arg_1 end
작업을 그룹화하여 네임스페이스에 배치할 수 있습니다:
namespace :db do desc "This task does nothing" task :nothing do # 정말 아무것도 하지 않음 end end
작업 호출은 다음과 같습니다:
$ bin/rails task_name $ bin/rails "task_name[value 1]" # 전체 인수 문자열은 따옴표로 묶어야 합니다 $ bin/rails "task_name[value 1,value2,value3]" # 여러 인수는 쉼표로 구분 $ bin/rails db:nothing
애플리케이션 모델과 상호 작용하고, 데이터베이스 쿼리를 수행하는 등의 작업을 수행하려면 environment
작업에 종속되어야 합니다.
task task_that_requires_app_code: [:environment] do User.create! end