Class: Montage::OrderParser

Inherits:
Object
  • Object
show all
Defined in:
lib/montage/query/order_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(clause) ⇒ OrderParser

Creates an OrderParser instance based on a clause argument. The instance can then be parsed into a valid ReQON string for queries

  • Args :

    • clause -> A hash or string ordering value

  • Returns :

    • A Montage::OrderParser instance

  • Raises :

    • ClauseFormatError -> If a blank string clause or a hash without a valid direction is found.



19
20
21
22
23
24
# File 'lib/montage/query/order_parser.rb', line 19

def initialize(clause)
  @clause = clause
  fail(
    ClauseFormatError, "Order direction missing or blank clause found!"
  ) unless clause_valid?
end

Instance Attribute Details

#clauseObject (readonly)

Returns the value of attribute clause.



6
7
8
# File 'lib/montage/query/order_parser.rb', line 6

def clause
  @clause
end

Instance Method Details

#clause_valid?Boolean

Validates clause arguments by checking a hash for a full word match of “asc” or “desc”. String clauses are rejected if they are blank or consist entirely of whitespace

  • Returns :

    • A boolean

Returns:

  • (Boolean)


33
34
35
36
37
38
39
40
41
# File 'lib/montage/query/order_parser.rb', line 33

def clause_valid?
  if @clause.is_a?(Hash)
    @clause.flatten.find do |e|
      return true unless (/\basc\b|\bdesc\b/).match(e).nil?
    end
  else
    return true unless @clause.split.empty?
  end
end

#parseObject

Determines clause datatype and triggers the correct parsing



76
77
78
# File 'lib/montage/query/order_parser.rb', line 76

def parse
  @clause.is_a?(Hash) ? parse_hash : parse_string
end

#parse_hashObject

Parses a hash clause

  • Returns :

    • A ReQON formatted array

  • Examples :

    @clause = { test: "asc"}
    @clause.parse
    => ["$order_by", ["$asc", "test"]]
    


52
53
54
55
56
# File 'lib/montage/query/order_parser.rb', line 52

def parse_hash
  direction = clause.values.first
  field = clause.keys.first.to_s
  ["$order_by", ["$#{direction}", field]]
end

#parse_stringObject

Parses a string clause, defaults direction to asc if missing or invalid

  • Returns :

    • A ReQON formatted array

  • Examples :

    @clause = "happy_trees desc"
    @clause.parse
    => ["$order_by", ["$desc", "happy_trees"]]
    


67
68
69
70
71
72
# File 'lib/montage/query/order_parser.rb', line 67

def parse_string
  direction = clause.split[1]
  field = clause.split[0]
  direction = "asc" unless %w(asc desc).include?(direction)
  ["$order_by", ["$#{direction}", field]]
end