Rails Console Json Data

레일스 콘솔에서 데이터 편하게 보는법.

일단 그냥 보면 되지 굳이 명령어하나 더 치면서 데이터를 확인할까 하지만 데이터가 너무 길고 보기 힘들때 이해도 못하는 데이터 보기라도 편하게 바꿔보자 싶어서 찾아보았다.

먼저 일반적으로 보던 모습이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
{"id"=>321312312,
"product_id"=>5858457321321223335,
"title"=>"",
"price"=>"17000",
"sku"=>"H59554J1S16C",
"position"=>16,
"inventory_policy"=>"deny",
"compare_at_price"=>nil,
"fulfillment_service"=>"manual",
"inventory_management"=>"shopify",
"option1"=>"brown",
"option2"=>"-4.25",
"option3"=>nil,
"created_at"=>"2020-09-28T16:44:30+09:00",
"updated_at"=>"2022-03-31T23:36:06+09:00",
"taxable"=>true,
"barcode"=>"8809693505654",
"grams"=>37,
"image_id"=>20065729413287,
"weight"=>37.0,
"weight_unit"=>"g",
"inventory_item_id"=>38760799502503,
"inventory_quantity"=>996,
"old_inventory_quantity"=>996,
"requires_shipping"=>false,
{"id"=>36712615346343,
"product_id"=>5858457223335,
"title"=>"brown / -4.50",
"price"=>"17000",
"sku"=>"H59554J1S17C",
"position"=>17,
"inventory_policy"=>"deny",
"compare_at_price"=>nil,
"fulfillment_service"=>"manual",
"inventory_management"=>"shopify",
"option1"=>"brown",
"option2"=>"-4.50",
"option3"=>nil,
"created_at"=>"2020-09-28T16:44:30+09:00",
"updated_at"=>"2022-03-31T23:36:07+09:00",
"taxable"=>true,
"barcode"=>"8809693505661",
"grams"=>37,
"image_id"=>20065729413287,
"weight"=>37.0,
"weight_unit"=>"g",
"inventory_item_id"=>38760799535271,
"inventory_quantity"=>999,
"old_inventory_quantity"=>999,
"requires_shipping"=>false,
"admin_graphql_api_id"=>"gid://shopify/ProductVariant/36712615346343",
"compare_at_price2"=>""},

Ruby on Rails Grape Gem

루비 온 레일스 Grape Gem 사용하기

Grape 젬은 레일스 환경에서 REST 와 유사한 API 프레임워크이다.

Grape GitHub
Grape Gem GitHub HomePage

Install Gem

1
2
# Gemfile
gem 'grape'

Gemfile 에 grape 젬을 추가해준뒤 bundle install 명령어를 실행한다.

설정하기

적용하기 위한 프로젝트의 레일스 버전이 7버전으로 grape github README 를 따라 6버전 이상의 세팅 방법을 따라 진행 하였다.

path: ./config/initializers/inflections.rb
아래의 코드가 이미 작성되어있고 주석처리가 되어있다. 해당부분 주석을 제거하고 작성해주면 된다.

1
2
3
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym "DefaultController" # 베이스가 되는 클래스의 이름을 입력하는 부분이다.
end

컨트롤러 생성

1
2
3
4
cd app
mkdir api
touch base_api.rb
touch default_controller.rb

path: ./app/api/base_api.rb

1
2
3
4
5
6
7
8
class BaseApi < Grape::API
# 기타 공용 함수들?
helpers do
def server_port
Rails.env['PORT'] || 3000
end
end
end

path: ./app/api/default_controller.rb

1
2
3
4
5
6
7
8
9
class DefaultController < BaseApi
version 'v1', using: :path
format :json
prefix :api

get 'alive' do
"rails server run #{server_port} port"
end
end

path: ./config/routes.rb

1
2
3
4
Rails.application.routes.draw do
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
mount DefaultController => '/'
end

curl을 이용하여 요청하기


User Controller 생성하기

1
2
3
# work dir: ./app
cd user_controller
touch user_api.rb

path: ./app/api/user_controller/user_api.rb

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
module UserController
class UserApi < BaseApi

resource 'users' do
helpers do
def post_params
params.as_json(only: %i[email password name nick_name age gender])
end
end
# GET /api/v1/users/all
get 'all' do
users = User.all
{
total: users.count,
result: users.map { |r| Entities::UserEntity.represent(r) },
}
end

# POST /api/v1/users
post do
user = User.create(post_params)
present user, with: Entities::UserEntity
end
end
end
end

POST /users


GET /users/all


Ruby on Rails Docker Setting (레일스 도커 개발환경 세팅하기)

Ruby on Rails Docker Setting

레일스 개발 환경을 도커로 세팅해보자

크게 복잡하고 거창한 환경 세팅은 아니지만 처음 세팅이 항상 골칫거리이다..

개발 환경
ruby-on-rails -v 7.0^
ruby -v 2.7.1
RubyMine
Docker
docker-compose
postgres -v 14.2-alpine

1. 기본 세팅을 위한 파일 생성 및 작성

1
2
3
4
5
6
mkdir backend
cd backend

touch Dockerfile
touch docker-compose.yml
touch docker-compoes.env

Dockerfile 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# syntax=docker/dockerfile:1
FROM ruby:2.7.1

RUN apt-get update -qq && apt-get install -y nodejs postgresql-client

WORKDIR /usr/src/app
COPY Gemfile ./
COPY Gemfile.lock ./
RUN bundle install

# Add a script to be executed every time the container starts.
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

# Configure the main process to run when running the image
CMD ["rails", "server", "-b", "0.0.0.0"]

docker-compose.yml 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
version: "3"
services:
## backend
database:
image: postgres:14.2-alpine
ports:
- "5432:5432"
env_file: docker-compose.env
volumes:
- ./psql/data:/var/lib/postgresql/data

## api
web:
container_name: web
build: .
command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'"
ports:
- "3000:3000"
env_file: docker-compose.env
volumes:
- ./:/usr/src/app
depends_on:
- "database"
environment:
- RAILS_ENV=development

Gemfile, Gemfile.lock 생성

1
2
touch Gemfile
touch Gemfile.lock
1
2
3
4
# Gemfile
source "https://rubygems.org"

ruby "2.7.1"

docker-compose.env

1
2
3
4
5
POSTGRES_USER=user
POSTGRES_PASSWORD=password

PG_USER=user
PG_PASSWORD=password

2. 빌드 시작

1
docker-compose build

빌드를 시작해도 아직 레일스 세팅이 안되어있다. docker 컨테이너를 이용하여 레일스 설치를 진행한다.

1
docker-compose run --no-deps web rails new . --api --force --database=postgresql

실행 시 뭔가 쭉쭉 설치되고 로컬 디렉토리와 컨테이너 볼륨을 지정해줬기 때문에 작업 디렉토리에 레일스 폴더, 파일들이 생성된다.



3. database.yml 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# ./config/database.yml

default: &default
adapter: postgresql
encoding: utf8
# For details on connection pooling, see Rails configuration guide
# https://guides.rubyonrails.org/configuring.html#database-pooling
pool: 5
host: database # docker 환경 데이터베이스와 연결을 하기위해서는 컨테이너 이름으로 지정해주어야 한다.
username: juren
password: juren

development:
<<: *default
database: juren_development

test:
<<: *default
database: juren_test

4. 데이터베이스 생성하기

아직 도커에서 실행중인 postgresql 에는 데이터베이스가 생성되어있지 않다. yml 파일에서 지정한 데이터베이스들을 생성해주기 위해서는 아래 명령어를 실행한다.

1
2
docker-compsoe up # 컨테이너 실행 명령어
docker-compose run web rake db:create # rails db 생성 명령어

5. localhost 접속

크롬 -> localhost:3000 접속 결과 확인



끝~👍👍

은 아니고 이제 시작...