Skip to content

Instantly share code, notes, and snippets.

@maetl
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maetl/3d6330093aaf3bc175bf to your computer and use it in GitHub Desktop.
Save maetl/3d6330093aaf3bc175bf to your computer and use it in GitHub Desktop.
Several more or less hacky ways to generate filter parameters as described in the JSON API recommendation (http://jsonapi.org/recommendations/). It looks as if using “filter[name]=value” directly is incompatible with the URI Template specification documented in RFC6570, but “filter%5Bname%5D=value” works. Unsure if that’s expected or not. The Fi…
require 'addressable/template'
class Filter::RawParams
def initialize(params)
@params = params
end
def encode_value(value)
Addressable::URI.encode_component(value, Addressable::URI::CharacterClasses::UNRESERVED)
end
def to_s
@params.reduce([]) do |param,(key,val)|
if val.is_a?(Array)
value = val.map { |v| encode_value(v) }.join(',')
else
value = encode_value(val)
end
param << "filter[#{key}]=#{value}"
end.join('&')
end
end
require 'addressable/template'
class Filter::Template < Addressable::Template
MAPPER = -> (k) { "filter_.#{k}._" }
def expand(mapping, processor=nil)
if mapping.key?(:filter)
mapping[:filter] = Hash[mapping[:filter].map { |k,v| [MAPPER.call(k), v] }]
end
result = self.pattern.dup
mapping = normalize_keys(mapping)
result.gsub!( EXPRESSION ) do |capture|
transform_capture(mapping, capture, processor)
end
result.gsub!('_.', '[')
result.gsub!('._', ']')
return Addressable::URI.parse(result)
end
end
require 'addressable/template'
class Filter::TemplateBuilder
def initialize(params)
@params = params
end
MAPPER = -> (k) { "filter[#{k}]" }
def to_s
Addressable::Template('{?filter*}').expand({
:filter => Hash[@params.map { |k,v| [MAPPER.call(k), v] }]
}).to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment