Class: Margrid::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/margrid/builder.rb

Overview

Utility class to ease the creation of Margrid::Grid instances. It can be subclassed to provide more specialized behavior for your applications.

class MyBuilder < Margrid::Builder
  def self.articles(id: "articles", relation: Articles.all)
    builder = new Margrid::Grid.new(id, relation)
    builder.sort_by "published_at", "desc"
    builder
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(grid) ⇒ Builder

Returns a new instance of Builder.



15
16
17
# File 'lib/margrid/builder.rb', line 15

def initialize(grid)
  @grid = grid
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args) ⇒ Object



39
40
41
42
43
44
# File 'lib/margrid/builder.rb', line 39

def method_missing(sym, *args)
  if @grid.respond_to?(sym)
    @grid = @grid.send(sym, *args)
    self
  end
end

Instance Attribute Details

#gridObject (readonly)

Returns the value of attribute grid.



13
14
15
# File 'lib/margrid/builder.rb', line 13

def grid
  @grid
end

Instance Method Details

#load(params) ⇒ Object

Deserialize Margrid components from a hash. This is usually the case when the state using the query string.

NOTE: this method should be the last call when chaining Builder methods. It will return the Margrid::Grid instance and not the builder itself.



35
36
37
# File 'lib/margrid/builder.rb', line 35

def load(params)
  @grid.load(params)
end

#paginated(current_page: 1) ⇒ Object

Configure the grid to use pagination.



20
21
22
# File 'lib/margrid/builder.rb', line 20

def paginated(current_page: 1)
  prepend paginator: Margrid::Paginator.new(current_page)
end

#sort_by(column, direction) ⇒ Object

Sort the grid by column in direction. Direction can be :asc or :desc



26
27
28
# File 'lib/margrid/builder.rb', line 26

def sort_by(column, direction)
  prepend sorter: Margrid::Sorter.new(column, direction)
end