ruby on rails - Howto add a new role with a custom permission set for Solidus / Spree? -


i want add new 'vendor' role. vendor can manage own products , orders, not see orders or products belonging other vendor.

i planning implement around stock location. e.g: 1 user vendor role belongs tokyo stock location. other user vendor role belongs other stock location.

which steps need me taken working?

1. create vendor role

$ rails console spree::role.create(name: 'vendor') 

2. define cancan permissions:

app/models/spree/multi_vendor_ability.rb

module spree   class multivendorability     include cancan::ability      def initialize(user)       user ||= spree::user.new # guest user (not logged in)       if user.admin?         can :manage, :all         puts "is admin"       else         can :read, :all         puts "not admin"       end        if user.stock_locations.present?         can  :manage, spree::stockitem, :stock_location_id => user.stock_locations.first.id       end     end    end end 

3. add new method spree::user

config/initializers/spree_user.rb

spree::user.class_eval      def vendor?       self.role_users.any? { |ru| ru.role.name == 'vendor' }     end  end 

4. rspec

spec/models/multi_vendor_spec.rb

require 'spec_helper'  describe spree::multivendorability   let(:ability) { spree::multivendorability.new(user) }   let(:user)    { create(:user) }   let(:product) { create :product }   let(:stock_location) { create(:stock_location_with_items) }   let(:stock_item) { stock_location.stock_items.order(:id).first }    subject { ability }    context "test"     before       rails.logger.debug "the stockitem #{stock_item.inspect}"       user.stock_locations = [stock_location]       user.save     end      context "when user associated stock location"        { is_expected.to be_able_to(:manage,  spree::stockitem) }     end      context "when user not associated stock location"         before           stock_item.stock_location_id = nil           stock_item.save           user.stock_locations = []           user.save           puts "the stockitem #{stock_item.inspect}"           user.stock_locations = []         end         { is_expected.to_not be_able_to(:manage, spree::stockitem) }     end    end  end 

Comments