Skip to content

Commit

Permalink
todos os testes passando
Browse files Browse the repository at this point in the history
  • Loading branch information
marciomoretto committed Mar 22, 2012
1 parent a8da00f commit ee829ae
Show file tree
Hide file tree
Showing 25 changed files with 276 additions and 159 deletions.
11 changes: 5 additions & 6 deletions Gemfile
Expand Up @@ -9,15 +9,13 @@ gem 'rails', '3.1.0'
#gem 'sqlite3'

gem 'jquery-rails'
gem 'rails3-jquery-autocomplete', :git => 'git://github.com/marciomr/rails3-jquery-autocomplete.git'
gem 'mysql2'
gem 'thinking-sphinx'
# :git => 'git://github.com/freelancing-god/thinking-sphinx.git',
# the very latest version is compliant with kaminari
gem 'thinking-sphinx' # queria aposentar esse
gem 'kaminari'
gem 'cancan'
gem 'nokogiri'
#gem 'cancan' # vou aposentar esse
gem 'nokogiri' # esse vou aposentar na proxima versao
gem 'friendly_id'
gem 'rack-pjax'

gem 'rspec-rails', :group => [:development, :test]
gem 'factory_girl_rails', :group => [:development, :test]
Expand All @@ -26,6 +24,7 @@ group :assets do
gem 'sass-rails', " ~> 3.1.0"
gem 'coffee-rails', " ~> 3.1.0"
gem 'uglifier'
# using my version of bootstrap because of the autocompletion
gem 'twitter-bootstrap-rails', :git => 'git://github.com/marciomr/twitter-bootstrap-rails.git'
end

Expand Down
37 changes: 31 additions & 6 deletions app/controllers/application_controller.rb
@@ -1,5 +1,5 @@
class ApplicationController < ActionController::Base
helper_method :current_user, :admin
helper_method :current_user, :admin, :admin?, :guest?, :restricted_to
# See ActionController::RequestForgeryProtection for details
# Uncomment the :secret if you're not using the cookie session store
protect_from_forgery # :secret => '5f2f9061bb334aa869d4717f2779655e'
Expand All @@ -11,12 +11,37 @@ def current_user
end

def admin
User.find(1)
@admin ||= User.find(1)
end

rescue_from CanCan::AccessDenied do |exception|
session[:return_to] = request.url
redirect_to login_path, :alert => "Acesso negado!"
end
def admin?
current_user == admin
end

def guest?
current_user.nil?
end

def unautorized!(path = login_path)
session[:return_to] = request.url
redirect_to path, :alert => "Acesso negado!"
end

def access_restricted_to(users)
users = [users] if !users.kind_of?(Array)

if !guest? && users.include?(current_user)
yield if block_given?
else
unautorized!
end
end

def restricted_to(users)
users = [users] if !users.kind_of?(Array)

if !guest? && users.include?(current_user)
yield
end
end
end
94 changes: 65 additions & 29 deletions app/controllers/books_controller.rb
@@ -1,21 +1,22 @@
# coding: utf-8

class BooksController < ApplicationController
load_and_authorize_resource
protect_from_forgery :only => [:create, :update, :destroy]

%w(editor subject city country).each do |field|
%w(editor subject city country).each do |field|
define_method "typeahead_#{field}" do
@books = Book.order(field.to_sym).where("#{field} like ?", "%#{params[:query]}%")
render :json => @books.map(&(field.to_sym)).uniq
end
end

# autocomplete para autores
def typeahead_authors
@authors = Author.order(:name).where("name like ?", "%#{params[:query]}%")
render :json => @authors.map(&:name).uniq
end

# autocomplete para tags
def typeahead_tags
@tags = Tag.order(:title).where("title like ?", "%#{params[:query]}%")
render :json => @tags.map(&:title).uniq
Expand Down Expand Up @@ -76,61 +77,96 @@ def index
@books.with_user_id(@user.id)
end
end

format.xml do
if params[:user_id]
@user = User.find_by_username(params[:user_id])
render :xml => @user.books, :except => [:user_id, :id, :created_at, :updated_at],
:include => {:authors => {:only => [:name]}, :tags => {:only => [:title]}}
else
render :xml => @books, :except => [:user_id, :id, :created_at, :updated_at],
:include => {:authors => {:only => [:name]}, :tags => {:only => [:title]}}
end
end
end
end

def show
@user = User.find_by_username(params[:user_id])
@book = @user.books.find_by_tombo(params[:id])
raise("not found") if @book.nil?

# se o livro não for encontrado 404
raise ActionController::RoutingError.new('Not Found')if @book.nil?
end

def new
@user = User.find_by_username(params[:user_id])
if @user != current_user
redirect_to new_user_book_path(current_user), :alert => "Acesso Negado!" if !current_user.admin?
end
if @user.nil?
redirect_to root_path, :alert => "Erro: você precisa estar no seu site para criar um livro."
else

if params[:isbn]
@attributes = Book.get_attributes(params[:isbn]) || { 'isbn' => params[:isbn] }
@book = Book.new @attributes
else
@book = Book.new
end

@book.authors.build
end
# tem que estar no site de alguma biblio para criar livro
if @user.nil? || @user.admin?
redirect_to root_path, :alert => "Você precisa estar no site de um biblioteca para criar um livro."

# guest não pode criar livros
elsif guest?
unautorized!

# só o admin pode criar na conta de outro usuário
elsif @user != current_user && !admin?
unautorized!(new_user_book_path(current_user))

elsif params[:isbn]
# tenta preencher os campos automaticamente
@attributes = Book.get_attributes(params[:isbn]) || { 'isbn' => params[:isbn] }
@book = Book.new @attributes
else
@book = Book.new
# um campo de autor aparece sem precisar clicar em "adicionar autor"
@book.authors.build
end
end

def create
@book = Book.new(params[:book])
@user = User.find_by_username(params[:user_id])
@book.user_id = @user.try(:id)

if @book.save
redirect_to user_book_path(@user, @book), :notice => "Livro criado com sucesso."
else
render :action => 'new'
access_restricted_to([@user, admin]) do
@book.user_id = @user.try(:id)

if @book.save
redirect_to [@user, @book], :notice => "Livro criado com sucesso."
else
render :new
end
end
end

def edit
@user = User.find_by_username(params[:user_id])
@book = @user.books.find_by_tombo(params[:id])

access_restricted_to([@user, admin])
end

def update
if @book.update_attributes(params[:book])
redirect_to [@book.user, @book], :notice => "Livro editado com sucesso."
else
render :action => 'edit'
@book = Book.find(params[:id])
@user = User.find_by_username(params[:user_id])

access_restricted_to([@user, admin]) do
if @book.update_attributes(params[:book])
redirect_to [@book.user, @book], :notice => "Livro editado com sucesso."
else
render :action => 'edit'
end
end
end

def destroy
@book.destroy
redirect_to root_path, :notice => "Livro deletado com sucesso." # queria voltar pra onde eu estava...
@user = User.find_by_username(params[:user_id])
@book = @user.books.find_by_tombo(params[:id])

access_restricted_to([@user, admin]) do
@book.destroy
redirect_to user_books_path(@user), :notice => "Livro deletado com sucesso."
end
end
end
7 changes: 3 additions & 4 deletions app/controllers/sessions_controller.rb
Expand Up @@ -8,17 +8,16 @@ def create
user = User.find_by_username(params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to (session[:return_to] || root_url), :notice => "Logado!"
redirect_to session[:return_to] || :back, :notice => 'Logado!'
session[:return_to] = nil
else
flash.now.alert = "Senha ou usuário invalido!"
render "new"
redirect_to :back, :alert => 'Senha ou usuário inválido!'
end
end

def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Deslogado!"
redirect_to :back, :notice => "Deslogado!"
end

end
8 changes: 5 additions & 3 deletions app/models/book.rb
Expand Up @@ -8,13 +8,15 @@ class Book < ActiveRecord::Base

belongs_to :user
validates_presence_of :user_id
validates_uniqueness_of :tombo, :scope => :user_id
validates_presence_of :title, :message => "O livro precisa ter um título."
# validates_format_of :pdflink, :imglink
# validates_integer year, page_number, volume
validates_format_of :pdflink, :imglink, :allow_blank => true, :with => /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix, :message => "Link inválido."
# talvez eu devesse verificar se o link é válido - http://joshuawood.net/validating-url-in-ruby-on-rails-3/
validates_numericality_of :year, :page_number, :volume, :only_integer => true, :allow_blank => true, :message => "Preencha com um número."

before_save do |book|
t = book.user.last_tombo + 1
book.tombo = t.to_s if book.tombo.nil?
book.tombo ||= t.to_s if book.tombo.nil?
end

def self.dc_fields
Expand Down
2 changes: 1 addition & 1 deletion app/views/books/edit.html.erb
Expand Up @@ -133,7 +133,7 @@

</div>
<div class="span12">
<div class="form-actions">
<div class="form-actions">
<%= builder.submit 'Salvar', :class => 'btn btn-primary' %>
<%= link_to 'Cancel', books_path, :class => 'btn' %>
</div>
Expand Down
29 changes: 14 additions & 15 deletions app/views/books/index.html.erb
Expand Up @@ -14,33 +14,32 @@
</div>
<% end %>


<table class="table table-striped">
<thead>
<tr>
<th>Título</th>
<th>Autores</th>
<th><% if current_user %>Ações<% end %></th>
<th><% if @user.nil? %>Acervo<% end %></th>
<% if current_user %><th>Ações</th><% end %>
<% if @user.nil? %><th>Acervo</th><% end %>
</tr>
</thead>
<tbody>
<% @books.each do |book| %>
<% if book %>
<tr>
<td>
<%= link_to "#{book.title} #{book.volume}", params.merge({:book => book.tombo, :user => book.user.username}) %>
<%= link_to "#{book.title} #{book.volume}", params.merge({:book => book.tombo, :user => book.user.username}), :class => 'book-title' %>
</td>
<td><%= book.authors.map(&:name).join(', ') %></td>
<td>
<% if can? :update, book %>
<td><a href="#" rel="tooltip" title="<%= book.authors.map(&:name).join(', ') %>"><%= truncate(book.authors.map(&:name).join(', ')) %></a></td>
<% restricted_to([book.user, admin]) do %>
<td>
<%= link_to 'Editar', edit_user_book_path(book.user, book), :class => 'btn btn-mini' %>
<% end %>
<% if can? :destroy, book %>
<%= link_to 'Deletar', user_book_path(book.user, book), :method => :delete, :confirm => 'Tem certeza?', :class => 'btn btn-mini btn-danger' %>
<% end %>
</td>
<td><% if @user.nil? %><%= link_to book.user.name, user_books_path(book.user) %><% end %></td>
</td>
<% end %>
<% if @user.nil? %>
<td><%= link_to book.user.name, user_books_path(book.user) %></td>
<% end %>
</tr>
<% end %>
<% end %>
Expand All @@ -51,8 +50,8 @@
<%= paginate @books %>
</div>

<% if current_user %>
<% if @user == current_user || (current_user.admin? && @user) %>
<%= link_to 'Novo livro', new_user_book_path(@user), :class => 'btn btn-primary' %>
<% restricted_to([@user, admin]) do %>
<% if @user %>
<%= link_to 'Novo livro', new_user_book_path(@user), :class => 'btn btn-primary' %>
<% end %>
<% end %>
4 changes: 2 additions & 2 deletions app/views/books/new.html.erb
Expand Up @@ -42,7 +42,7 @@
<div class="control-group">
<%= builder.label :volume, 'Volume', :class => 'control-label' %>
<div class="controls">
<%= builder.number_field :volume, :class => 'number_field' %>
<%= builder.text_field :volume, :class => 'number_field' %>
</div>
</div>

Expand Down Expand Up @@ -71,7 +71,7 @@
<div class="control-group">
<%= builder.label :page_number, 'Páginas', :class => 'control-label' %>
<div class="controls">
<%= builder.number_field :page_number, :class => 'number_field' %>
<%= builder.text_field :page_number, :class => 'number_field' %>
</div>
</div>

Expand Down
16 changes: 7 additions & 9 deletions app/views/books/show.html.erb
Expand Up @@ -6,12 +6,16 @@
</div>
<% end %>

<p>
<strong>Acervo:</strong>
<%=h @book.user.name %>
</p>
<p>
<strong>Tombo:</strong>
<%=h @book.tombo %>
</p>
<p>
<strong>Título:</strong>
<strong>Título:</strong>
<%=h @book.title %>
</p>
<% if !@book.subtitle.blank? %>
Expand Down Expand Up @@ -107,18 +111,12 @@
</p>

<div class="form-actions">
<%# if @user %>
<%#= link_to 'Voltar', user_books_path(@user), :class => 'btn' %>
<%# else %>
<%#= link_to 'Voltar', books_path, :class => 'btn' %>
<%# end %>
<% params.delete(:book) %>
<% params.delete(:user) %>
<%= link_to 'Voltar', params, :class => 'btn' %>
<% if can? :update, @book%>
<% restricted_to([@user, admin]) do %>
<%= link_to 'Editar', edit_user_book_path(@book.user, @book), :class => 'btn' %>
<% end %>
<% if can? :destroy, @book%>
<%= link_to 'Deletar', user_book_path(@book.user, @book), :method => 'delete', :confirm => 'Tem certeza?', :class => 'btn btn-danger' %>
<% end %>
</div>

0 comments on commit ee829ae

Please sign in to comment.