Skip to content

Commit 987a49d

Browse files
author
Lee Richmond
committed
Allow querying via escaped JSON
Pass `{{{ "id": 1 }}}` and `value` yielded by `allow_filter` will be ruby hash of `{ 'id' => 1 }`
1 parent 219c1c9 commit 987a49d

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

lib/jsonapi_compliable/scoping/filter.rb

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -61,19 +61,28 @@ def each_filter
6161
# foo,bar,baz becomes ["foo", "bar", "baz"]
6262
# {{foo}} becomes ["foo"]
6363
# {{foo,bar}},baz becomes ["foo,bar", "baz"]
64+
#
65+
# JSON of
66+
# {{{ "id": 1 }}} becomes { 'id' => 1 }
6467
def parse_string_arrays(value)
65-
if value.is_a?(String)
66-
# Find the quoted strings
67-
quotes = value.scan(/{{.*?}}/)
68-
# remove them from the rest
69-
quotes.each { |q| value.gsub!(q, '') }
70-
# remove the quote characters from the quoted strings
71-
quotes.each { |q| q.gsub!('{{', '').gsub!('}}', '') }
72-
# merge everything back together into an array
73-
value = Array(value.split(',')) + quotes
74-
# remove any blanks that are left
75-
value.reject! { |v| v.length.zero? }
76-
value = value[0] if value.length == 1
68+
if value.is_a?(String)# && value[0..2] != '{{{'
69+
# Escaped JSON
70+
if value[0..2] == '{{{'
71+
value = value.sub('{{', '').sub('}}', '')
72+
value = JSON.parse(value)
73+
else
74+
# Find the quoted strings
75+
quotes = value.scan(/{{.*?}}/)
76+
# remove them from the rest
77+
quotes.each { |q| value.gsub!(q, '') }
78+
# remove the quote characters from the quoted strings
79+
quotes.each { |q| q.gsub!('{{', '').gsub!('}}', '') }
80+
# merge everything back together into an array
81+
value = Array(value.split(',')) + quotes
82+
# remove any blanks that are left
83+
value.reject! { |v| v.length.zero? }
84+
value = value[0] if value.length == 1
85+
end
7786
end
7887
value
7988
end

spec/filtering_spec.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
allow_filter :temp do |scope, value, ctx|
1818
scope.where(id: ctx.runtime_id)
1919
end
20+
21+
allow_filter :by_json do |scope, value|
22+
scope.where(id: value['id'])
23+
end
2024
end
2125
end
2226

@@ -87,6 +91,17 @@
8791
end
8892
end
8993

94+
context 'when filter is escaped JSON' do
95+
before do
96+
params[:filter] = { by_json: '{{{ "id": 2 }}}' }
97+
end
98+
99+
it 'works' do
100+
ids = scope.resolve.map(&:id)
101+
expect(ids).to eq([author2.id])
102+
end
103+
end
104+
90105
context 'when filter is a {{string}} with a comma' do
91106
before do
92107
params[:filter] = { first_name: '{{foo,bar}}' }

0 commit comments

Comments
 (0)