-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
メモアプリの作成(DB版) #3
base: main
Are you sure you want to change the base?
Conversation
app.rb
Outdated
enable :method_override | ||
|
||
def connect_db | ||
@conn = PG.connect(dbname: 'sinatra_note_app') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
接続をキャッシュしているの素晴しいですね。大体ここが指摘ポイントになるので。
ただ、呼び出し元で nil チェックをしているので、呼び出す度にifが必要になっているのがもったいないですね。
このメソッド内でチェックするようにして、 メソッド名をconn
とか connection
とかにして、@conn
を返すようにすれば呼び出し元はシンプルになりますよ。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
レビューありがとうございます!
なるほど!確かに、同じif文が繰り返されているのをみて「共通化できないかな」と考えてみるべきでした...!
修正してみたのでご確認お願いします😊🙏
enable :method_override | ||
|
||
def connection | ||
@conn = PG.connect(dbname: 'sinatra_note_app') if @conn.nil? |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
惜しい!
あと一歩なので書いちゃうと、これを
def connection
@conn = PG.connect(dbname: 'sinatra_note_app') if @conn.nil?
@conn
end
とすれば
connection
@conn.exec("INSERT INTO notes (title,content) VALUES ('#{params[:title]}','#{params[:content]}')")
↓
connection.exec("INSERT INTO notes (title,content) VALUES ('#{params[:title]}','#{params[:content]}')")
となります。
あとはイディオムとして以下のようによく書きます。 ||=
で nil(もしくはfalse)のときだけ右辺を実行して代入させる事ができるんですよね。
def connection
@conn ||= PG.connect(dbname: 'sinatra_note_app')
end
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
レビューありがとうございます🙇🏻♂️!!
なるほど、確かにその方がより簡潔になりますね...!!
また||=
についてもよく見かける書き方ですが、今回の例でより使いどころを理解することができました!使いこなせるようになりたいと思います!
プルリクエストを作り直しました