47 lines
1.1 KiB
Ruby
47 lines
1.1 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
# Books controller
|
|
class BooksController < ApplicationController
|
|
before_action :set_book, only: %i[show edit update add_to_cart]
|
|
before_action :ensure_admin, only: %i[edit update]
|
|
|
|
def index
|
|
books = if current_user&.admin?
|
|
Book.all
|
|
else
|
|
Book.published
|
|
end
|
|
@books = books.map { |book| BooksPresenter.new(book) }
|
|
end
|
|
|
|
def edit; end
|
|
|
|
def update
|
|
redirect_to '/books' if @book.update(book_params)
|
|
end
|
|
|
|
def add_to_cart
|
|
@book = Book.find(params[:id])
|
|
return unless @book.quantity.positive?
|
|
|
|
current_user.books << @book
|
|
@book.decrement!(:quantity)
|
|
redirect_to '/books', notice: 'Book added to your cart'
|
|
end
|
|
|
|
def shopping_cart
|
|
@books = current_user.books.map { |book| BooksPresenter.new(book) }
|
|
end
|
|
|
|
private
|
|
|
|
def set_book
|
|
@book = BooksPresenter.new(Book.find(params[:id]))
|
|
end
|
|
|
|
def book_params
|
|
result = params.require(:book).permit(:title, :price, :published)
|
|
result['price'] = result['price'].to_d * 100
|
|
result
|
|
end
|
|
end
|