首页
/ HasScope 项目技术文档

HasScope 项目技术文档

2024-12-23 08:13:39作者:裴锟轩Denise

本文档将详细介绍如何安装、使用 HasScope 项目,以及如何使用其 API。HasScope 是一个允许您基于传入的参数集动态地对资源应用命名作用域的 Ruby 库。

1. 安装指南

在您的项目中安装 HasScope,您可以通过以下两种方式之一进行:

  • 使用 Bundler 添加 HasScope:

    bundle add has_scope
    
  • 或者手动将其添加到您的 Gemfile 中:

    gem 'has_scope'
    

添加后,执行 bundle install 来安装宝石。

2. 项目使用说明

HasScope 可以在 Rails 控制器和普通 Ruby 对象中使用。以下是如何在控制器中使用 HasScope 的例子:

在 Rails 控制器中使用

首先,定义您的模型作用域。例如:

class Graduation < ActiveRecord::Base
  scope :featured, -> { where(featured: true) }
  scope :by_degree, ->(degree) { where(degree: degree) }
  scope :by_period, ->(started_at, ended_at) { where("started_at = ? AND ended_at = ?", started_at, ended_at) }
end

接着,在控制器中声明可以使用的作用域:

class GraduationsController < ApplicationController
  has_scope :featured, type: :boolean
  has_scope :by_degree
  has_scope :by_period, using: %i[started_at ended_at], type: :hash

  def index
    @graduations = apply_scopes(Graduation).all
  end
end

对于每个请求,HasScope 会自动根据请求参数应用相应的作用域。

在普通 Ruby 对象中使用

HasScope 也可以在普通 Ruby 对象中使用。首先,创建一个对象并包含 HasScope 模块:

class GraduationsSearchQuery
  include HasScope

  has_scope :featured, type: :boolean
  has_scope :by_degree
  has_scope :by_period, using: %i[started_at ended_at], type: :hash

  def perform(collection: Graduation, params: {})
    apply_scopes(collection, params)
  end
end

然后在控制器中使用这个对象:

class GraduationsController < ApplicationController
  def index
    graduations_query = GraduationsSearchQuery.new
    @graduations = graduations_query.perform(collection: Graduation, params: params)
  end
end

3. 项目 API 使用文档

HasScope 提供了以下选项来自定义作用域的使用:

  • :type - 检查传入参数的类型。
  • :only - 在哪些动作中应用作用域。
  • :except - 在哪些动作中不应用作用域。
  • :as - 在 params 哈希中预期的键名来找到作用域。
  • :using - 当类型为哈希时,用于作用域参数的子键。
  • :in - 一个简写,用于结合 :using 选项和嵌套哈希。
  • :if - 指定一个方法或程序块来决定是否应用作用域。
  • :unless - 指定一个方法或程序块来决定是否不应用作用域。
  • :default - 作用域的默认值。提供时,作用域总是被调用。
  • :allow_blank - 默认情况下,不发送空值给作用域。设置为 true 来覆盖此行为。

更多关于这些选项的详细信息,请参考项目 README 文档。

4. 项目安装方式

HasScope 的安装方式已在安装指南中详细描述。您可以通过 Bundler 或手动添加到 Gemfile 中来安装它。

以上就是 HasScope 项目的技术文档,希望对您使用该项目有所帮助。

登录后查看全文
热门项目推荐
相关项目推荐