class Margrid::Grid
Public Class Methods
new(id, relation)
click to toggle source
# File lib/margrid/grid.rb, line 3 def initialize(id, relation) @id = id @relation = relation @registered_components = {sorter: Sorter, paginator: Paginator} @components = {} end
Public Instance Methods
component(comp_sym)
click to toggle source
Get the component for a given comp_sym
.
# File lib/margrid/grid.rb, line 22 def component(comp_sym) @components[comp_sym] end
component?(comp_sym)
click to toggle source
Check wether a component is registered or not.
# File lib/margrid/grid.rb, line 17 def component?(comp_sym) @components.key? comp_sym end
dump(comps = nil)
click to toggle source
Dump components to a nested Hash.
# File lib/margrid/grid.rb, line 47 def dump(comps = nil) comps ||= @components.values grid_params = comps.inject({}) do |params, comp| params.merge(comp.dump) end {"margrid" => {@id => grid_params}} end
load(params)
click to toggle source
Load components from a Hash.
# File lib/margrid/grid.rb, line 36 def load(params) grid_params = params.fetch("margrid", {}).fetch(@id, {}) @registered_components.each do |comp_sym, comp_class| if comp = comp_class.load(grid_params) prepend comp_sym => comp end end self end
param_prefix()
click to toggle source
# File lib/margrid/grid.rb, line 75 def param_prefix @param_prefix ||= "margrid[#{@id}]" end
prepend(comp_hash)
click to toggle source
Attach components to the grid. This method can be called multiple times. Prepending a component will overwrite existing components.
comp_hash
uses a comp_sym
as key and a component instance as value.
# File lib/margrid/grid.rb, line 30 def prepend(comp_hash) @components.update comp_hash self end
register(comp_sym, comp_class, comp = nil)
click to toggle source
# File lib/margrid/grid.rb, line 10 def register(comp_sym, comp_class, comp = nil) @registered_components[comp_sym] = comp_class @components[comp_sym] = comp unless comp.nil? self end
rows()
click to toggle source
Rows to display in the grid. This will apply every registered component to the ActiveRecord::Relation
passed upon grid initialization. This method returns a new ActiveRecord::Relation
representing the grid rows.
# File lib/margrid/grid.rb, line 69 def rows @rows ||= @components.values.inject(@relation) do |relation, comp| comp.apply(relation) end end
to_query(comps = nil)
click to toggle source
Dump components to a Hash. The key of the Hash is the rack param name.
# File lib/margrid/grid.rb, line 56 def to_query(comps = nil) comps ||= @components.values comps.inject({}) do |params, comp| comp.dump.each do |k, v| params[param_prefix + "[#{k}]"] = v end params end end