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



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

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



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

def api
  @api
end

#dataObject

Returns the value of attribute data



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

def data
  @data
end

#formObject

Returns the value of attribute form



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

def form
  @form
end

#ref(ref) ⇒ SearchForm

Set the reference to use

Parameters:

Returns:



351
352
353
# File 'lib/prismic.rb', line 351

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 197

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 202

#form_actionString

Returns the form's action (URL)

Returns:

  • (String)


248
249
250
# File 'lib/prismic.rb', line 248

def form_action
  form.action
end

#form_enctypeString

Returns the form's encoding type

Returns:

  • (String)


241
242
243
# File 'lib/prismic.rb', line 241

def form_enctype
  form.enctype
end

#form_fieldsString

Returns the form's fields

Returns:

  • (String)


255
256
257
# File 'lib/prismic.rb', line 255

def form_fields
  form.fields
end

#form_methodString

Returns the form's HTTP method

Returns:

  • (String)


227
228
229
# File 'lib/prismic.rb', line 227

def form_method
  form.form_method
end

#form_nameString

Returns the form's name

Returns:

  • (String)


220
221
222
# File 'lib/prismic.rb', line 220

def form_name
  form.name
end

#form_relString

Returns the form's relationship

Returns:

  • (String)


234
235
236
# File 'lib/prismic.rb', line 234

def form_rel
  form.rel
end

#orderings(orderings) ⇒ SearchForm

Specify a orderings for this form.

Parameters:

  • orderings (String)

    The orderings

Returns:



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

#page(page) ⇒ SearchForm

Specify a page for this form.

Parameters:

  • page (String, Fixum)

    The page

Returns:



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

#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 192

#q(*query) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/prismic.rb', line 161

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
    predicates = query.map { |q|
      op = q.shift
      "[:d = #{op}(#{q.map { |arg| serialize(arg) }.join(', ')})]"
    }
    set('q', "[#{predicates * ''}]")
  end
end

#query(*query) ⇒ Object

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



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

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

#serialize(field) ⇒ Object



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

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:



333
334
335
336
337
338
339
340
341
342
343
344
# File 'lib/prismic.rb', line 333

def set(field_name, value)
  field = @form.fields[field_name]
  unless value == nil
    if 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)



273
274
275
# File 'lib/prismic.rb', line 273

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:



290
291
292
293
294
295
296
297
298
299
300
301
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
# File 'lib/prismic.rb', line 290

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