Skip to content

Instantly share code, notes, and snippets.

@sharipov-ru
Created April 5, 2013 12:35
Show Gist options
  • Save sharipov-ru/5318975 to your computer and use it in GitHub Desktop.
Save sharipov-ru/5318975 to your computer and use it in GitHub Desktop.
100.times do
user = FactoryGirl.create(:user)
form = FactoryGirl.create(:form)
# Example usage of a Submissions-storage to read/write submissions (user answers)
# It let us don't care much in application how would storage work and which database it uses
# Write a value to storage
#
# user.storage_for(form.token).store(key, value)
#
# or
#
# user.storage_for(form.token).store(array_with_fields)
#
# Get list of filled forms for user:
#
# user.storage_for(form.token).list
#
# Get list of fields with values for particular form:
#
# user.storage_for(form.token).values
# Filling out record extensions data for user:
# Storage will write it somewhere (MySQL, MongoDB)
user.storage_for(form.token).store([
{ type: "NumberField", label: "Mother's name", value: 'Nikki' },
{ type: "NumberField", label: "Father's name", value: 'Matt' },
{ type: "TextField", label: "Mother's age", value: '29' },
{ type: "TextField", label: "Father's age", value: '30' },
]
end
@barkerja
Copy link

I was thinking of maybe creating a DSL for forms/record extensions.

  # This creates a user submission for the form with ID 1
  submission = user.form.find(1) do |form|
    text 'First Name', 'John'
    text 'Last Name', 'Barker'
    email 'Email Address', 'jabarker1@gmail.com'
    phone 'Phone Number', '1234567890'
    select 'Favorite TV Show?', ['Dexter', 'Homeland', 'Game of Thrones'], 'Dexter'
    address 'Home Address', Address.new(address_1: '123 Main Street', city: 'City', state: 'State')
    invoice 'Some Erroneous Bill', Invoice.standalone({ name: form.name, user_id: user.id, organization_id: form.organization_id, items: [{ PAY_FIELDS_FROM_FORM }] })
  end

  # submission now contains a submission model with its embedded answers
  submission.save

  # Record Extensions are essentially the same as forms, but handled through the
  # record_extension association
  submission = user.record_extensions.find(1) do
    text "Mother's First Name", 'Jane'
    text "Mother's Last Name", 'Doe'
    address "Mother's Address", Address.new(address_1: '123 Main Street', city: 'City', state: 'State')
  end

  submission = user.forms.find(1).submission
  submission.each do |label,value|
    puts "#{label}: #{value}"
  end

  # => First Name: John
  # => Last Name: Barker
  # => Email Address: jabarker1@gmail.com
  # => Phone Number: 123-456-7890
  # => Favorite TV Show?: Dexter
  # => Home Address: ['123 Main Street', ['City', 'State']]
  # => Some Erroneous Bill: $20 (Not Paid)

  # Or

  submission['Favorite TV Show?'] # => Dexter
  submission[4] # => Dexter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment