class Prismic::SearchForm

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:

@example

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

Attributes

api[RW]
data[RW]
form[RW]
ref[RW]

Public Class Methods

new(api, form, data={}, ref=nil) click to toggle source
# 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

Public Instance Methods

form_action() click to toggle source

Returns the form's action (URL)

@return [String]

# File lib/prismic.rb, line 260
def form_action
  form.action
end
form_enctype() click to toggle source

Returns the form's encoding type

@return [String]

# File lib/prismic.rb, line 253
def form_enctype
  form.enctype
end
form_fields() click to toggle source

Returns the form's fields

@return [String]

# File lib/prismic.rb, line 267
def form_fields
  form.fields
end
form_method() click to toggle source

Returns the form's HTTP method

@return [String]

# File lib/prismic.rb, line 239
def form_method
  form.form_method
end
form_name() click to toggle source

Returns the form's name

@return [String]

# File lib/prismic.rb, line 232
def form_name
  form.name
end
form_rel() click to toggle source

Returns the form's relationship

@return [String]

# File lib/prismic.rb, line 246
def form_rel
  form.rel
end
q(*query) click to toggle source
# 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) click to toggle source

Specify a query for this form.

@param  query [String] The query
@return [SearchForm] self
# File lib/prismic.rb, line 158
def query(*query)
  q(*query)
end
serialize(field) click to toggle source
# 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) click to toggle source

Specify a parameter for this form @param field_name [String] The parameter's name @param value [String] The parameter's value

@return [SearchForm] self

# 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) click to toggle source

Submit the form @api

@note The reference MUST be defined, either by:

- setting it at {API#create_search_form creation}
- using the {#ref} method
- providing the ref parameter.

@param ref [Ref, String] The {Ref reference} to use (if not already

defined)

@return [Response] The results (array of Document object + pagination

specifics)
# File lib/prismic.rb, line 285
def submit(ref = nil)
  Prismic::JsonParser.response_parser(JSON.load(submit_raw(ref)))
end
submit_raw(ref = nil) click to toggle source

Submit the form, returns a raw JSON string @api

@note The reference MUST be defined, either by:

- setting it at {API#create_search_form creation}
- using the {#ref} method
- providing the ref parameter.

@param ref [Ref, String] The {Ref reference} to use (if not already

defined)

@return [string] The JSON string returned by the API

# 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

Private Instance Methods

create_field_helper_method(name) click to toggle source

Create the fields'helper methods

# File lib/prismic.rb, line 220
def create_field_helper_method(name)
  return if name == 'ref'
  return unless name =~ /\A[a-zA-Z][a-zA-Z0-9_]*\z/
  meth_name = name.gsub(/([A-Z])/, '_\1').downcase
  return if respond_to?(meth_name)
  define_singleton_method(meth_name){|value| set(name, value) }
end