From 51945a65a5b565517e4f7a1ed04320eff35c3f23 Mon Sep 17 00:00:00 2001 From: Alex Kotov Date: Fri, 8 Feb 2019 12:32:33 +0500 Subject: [PATCH] Add method Role.make! --- app/models/account.rb | 16 ++++------------ app/models/role.rb | 13 +++++++++++++ spec/models/role_spec.rb | 2 ++ 3 files changed, 19 insertions(+), 12 deletions(-) diff --git a/app/models/account.rb b/app/models/account.rb index d7f6a30..95d3801 100644 --- a/app/models/account.rb +++ b/app/models/account.rb @@ -64,18 +64,10 @@ class Account < ApplicationRecord def add_role(role_name, resource = nil) raise 'can not add role to guest account' if guest? - resource_type = - resource.is_a?(Class) ? resource.to_s : resource&.class&.name - - resource_id = resource&.id unless resource.is_a? Class - - role = self.class.role_class.where( - name: role_name, - resource_type: resource_type, - resource_id: resource_id, - ).first_or_create! - - add_role_record role, resource + add_role_record( + self.class.role_class.make!(role_name, resource), + resource, + ) end def remove_role(role_name, resource = nil) diff --git a/app/models/role.rb b/app/models/role.rb index ce396ad..9560cc5 100644 --- a/app/models/role.rb +++ b/app/models/role.rb @@ -24,6 +24,19 @@ class Role < ApplicationRecord scopify + def self.make!(role_name, resource = nil) + resource_type = + resource.is_a?(Class) ? resource.to_s : resource&.class&.name + + resource_id = resource&.id unless resource.is_a? Class + + find_or_create_by!( + name: role_name, + resource_type: resource_type, + resource_id: resource_id, + ) + end + def human_name I18n.translate name, scope: :roles end diff --git a/spec/models/role_spec.rb b/spec/models/role_spec.rb index bfad00d..4e7904d 100644 --- a/spec/models/role_spec.rb +++ b/spec/models/role_spec.rb @@ -18,6 +18,8 @@ RSpec.describe Role do .through(:account_roles) end + pending '.make!' + describe '#name' do def allow_value(*) super.for :name