Class: Muster::Strategies::SortExpression

Inherits:
Hash
  • Object
show all
Defined in:
lib/muster/strategies/sort_expression.rb

Overview

Query string parsing strategy with additional value handling for sort orders

Examples:


strategy = Muster::Strategies::SortExpression.new
results  = strategy.parse('sort=name:desc')  #=>  { 'sort' => 'name desc' }

Instance Attribute Summary

Attributes inherited from Hash

#unique_values, #value_separator

Attributes inherited from Rack

#fields, #options

Instance Method Summary collapse

Methods inherited from Hash

#initialize, #separate_values

Methods inherited from Rack

#fields_to_parse, #initialize, #parse_query_string

Constructor Details

This class inherits a constructor from Muster::Strategies::Hash

Instance Method Details

#parse(query_string) ⇒ Hash

Processes a query string and returns a hash of its fields/values

Examples:


results = strategy.parse('order=name')            #=>  { 'order' => 'name asc' }
results = strategy.parse('order=name:desc')       #=>  { 'order' => 'name desc' }
results = strategy.parse('order=name,date:desc')  #=>  { 'order' => ['name asc', 'date desc'] }

Parameters:

  • query_string (String)

    the query string to parse

Returns:



26
27
28
29
30
31
32
# File 'lib/muster/strategies/sort_expression.rb', line 26

def parse( query_string )
  parameters  = super

  parameters.each do |key, value|
    parameters[key] = self.parse_sort_expression(value)
  end
end

#parse_direction(direction) ⇒ String (protected)

Parse and normalize the sot expression direction

Examples:


direction = self.parse_direction('ascending')   #=> 'asc'
direction = self.parse_direction('descending')  #=> 'desc'

Parameters:

  • direction (String)

    the direction to normalize

Returns:

  • (String)


69
70
71
# File 'lib/muster/strategies/sort_expression.rb', line 69

def parse_direction( direction )
  direction.to_s.match(/^desc/i) ? 'desc' : 'asc'
end

#parse_sort_expression(value) ⇒ String, Arrary (protected)

Separates the values into their field and direction

Examples:


value = self.parse_sort_expression('name:asc')  #=>  'name asc'
value = self.parse_sort_expression(['name:asc', 'date'])  #=>  ['name asc', 'date asc']

Parameters:

  • value (String)

    the value being parsed

Returns:

  • (String, Arrary)

    String if a single value, Array otherwise



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/muster/strategies/sort_expression.rb', line 46

def parse_sort_expression( value )
  values = Array.wrap(value)

  values = values.map do |value|
    name, direction = value.split(':', 2)
    direction = self.parse_direction(direction)

    "#{name} #{direction}"
  end.flatten

  return (values.size > 1) ? values : values.first
end