문서 메뉴

문서 홈몽고이드

시작하기(시나트라)

이 페이지의 내용

  • 새 애플리케이션
  • Git 리포지토리 만들기
  • 젬파일 생성
  • 설치 종속성
  • 로컬에서 MongoDB 실행
  • MongoDB Atlas 사용
  • 기본 애플리케이션
  • 애플리케이션 실행
  • 기존 애플리케이션

이 섹션에서는 데이터 액세스에 Mongoid를 사용하여 새로운 Sinatra 애플리케이션을 만드는 방법을 보여줍니다. 이 프로세스는 Ruby on Rails를 사용하지 않는 다른 Ruby 애플리케이션에서도 유사합니다.

이 애플리케이션의 전체 소스 코드는 mongoid-demo GitHub 리포지토리 에서 확인할 수 있습니다. .

필수는 아니지만, 애플리케이션에 대한 Git 리포지토리를 생성하는 것이 좋습니다.

git init blog
cd blog

이 튜토리얼을 따라하면서 변경 사항을 커밋합니다.

다음 내용으로 Gemfile 이라는 파일을 만듭니다.

source 'https://rubygems.org'
gem 'sinatra'
gem 'mongoid'
gem 'puma'

다음 명령을 실행하여 종속성을 설치합니다.

gem install bundler
bundle install

이 명령은 Gemfile.lock 이라는 파일을 생성하며, 이 파일을 Git 리포지토리에 커밋하는 것이 좋습니다.

MongoDB를 사용하여 로컬에서 개발하려면 MongoDB 를 다운로드하여 설치 합니다.

MongoDB가 설치되어 실행 중이면 배포서버를 가리키는 config/mongoid.yml 파일을 생성합니다. 예를 들어 기본 포트에서 독립형 mongod 를 실행한 경우 다음 내용이 적절합니다.

development:
clients:
default:
database: blog_development
hosts:
- localhost:27017
options:
server_selection_timeout: 1

MongoDB를 다운로드하고 설치하여 로컬에서 실행하는 대신 무료로 MongoDB Atlas 계정을 생성하고 Atlas에서 무료 MongoDB cluster를 만들 수 있습니다. 클러스터가 만들어지면 클러스터에 연결하기 페이지의 안내에 따라 URI를 가져옵니다. Ruby 드라이버 2.5 이상의 형식을 사용하세요.

다음 내용이 포함된 config/mongoid.yml 파일을 만들고 URI를 cluster의 실제 URI로 바꿉니다.

development:
clients:
default:
uri: mongodb+srv://user:pass@yourcluster.mongodb.net/blog_development?retryWrites=true&w=majority
options:
server_selection_timeout: 5

다음 내용으로 app.rb 이라는 파일을 만듭니다. 먼저 일부 항목에는 다음이 필요합니다.

require 'sinatra'
require 'mongoid'

Mongoid 구성 파일을 로드하고 Mongoid를 구성합니다. 이 작업은 Mongoid를 Rails와 함께 사용할 때 자동으로 수행되지만, Mongoid를 Sinatra와 함께 사용하기 때문에 직접 수행해야 합니다.

Mongoid.load!(File.join(File.dirname(__FILE__), 'config', 'mongoid.yml'))

이제 몇 가지 모델을 정의할 수 있습니다:

class Post
include Mongoid::Document
field :title, type: String
field :body, type: String
has_many :comments
end
class Comment
include Mongoid::Document
field :name, type: String
field :message, type: String
belongs_to :post
end

... 그리고 몇 가지 경로를 추가합니다:

get '/posts' do
Post.all.to_json
end
post '/posts' do
post = Post.create!(params[:post])
post.to_json
end
get '/posts/:post_id' do |post_id|
post = Post.find(post_id)
post.attributes.merge(
comments: post.comments,
).to_json
end
post '/posts/:post_id/comments' do |post_id|
post = Post.find(post_id)
comment = post.comments.create!(params[:comment])
{}.to_json
end

애플리케이션을 실행합니다.

bundle exec ruby app.rb

컬을 통해 몇 가지 요청을 시도합니다:

curl http://localhost:4567/posts
# => []
curl -d 'post[title]=hello&post[body]=hello+world' http://localhost:4567/posts
# => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"}
curl http://localhost:4567/posts
# => [{"_id":{"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"body":"hello world","title":"hello"}]
curl -d 'comment[name]=David&comment[message]=I+like' http://localhost:4567/posts/5d8151ec96fb4f0ed5a7a03f/comments
# => {}
curl http://localhost:4567/posts/5d8151ec96fb4f0ed5a7a03f
# => {"_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"},"title":"hello","body":"hello world","comments":[{"_id":{"$oid":"5d8157ac96fb4f20c5e45c4d"},"message":"I like","name":"David","post_id":{"$oid":"5d8151ec96fb4f0ed5a7a03f"}}]}

기존 Sinatra 애플리케이션에서 Mongoid 사용을 시작하는 단계는 기본적으로 새 애플리케이션에 대해 위에 제공된 단계와 동일합니다.

  1. mongoid 종속성을 Gemfile 에 추가합니다.

  2. mongoid.yml 구성 파일을 만듭니다.

  3. 구성 파일을 로드하고 애플리케이션에서 Mongoid를 구성합니다.

  4. Mongoid 모델을 정의합니다.

←  튜토리얼시작하기(레일즈 7) →