From 0781b680ad3a3337ebe6450bbe607379afe0c01e Mon Sep 17 00:00:00 2001 From: jonkaplan Date: Sat, 1 Jun 2024 12:57:52 -0400 Subject: [PATCH] Basic pundit setup with OrderPolicy on create - Needs to be integrated into a controller with `authorize @order` to be useful - Add a default ApplicationPolicy using `pundit install` --- Gemfile | 2 ++ Gemfile.lock | 3 ++ app/jobs/stock_purchase_job.rb | 11 +++++++ app/policies/application_policy.rb | 53 ++++++++++++++++++++++++++++++ app/policies/order_policy.rb | 5 +++ 5 files changed, 74 insertions(+) create mode 100644 app/jobs/stock_purchase_job.rb create mode 100644 app/policies/application_policy.rb create mode 100644 app/policies/order_policy.rb diff --git a/Gemfile b/Gemfile index 797fa1f..0de456d 100644 --- a/Gemfile +++ b/Gemfile @@ -41,3 +41,5 @@ group :test do gem "selenium-webdriver" gem "webmock" end + +gem "pundit", "~> 2.3" diff --git a/Gemfile.lock b/Gemfile.lock index 86f2482..d1c9090 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -218,6 +218,8 @@ GEM public_suffix (5.0.5) puma (6.4.2) nio4r (~> 2.0) + pundit (2.3.2) + activesupport (>= 3.0.0) racc (1.7.3) rack (3.0.10) rack-session (2.0.0) @@ -388,6 +390,7 @@ DEPENDENCIES pg (~> 1.1) pry (~> 0.14.2) puma (>= 5.0) + pundit (~> 2.3) rails (~> 7.1.3, >= 7.1.3.2) selenium-webdriver shadcn-ui (~> 0.0.12) diff --git a/app/jobs/stock_purchase_job.rb b/app/jobs/stock_purchase_job.rb new file mode 100644 index 0000000..af07efd --- /dev/null +++ b/app/jobs/stock_purchase_job.rb @@ -0,0 +1,11 @@ +class StockPurchaseJob < ApplicationJob + queue_as :default + + def perform + pending_orders = Order.pending + + pending_orders.each do |pending_order| + PurchaseStock.execute(pending_order) + end + end +end diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb new file mode 100644 index 0000000..be644fe --- /dev/null +++ b/app/policies/application_policy.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +class ApplicationPolicy + attr_reader :user, :record + + def initialize(user, record) + @user = user + @record = record + end + + def index? + false + end + + def show? + false + end + + def create? + false + end + + def new? + create? + end + + def update? + false + end + + def edit? + update? + end + + def destroy? + false + end + + class Scope + def initialize(user, scope) + @user = user + @scope = scope + end + + def resolve + raise NoMethodError, "You must define #resolve in #{self.class}" + end + + private + + attr_reader :user, :scope + end +end diff --git a/app/policies/order_policy.rb b/app/policies/order_policy.rb new file mode 100644 index 0000000..74d33af --- /dev/null +++ b/app/policies/order_policy.rb @@ -0,0 +1,5 @@ +class OrderPolicy < ApplicationPolicy + def create? + user.portfolio == resource.portfolio + end +end