### User Grid Using Custom Base Class
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
An example of a `UsersGrid` that inherits from the custom `ApplicationGrid`, demonstrating the use of scopes and the custom `timestamp_column` helper.
```ruby
# app/grids/users_grid.rb
class UsersGrid < ApplicationGrid
scope { User }
column(:name)
timestamp_column(:created_at)
end
```
--------------------------------
### Version 1 Datagrid Form HTML
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Example HTML output for a Datagrid form in Version 1, showcasing its structure and CSS classes.
```html
```
--------------------------------
### Run Tests with Appraisals
Source: https://github.com/bogdan/datagrid/blob/main/CONTRIBUTING.md
Use this method to run tests against different Rails versions using the appraisals gem. Ensure all dependencies are installed first.
```shell
bundle install
bundle exec appraisal install
bundle exec appraisal rails-8.1 rake
```
```shell
bundle exec appraisal rails-7.0 rake
```
--------------------------------
### Instantiate and Use a Datagrid Report
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Instantiate a Datagrid report with specific parameters and access its data. This example demonstrates how to set filters, sorting, and retrieve the header, rows, and full data. The SQL query generated by the report is also shown.
```ruby
report = UsersGrid.new(
group_id: [1,2],
logins_count: [1, nil],
category: "first",
order: :group,
descending: true
)
report.assets # => Array of User instances:
# SELECT * FROM users WHERE users.group_id in (1,2) AND
# users.logins_count >= 1 AND
# users.category = 'first'
# ORDER BY groups.name DESC
report.header # => ["Name", "Group", "Activated"]
report.rows # => [
# ["Steve", "Spammers", false],
# [ "John", "Spoilers", false],
# ["Berry", "Good people", true]
# ]
report.data # => [ header, *rows]
report.to_csv # => Yes, it is
```
--------------------------------
### Version 2 Datagrid Form HTML
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Example HTML output for a Datagrid form in Version 2, demonstrating updated structure and CSS class names.
```html
```
--------------------------------
### Export Datagrid to PDF using Ruport
Source: https://github.com/bogdan/datagrid/wiki/PDF-Export
Generates a PDF report from Datagrid data using the Ruport gem. Ensure 'ruport' is installed.
```ruby
require 'ruport' # gem install ruport
f = File.new("report.pdf", "w")
f.write Ruport::Data::Table.new(:column_names =>report.header, :data => report.rows).to_pdf
f.close
```
--------------------------------
### Run Tests with BUNDLE_GEMFILE
Source: https://github.com/bogdan/datagrid/blob/main/CONTRIBUTING.md
Alternatively, run tests against specific Rails versions by setting the BUNDLE_GEMFILE environment variable. This requires installing dependencies for each specified Gemfile.
```shell
BUNDLE_GEMFILE=gemfiles/rails_8.1.gemfile bundle install
BUNDLE_GEMFILE=gemfiles/rails_8.1.gemfile bundle exec rake
```
```shell
BUNDLE_GEMFILE=gemfiles/rails_7.0.gemfile bundle install
BUNDLE_GEMFILE=gemfiles/rails_7.0.gemfile bundle exec rake
```
--------------------------------
### Migrating Column Class Option to Tag Options
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Provides an example of migrating from the deprecated `class` column option to the more flexible `tag_options` in Datagrid V2.
```ruby
# V1
column(:status, class: 'issue-status')
# V2
column(:status, tag_options: {class: 'issue-status'})
```
--------------------------------
### V1 Filter Input Markup
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Example of how filters were rendered in Datagrid V1, using CSS classes for meta-information like filter name and type.
```html
```
--------------------------------
### Define a Datagrid Class
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Define a Datagrid class by specifying the scope, filters, and columns. This example shows how to set up filters for category, disabled status, group ID, login counts, and group name, along with columns for name, group, and active status.
```ruby
class UsersGrid < Datagrid::Base
scope do
User.includes(:group)
end
filter(:category, :enum, select: ["first", "second"])
filter(:disabled, :xboolean)
filter(:group_id, :integer, multiple: true)
filter(:logins_count, :integer, range: true)
filter(:group_name, :string, header: "Group") do |value|
self.joins(:group).where(groups: {name: value})
end
column(:name)
column(:group, order: -> { joins(:group).order(groups: :name) }) do |user|
user.name
end
column(:active, header: "Activated") do |user|
!user.disabled
end
end
```
--------------------------------
### Configure Filter Input Type with input_options
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Customize the HTML input type for filters using the `input_options` argument. This example shows how to revert to 'text' for date and integer types, and how to specify 'textarea' for string types.
```ruby
filter(:created_at, :date, range: true, input_options: {type: 'text'})
filter(:salary, :integer, range: true, input_options: {type: 'text', step: nil})
```
```ruby
class ApplicationGrid < Datagrid::Base
def self.filter(name, type = :default, input_options: {}, **options)
if [:date, :datetime, :float, :integer].include?(type)
input_options[:type] ||= 'text'
end
super(name, type, input_options:, **options)
end
end
```
```ruby
# Rendered as tag:
filter(:text, :string, input_options: {type: 'textarea'})
```
--------------------------------
### Define a Datagrid Column with Formatting
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Define a datagrid column with a custom header, sorting option, and a block to calculate the value. This example shows how to define an 'activated' column with a header 'Active' and a value derived from the 'activated?' method.
```ruby
column(:activated, header: "Active", order: "activated", after: :name) do
self.activated?
end
```
--------------------------------
### Generate Datagrid Scaffold
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Use the Rails generator to create a datagrid scaffold for a given resource. This command generates the grid class, controller, view, and routes, providing a starting point for your datagrid implementation.
```ruby
rails g datagrid:scaffold skills
```
--------------------------------
### Implement datagrid_order_for in ApplicationHelper
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
The `datagrid_order_for` helper is deprecated. This shows how to implement it in `ApplicationHelper` if needed, rendering the `datagrid/order_for` partial.
```ruby
module ApplicationHelper
def datagrid_order_for(grid, column)
render(partial: "datagrid/order_for", locals: { grid: grid, column: column })
end
end
```
--------------------------------
### Initialize Datagrid with JSON Attributes
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Initializes a UsersGrid object by loading attributes from a JSON string. This is useful for reconstructing grid states.
```ruby
grid = UsersGrid.new(ActiveSupport::JSON.load(grid.attributes.to_json))
```
--------------------------------
### Publish Datagrid Views
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Run this command to publish the datagrid's built-in views to your application. This allows you to customize the default frontend appearance and behavior of your datagrids.
```sh
rails g datagrid:views
```
--------------------------------
### Migrate column[url] option to format block
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Version 1 used `column[url]` for defining links. Version 2 uses a `format` block with `link_to` for more flexibility.
```ruby
column(:user, url: -> (user) => { user_profile_path(user) }) do
user.name
end
```
```ruby
column(:user) do |user|
format(user.name) do |value|
link_to value, user_profile_path(user)
end
end
```
--------------------------------
### Inherit Datagrid::Base for custom grids
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Version 2 recommends inheriting from `Datagrid::Base` for custom grid classes, similar to how most gems provide a base class.
```ruby
class ApplicationGrid < Datagrid::Base
end
```
--------------------------------
### Adding HTML Class to Datagrid Column (V1)
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Demonstrates how to attach an HTML class to a column in Datagrid version 1 using the `class` option.
```ruby
column(:name, tag_options: { class: 'short-column' })
```
--------------------------------
### Datagrid Column with HTML Attributes (V2)
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Shows how to apply arbitrary HTML attributes to column headers and cells in Datagrid version 2 using the `tag_options` parameter.
```html
Name
...
John
```
--------------------------------
### Datagrid Structure and Data Access
Source: https://github.com/bogdan/datagrid/wiki/PDF-Export
Accessing header, rows, and combined data from a Datagrid instance.
```ruby
report = MyGrid.new
report.header # => ["Group", "Name", "Activated"]
report.rows # => [
# ["Steve", "Spammers", true],
# [ "John", "Spoilers", true],
# ["Berry", "Good people", false]
# ]
report.data # => [ header, *rows]
```
--------------------------------
### Datagrid V1 HTML Table Structure
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Illustrates the basic HTML table structure used by Datagrid version 1 for displaying data, including column headers and data rows.
```html
Name
Category
John
Worker
Mike
Manager
```
--------------------------------
### Custom Datagrid Base Class Definition
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Defines a custom base class for Datagrids, renamed from `BaseGrid` to `ApplicationGrid` to align with Rails naming conventions. Includes a helper method for timestamp columns.
```ruby
# app/grids/application_grid.rb
class ApplicationGrid < Datagrid::Base
def self.timestamp_column(name, *args, &block)
column(name, *args) do |model|
value = block ? block.call(model) : model.public_send(name)
value&.strftime("%Y-%m-%d")
end
end
end
```
--------------------------------
### Datagrid Form Helper
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Generates an HTML form for a Datagrid object. This is the primary method for creating interactive grid forms.
```ruby
datagrid_form_for(@grid)
```
--------------------------------
### Base PDF Report Class with PrawnPDF
Source: https://github.com/bogdan/datagrid/wiki/PDF-Export
Defines a base class for PDF reports using PrawnPDF, including table row colors and font size settings. Requires the 'prawn' gem.
```ruby
gem 'prawn'
```
```ruby
class PdfReport < Prawn::Document
TABLE_ROW_COLORS = ["FFFFFF","DDDDDD"]
TABLE_FONT_SIZE = 9
def initialize(default_prawn_options={})
super(default_prawn_options)
font_size 10
end
def header(title=nil)
text title, size: 18, style: :bold, align: :center if title
end
end
```
--------------------------------
### Controller Action for PDF Export
Source: https://github.com/bogdan/datagrid/wiki/PDF-Export
Configures a controller to respond with a PDF export of the identities report. The PDF is generated using the IdentitiesPdfReport class and sent as an attachment.
```ruby
respond_to do |format|
format.html
format.csv do
...
end
format.pdf do
send_data IdentitiesPdfReport.new(@title, @grid.header, @grid.rows).render,
type: "application/pdf",
disposition: 'attachment',
filename: "identities-#{Time.current.to_s}.pdf"
end
end
```
--------------------------------
### Datagrid V1 Range Filter Input HTML
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Illustrates the HTML output for range filter inputs in Datagrid version 1, which lacked `id` attributes for inputs, potentially causing W3C validation warnings.
```html
-
```
--------------------------------
### Range Filter Input Generation (V2)
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Datagrid V2 generates 'from' and 'to' input fields for range filters by default, using a hash structure for parameters. This ensures proper typecasting to a Range object.
```html
-
```
--------------------------------
### V2 Filter Input Markup with Data Attributes
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Datagrid V2 renders filters using data attributes (e.g., `data-filter`, `data-type`) for meta-information, offering a more semantic and collision-proof approach compared to V1's class-based system.
```html
```
--------------------------------
### Datagrid V2 HTML Table Structure
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Shows the updated HTML table structure in Datagrid version 2, utilizing `data-column` attributes for column identification.
```html
Name
Category
John
Worker
Mike
Manager
```
--------------------------------
### Use datagrid_form_with instead of datagrid_form_for
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Rails deprecates `form_for` in favor of `form_with`. Datagrid v2 follows this by introducing `datagrid_form_with`.
```ruby
# V1
datagrid_form_for(@users_grid, url: users_path)
# V2
datagrid_form_with(model: @users_grid, url: users_path)
```
--------------------------------
### Range Filter Assignment (V2)
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Assigning a hash with 'from' and 'to' keys to a range filter automatically converts it into a Range object.
```ruby
grid.members_count = {from: 1, to: 5}
grid.members_count # => 1..5
```
--------------------------------
### Custom Identities PDF Report Class
Source: https://github.com/bogdan/datagrid/wiki/PDF-Export
Extends the base PdfReport class to display identity data, including headers and rows, with custom formatting. Handles cases with no identities found.
```ruby
class IdentitiesPdfReport < PdfReport
def initialize(title, header=[], rows=[])
super()
@header = header
@rows = rows
header title
display_table
end
private
def display_table
if @rows.empty?
text "No Identities Found"
else
table @rows.unshift(@header),
header: true,
width: bounds.width,
row_colors: TABLE_ROW_COLORS,
cell_style: { size: TABLE_FONT_SIZE }
end
end
end
```
--------------------------------
### Range Filter Assignment (V1 Compatibility)
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
The old convention of assigning an array to a range filter is still supported for backward compatibility, converting it into a Range object.
```ruby
grid.members_count = [3, 7]
grid.members_count # => 3..7
```
--------------------------------
### Use endless ranges for range filters
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Datagrid v2 supports Ruby's endless ranges for range filters, replacing the need for Hash or Array representations. Old formats are converted.
```ruby
class UsersGrid < Datagrid::Base
filter(:id, :integer, range: true) do |value, scope|
# V1 value is [1, nil]
# V2 value is 1..nil
scope.where(id: value)
end
end
```
```ruby
grid = UsersGrid.new
grid.id = [1, nil]
grid.id # V1: [1, nil]
# V2: (1..nil)
```
```ruby
grid.id = 1..5
grid.id # => 1..5
grid.id = "1..5"
grid.id # => 1..5
grid.id = [nil, 5]
grid.id # => ..5
grid.id = nil..nil
grid id # => nil
grid.id = 3..7
# Simulate serialization/deserialization when interacting with
```
--------------------------------
### Define a Datagrid Scope
Source: https://github.com/bogdan/datagrid/blob/main/README.md
Define the default scope of objects for the datagrid. This is typically an ActiveRecord::Base subclass or any other supported ORM, often with generic scopes included.
```ruby
scope do
User.includes(:group)
end
```
--------------------------------
### Find Broken Range Filters Script
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
A Ruby script to identify and list all filters that are broken with `range: true` and a custom block. This script is specific to V2.
```ruby
puts "This script is intended to be run as a separate file."
```
--------------------------------
### Datagrid V2 Range Filter Input HTML with ID
Source: https://github.com/bogdan/datagrid/blob/main/version-2/Readme.markdown
Shows the HTML for range filter inputs in Datagrid version 2, which now generates an `id` attribute for the first input to improve accessibility and W3C validation.
```html
-
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.