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



105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/datagrid/core.rb', line 105

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 scope at class level

Examples:

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


51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/datagrid/core.rb', line 51

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