diff --git a/app/controllers/authors_controller.rb b/app/controllers/authors_controller.rb new file mode 100644 index 0000000..f96718c --- /dev/null +++ b/app/controllers/authors_controller.rb @@ -0,0 +1,5 @@ +class AuthorsController < ApplicationController + def index + @authors = Author.all + end +end diff --git a/app/controllers/books_controller.rb b/app/controllers/books_controller.rb index bafab99..3ef6625 100644 --- a/app/controllers/books_controller.rb +++ b/app/controllers/books_controller.rb @@ -1,5 +1,43 @@ class BooksController < ApplicationController + before_action :set_book, only: [:show, :edit, :update] + before_action :ensure_admin, only: [:edit, :update] + def index - @books = Book.published.map { |book| BooksPresenter.new(book) } + if current_user.admin? + books = Book.all + else + books = Book.published + end + @books = books.map { |book| BooksPresenter.new(book) } + end + + def show + end + + def edit + end + + def update + if @book.update(book_params) + redirect_to '/books' + end + end + + private + + def ensure_admin + unless current_user&.admin? + redirect_to '/welcome', notice: 'You are not allowed to perform this action' + end + end + + 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 diff --git a/app/models/book.rb b/app/models/book.rb index 860c5d5..e0b5624 100644 --- a/app/models/book.rb +++ b/app/models/book.rb @@ -4,5 +4,4 @@ class Book < ApplicationRecord scope :published, -> { where(published: true) } validates :title, presence: true validates :price, presence: true - validates :published, presence: true end diff --git a/app/models/user.rb b/app/models/user.rb index 174b4bc..9731bb0 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -5,5 +5,9 @@ class User < ApplicationRecord validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } validates :role, presence: true - validates :password, presence: true, length: { minimum: 8 } + validates :password, { + presence: true, + length: { minimum: 8 }, + if: lambda{ new_record? || !password.nil? } + } end diff --git a/app/presenters/books_presenter.rb b/app/presenters/books_presenter.rb index 49888bb..c6b3f40 100644 --- a/app/presenters/books_presenter.rb +++ b/app/presenters/books_presenter.rb @@ -2,7 +2,11 @@ class BooksPresenter < SimpleDelegator include ActiveSupport::NumberHelper def price - number_to_currency(super / 100) + super / 100 + end + + def price_with_currency + number_to_currency(price) end def authors diff --git a/app/views/books/edit.html.erb b/app/views/books/edit.html.erb new file mode 100644 index 0000000..d45ee1c --- /dev/null +++ b/app/views/books/edit.html.erb @@ -0,0 +1,14 @@ +