Module: Datagrid::Core::ClassMethods

Defined in:
lib/datagrid/core.rb

Instance Method Summary collapse

Instance Method Details

#dynamic(&block) ⇒ void

This method returns an undefined value.

Allows dynamic columns definition, that could not be defined at class level Columns that depend on the database state or third party service can be defined this way.

Examples:

class MerchantsGrid

  scope { Merchant }

  column(:name)

  dynamic do
    PurchaseCategory.all.each do |category|
      column(:"#{category.name.underscore}_sales") do |merchant|
        merchant.purchases.where(category_id: category.id).count
      end
    end
  end
end

ProductCategory.create!(name: 'Swimwear')
ProductCategory.create!(name: 'Sportswear')

grid = MerchantsGrid.new
grid.data # => [
          #      [ "Name",   "Swimwear Sales", "Sportswear Sales", ... ]
          #      [ "Reebok", 2083382,            8382283,          ... ]
          #      [ "Nike",   8372283,            18734783,         ... ]
          #    ]

Parameters:

  • block (Proc)

    block that defines dynamic columns



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/datagrid/core.rb', line 134

def dynamic(&block)
  previous_block = dynamic_block
  self.dynamic_block =
    if previous_block
      proc {
        instance_eval(&previous_block)
        instance_eval(&block)
      }
    else
      block
    end
end

#scope(&block) ⇒ void

This method returns an undefined value.

Defines a relation scope of database models to be filtered

Examples:

scope { User }
scope { Project.where(deleted: false) }
scope { Project.preload(:stages) }


80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/datagrid/core.rb', line 80

def scope(&block)
  if block
    current_scope = scope_value
    self.scope_value = proc {
      Datagrid::Utils.apply_args(current_scope ? current_scope.call : nil, &block)
    }
    self
  else
    scope = original_scope
    driver.to_scope(scope)
  end
end