Skip to content

meltheadorable/whitelist_scope

Repository files navigation

#Whitelist Scope

Gem VersionBuild StatusCode ClimateCoverage StatusDependency StatusDocumentation Status

whitelist_scope provides a safe way to register and call scopes inside rails apps

⚠️ Warning:

whitelist_scope is in the very early stages of development right now, has few tests and could introduce breaking changes. Use at your own risk.

Getting Started

To get started, add whitelist_scope to your gemfile:

gem 'whitelist_scope'

Then run bundle install to fetch the current version.

Usage

Using WhitelistScope is very simple. All you need to do is specify whitelisted scopes in your models, then call call_whitelisted_scope in your controllers naming a scope.

Models

Whitelist Scope acts as a wrapper around ActiveRecord scopes, providing a tiny bit of extra functionality to keep track of the whitelist.

If you don't know what scopes are, you can read about them here:

First you'll need to extend WhitelistScope, and then you can specify your scopes.

class Item < ActiveRecord::Base
  extend WhitelistScope # includes the whitelist_scope methods in your model

  whitelist_scope :most_recent, -> { order(updated_at: :desc) }
  whitelist_scope :created_first, -> { order(created_at: :asc) }
  whitelist_scope :approved, -> { where(approved: true) }
  whitelist_scope :featured, -> { where(featured: true) }
end

whitelist_scope takes a symbol as a name, and a lambda, exactly like an ActiveRecord scope.

Controllers

For your controllers, WhitelistScope provides the call_whitelisted_scope method, which takes a string naming one of your whitelisted scopes as an argument. Because WhitelistScope uses scopes under the hood, it can be chained with other scopes.

⚠️ Warning:

The whitelist_scope method will raise a NoMethodError if it cannot find a whitelisted with the name you passed in.

class ItemController < ApplicationController
  def index
    @items = Item.call_whitelisted_scope("most_recent") # sorts your items by most recent
    @others = Item.call_whitelisted_scope(params[:sort]) # sorts by the method specified in the params
    @approved_features = Item.call_whitelisted_scope("approved", "featured") # call multiple at once
  end
end

Because it uses scopes under the hood, WhitelistScope also provides separate methods for your whitelisted scopes:

class ItemController < ApplicationController
  def index
    @items = Item.created_first # all of your Items, sorted by creation date
  end
end

License

WhitelistScope is released under the MIT License

About

No description, website, or topics provided.

Resources

License

Code of conduct

Stars

Watchers

Forks

Packages

No packages published

Languages