Class: Prismic::SearchForm

Inherits:
Object
  • Object
show all
Defined in:
lib/prismic.rb

Overview

A SearchForm represent a Form returned by the prismic.io API.

These forms depend on the prismic.io repository, and can be filled and sent as regular HTML forms.

You may get a SearchForm instance through the API#form method.

The SearchForm instance contains helper methods for each predefined form's fields. Note that these methods are not created if they risk to add confusion:

  • only letters, underscore and digits are authorized in the name
  • name starting with a digit or an underscore are forbidden
  • generated method can't override existing methods

Examples:

search_form = api.form('everything')
search_form.page(3)  # specify the field 'page'
search_form.page_size("20")  # specify the 'page_size' field
results = search_form.submit(master_ref)  # submit the search form
results = api.form('everything').page(3).page_size("20").submit(master_ref) # methods can be chained

Defined Under Namespace

Classes: AuthenticationException, AuthorizationException, FormSearchException, NoRefSetException, RefNotFoundException, UnsupportedFormKind

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api, form, data = {}, ref = nil) ⇒ SearchForm

Returns a new instance of SearchForm.



145
146
147
148
149
150
151
152
153
# File 'lib/prismic.rb', line 145

def initialize(api, form, data={}, ref=nil)
  @api = api
  @form = form
  @data = {}
  form.fields.each { |name, _| create_field_helper_method(name) }
  form.default_data.each { |key, value| set(key, value) }
  data.each { |key, value| set(key, value) }
  @ref = ref
end

Instance Attribute Details

#apiObject

Returns the value of attribute api.



143
144
145
# File 'lib/prismic.rb', line 143

def api
  @api
end

#dataObject

Returns the value of attribute data.



143
144
145
# File 'lib/prismic.rb', line 143

def data
  @data
end

#formObject

Returns the value of attribute form.



143
144
145
# File 'lib/prismic.rb', line 143

def form
  @form
end

#ref(ref) ⇒ SearchForm

Set the reference to use

Parameters:

Returns:



365
366
367
# File 'lib/prismic.rb', line 365

def ref
  @ref
end

Instance Method Details

#fetch(fields) ⇒ SearchForm

Restrict the document fragments to the specified fields

Parameters:

  • fields (String)

    The fields separated by commas (,)

Returns:



# File 'lib/prismic.rb', line 204

Include the document fragments correspondong to the specified fields for DocumentLink

Parameters:

  • fields (String)

    The fields separated by commas (,)

Returns:



# File 'lib/prismic.rb', line 209

#form_actionString

Returns the form's action (URL)

Returns:

  • (String)


260
261
262
# File 'lib/prismic.rb', line 260

def form_action
  form.action
end

#form_enctypeString

Returns the form's encoding type

Returns:

  • (String)


253
254
255
# File 'lib/prismic.rb', line 253

def form_enctype
  form.enctype
end

#form_fieldsString

Returns the form's fields

Returns:

  • (String)


267
268
269
# File 'lib/prismic.rb', line 267

def form_fields
  form.fields
end

#form_methodString

Returns the form's HTTP method

Returns:

  • (String)


239
240
241
# File 'lib/prismic.rb', line 239

def form_method
  form.form_method
end

#form_nameString

Returns the form's name

Returns:

  • (String)


232
233
234
# File 'lib/prismic.rb', line 232

def form_name
  form.name
end

#form_relString

Returns the form's relationship

Returns:

  • (String)


246
247
248
# File 'lib/prismic.rb', line 246

def form_rel
  form.rel
end

#lang(lang) ⇒ SearchForm

Specify a language for this form.

Parameters:

  • lang (String)

    The document language

Returns:



# File 'lib/prismic.rb', line 214

#orderings(orderings) ⇒ SearchForm

Specify a orderings for this form.

Parameters:

  • orderings (String)

    The orderings

Returns:



# File 'lib/prismic.rb', line 189

#page(page) ⇒ SearchForm

Specify a page for this form.

Parameters:

  • page (String, Fixum)

    The page

Returns:



# File 'lib/prismic.rb', line 194

#page_size(page_size) ⇒ SearchForm

Specify a page size for this form.

Parameters:

  • page_size (String, Fixum)

    The page size

Returns:



# File 'lib/prismic.rb', line 199

#q(*query) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/prismic.rb', line 162

def q(*query)
  def serialize(field)
    if field.kind_of?(String) and not (field.start_with?('my.') or field.start_with?('document'))
      %("#{field}")
    elsif field.kind_of?(Array)
      %([#{field.map{ |arg| serialize(arg) }.join(', ')}])
    else
      %(#{field})
    end
  end
  if query[0].kind_of?(String)
    set('q', query[0])
  else
    unless query[0][0].kind_of?(Array)
      query = [query]
    end
    predicates = query.map { |predicate|
      predicate.map { |q|
        op = q[0]
        rest = q[1..-1]
        "[:d = #{op}(#{rest.map { |arg| serialize(arg) }.join(', ')})]"
      }.join('')
    }
    set('q', "[#{predicates * ''}]")
  end
end

#query(*query) ⇒ Object

Specify a query for this form. @param query [String] The query @return [SearchForm] self



158
159
160
# File 'lib/prismic.rb', line 158

def query(*query)
  q(*query)
end

#serialize(field) ⇒ Object



163
164
165
166
167
168
169
170
171
# File 'lib/prismic.rb', line 163

def serialize(field)
  if field.kind_of?(String) and not (field.start_with?('my.') or field.start_with?('document'))
    %("#{field}")
  elsif field.kind_of?(Array)
    %([#{field.map{ |arg| serialize(arg) }.join(', ')}])
  else
    %(#{field})
  end
end

#set(field_name, value) ⇒ SearchForm

Specify a parameter for this form

Parameters:

  • field_name (String)

    The parameter's name

  • value (String)

    The parameter's value

Returns:



345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/prismic.rb', line 345

def set(field_name, value)
  field = @form.fields[field_name]
  unless value == nil
    if value == ""
      data[field_name] = nil
    elsif field && field.repeatable?
      data[field_name] = [] unless data.include? field_name
      data[field_name] << value.to_s
    else
      data[field_name] = value.to_s
    end
  end
  self
end

#submit(ref = nil) ⇒ Response

Note:

The reference MUST be defined, either by:

  • setting it at creation
  • using the #ref method
  • providing the ref parameter.

Submit the form

Parameters:

  • ref (Ref, String) (defaults to: nil)

    The reference to use (if not already defined)

Returns:

  • (Response)

    The results (array of Document object + pagination specifics)



285
286
287
# File 'lib/prismic.rb', line 285

def submit(ref = nil)
  Prismic::JsonParser.response_parser(JSON.load(submit_raw(ref)))
end

#submit_raw(ref = nil) ⇒ string

Note:

The reference MUST be defined, either by:

  • setting it at creation
  • using the #ref method
  • providing the ref parameter.

Submit the form, returns a raw JSON string

Parameters:

  • ref (Ref, String) (defaults to: nil)

    The reference to use (if not already defined)

Returns:

  • (string)

    The JSON string returned by the API

Raises:



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/prismic.rb', line 302

def submit_raw(ref = nil)
  self.ref(ref) if ref
  data['ref'] = @ref
  raise NoRefSetException unless @ref

  # cache_key is a mix of HTTP URL and HTTP method
  cache_key = form_method+'::'+form_action+'?'+data.map{|k,v|"#{k}=#{v}"}.join('&')

  from_cache = api.has_cache? && api.cache.get(cache_key)
  if (from_cache)
    from_cache
  else
    if form_method == 'GET' && form_enctype == 'application/x-www-form-urlencoded'
      data['access_token'] = api.access_token if api.access_token
      data.delete_if { |k, v| v.nil? }

      response = api.http_client.get(form_action, data, 'Accept' => 'application/json')

      if response.code.to_s == '200'
        ttl = (response['Cache-Control'] || '').scan(/max-age\s*=\s*(\d+)/).flatten.first
        if ttl != nil && api.has_cache?
          api.cache.set(cache_key, response.body, ttl.to_i)
        end
        response.body
      else
        body = JSON.load(response.body) rescue nil
        error = body.is_a?(Hash) ? body['error'] : response.body
        raise AuthenticationException, error if response.code.to_s == '401'
        raise AuthorizationException, error if response.code.to_s == '403'
        raise RefNotFoundException, error if response.code.to_s == '404'
        raise FormSearchException, error
      end
    else
      raise UnsupportedFormKind, "Unsupported kind of form: #{form_method} / #{enctype}"
    end
  end
end