add support to specify author models

main
Washington Botelho 2017-11-03 00:02:23 -02:00
parent cd51130143
commit 722eb9ef05
No known key found for this signature in database
GPG Key ID: BECE10A8106CC7A0
7 changed files with 43 additions and 4 deletions

View File

@ -272,6 +272,15 @@ article.rates_records
# { value: 1 }, { value: 3, scopeable: category_1 }, { value: 5, scopeable: category_2 }
```
### As
If you have a model that will only be able to rate but not to receive a rate, configure it as `author`.
An author model still can be rated, but won't genarate a Rating record with all values as zero to be easier to display.
```ruby
rating as: :author
```
## Love it!
Via [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=X8HEP2878NDEG&item_name=rating) or [Gratipay](https://gratipay.com/rating). Thanks! (:

View File

@ -31,8 +31,8 @@ module Rating
end
module ClassMethods
def rating
after_create { Rating.find_or_create_by resource: self }
def rating(as: nil)
after_create -> { Rating.find_or_create_by resource: self }, unless: -> { as == :author }
has_many :rating_records,
as: :resource,

View File

@ -0,0 +1,7 @@
# frozen_string_literal: true
FactoryBot.define do
factory :author do
sequence(:name) { |i| "Author #{i}" }
end
end

View File

@ -3,10 +3,10 @@
require 'rails_helper'
RSpec.describe Rating::Extension, ':after_create' do
context 'when creates object' do
context 'with :as as nil' do
let!(:user) { create :user }
it 'creates a record with zero values just to be easy to make the count' do
it 'creates a rating record with zero values just to be easy to make the count' do
rating = Rating::Rating.find_by(resource: user)
expect(rating.average).to eq 0
@ -17,4 +17,12 @@ RSpec.describe Rating::Extension, ':after_create' do
expect(rating.total).to eq 0
end
end
context 'with :as as :author' do
let!(:author) { create :author }
it 'does not creates a rating record' do
expect(Rating::Rating.exists?(resource: author)).to eq false
end
end
end

View File

@ -0,0 +1,9 @@
# frozen_string_literal: true
class CreateAuthorsTable < ActiveRecord::Migration[5.0]
def change
create_table :authors do |t|
t.string :name, null: false
end
end
end

View File

@ -3,6 +3,7 @@
require File.expand_path('../../lib/generators/rating/templates/db/migrate/create_rating_tables.rb', __dir__)
CreateArticlesTable.new.change
CreateAuthorsTable.new.change
CreateCategoriesTable.new.change
CreateRatingTables.new.change
CreateUsersTable.new.change

View File

@ -0,0 +1,5 @@
# frozen_string_literal: true
class Author < ::ActiveRecord::Base
rating as: :author
end