Class: Sorted::ActiveRecord::Builder

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

Defined Under Namespace

Classes: ParseError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sort: [], order: [], whitelist: []) ⇒ Builder

Returns a new instance of Builder.



12
13
14
15
16
17
18
19
20
# File 'lib/sorted/active_record/builder.rb', line 12

def initialize(sort: [], order: [], whitelist: [])
  @return_hash = true
  uri = parse_sort(sort)
  if whitelist.length > 0
    uri = ::Sorted::Set.new(uri.select { |o| whitelist.include?(o[0]) })
  end
  sql = parse_order(order)
  @set = uri + (sql - uri)
end

Instance Attribute Details

#setObject (readonly)

Returns the value of attribute set.



10
11
12
# File 'lib/sorted/active_record/builder.rb', line 10

def set
  @set
end

Instance Method Details

#parse(values) ⇒ Object

rubocop:disable Metrics/MethodLength rubocop:disable Metrics/AbcSize



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/sorted/active_record/builder.rb', line 49

def parse(values)
  values.inject(Sorted::Set.new) do |memo, value|
    case value.class.name
    when 'Hash'
      memo += parse(value.to_a)
    when 'String'
      @return_hash = false
      memo += ::Sorted::SQLQuery.parse(value)
    when 'Symbol'
      memo = memo << [value.to_s, 'asc']
    when 'Array'
      memo = memo << [value[0].to_s, value[1].to_s]
    else
      raise ParseError, "could not parse - #{value}"
    end
    memo
  end
end

#parse_order(order) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/sorted/active_record/builder.rb', line 34

def parse_order(order)
  return ::Sorted::Set.new if order.nil?
  case order.class.name
  when 'String'
    @return_hash = false
    ::Sorted::SQLQuery.parse(order)
  when 'Array'
    parse(order)
  else
    raise ParseError, "could not parse sort - #{order}"
  end
end

#parse_sort(sort) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/sorted/active_record/builder.rb', line 22

def parse_sort(sort)
  return ::Sorted::Set.new if sort.nil?
  case sort.class.name
  when 'String'
    ::Sorted::URIQuery.parse(sort)
  when 'Array'
    parse(sort)
  else
    raise ParseError, "could not parse sort - #{sort}"
  end
end

#to_hashObject

We return sym here becuase rails 4.0.0 does not like string for values and keys.



70
71
72
# File 'lib/sorted/active_record/builder.rb', line 70

def to_hash
  @set.to_a.inject({}) { |a, e| a.merge(Hash[e[0].to_sym, e[1].to_sym]) }
end

#to_sqlObject



74
75
76
# File 'lib/sorted/active_record/builder.rb', line 74

def to_sql
  @return_hash ? to_hash : ::Sorted::SQLQuery.encode(@set)
end