Sha256: 014bfa41b487478c216aa0e66b4259ccfb604552352cf1983093d6e0ca98cc10

Contents?: true

Size: 1.91 KB

Versions: 2

Compression:

Stored size: 1.91 KB

Contents

module TypedForm
  # A representation of the Typeform Form Data for a single form response.
  class Form
    extend Forwardable

    # @!method responses
    # @see FormData::ParsedJson#responses
    def_delegators :parsed_json, :responses

    # @!method questions
    # @see FormSubmission#questions
    def_delegators :submission, :questions

    # Creates a new instance of a Form, to allow querying
    #
    # @params [String] json Typeform Data API JSON input for form.
    def initialize(json:)
      @raw_json = json
    end

    # Removes non-breaking spaces (character point 160) from TypeForm data
    # before beginning processing.
    def json
      @_json ||= @raw_json.gsub("\\u00a0", " ")
    end

    # Uses the Typeform API client to query/find the form based on the form_id
    # and token, then builds a new Form from that JSON request.
    # @param [API::Client] client Typeform API client instance
    # @param [String] form_id Form ID you're querying
    # @param [String] token The token for the response you're retrieving
    # @return [Form] A Form, via JSON fetched from Typeform's API
    def self.find_form_by(client:, form_id:, token:)
      json = client.find_form_by(form_id: form_id, token: token)
      new(json: json)
    end

    # Builds a hash of Questions matched with Answers.
    # @return [Hash] A Hash matching { "Question" => "Answer" } format.
    def to_hash
      questions.each_with_object({}) { |q, hash| hash[q.text] = q.answer }
    end

    def response
      raise StandardError, "Form expects a single response" if multi_response?
      responses.first
    end

    private

    def submission
      @_submission ||= FormData::FormSubmission.new(
        parsed_questions: parsed_json.questions,
        parsed_response: response
      )
    end

    def multi_response?
      responses.size > 1
    end

    def parsed_json
      @_parsed_json ||= FormData::ParsedJson.new(json: json)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
typed_form-0.1.3 lib/typed_form/form.rb
typed_form-0.1.2 lib/typed_form/form.rb