Skip to content

Instantly share code, notes, and snippets.

@angusluk
Last active October 19, 2017 07:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angusluk/f98bd7c37e28263acb6dc970e8fe27d7 to your computer and use it in GitHub Desktop.
Save angusluk/f98bd7c37e28263acb6dc970e8fe27d7 to your computer and use it in GitHub Desktop.
sample-form-request
require 'faraday'
require 'faraday-cookie_jar'
def new_faraday_session
Faraday.new do |conn|
conn.use :cookie_jar
conn.request :url_encoded
conn.adapter :net_http
end
end
def extract_csrf_token(faraday, url)
faraday.get(url).body.match([
Regexp.escape(%{<meta name="csrf-token" content="}),
%{(?<csrf_token>.+?)},
Regexp.escape(%{" />})
].join)[:csrf_token]
end
def submit_rsvp_form(rsvp_url, attendee_params={})
faraday = new_faraday_session
csrf_token = extract_csrf_token(faraday, rsvp_url)
post_url = rsvp_url.gsub(/\/edit$/, '')
post_data = {
_method: 'patch',
authenticity_token: csrf_token
}
post_data.merge!(attendee_params)
faraday.post(post_url) do |req|
req.body = post_data
end
end
begin
rsvp_url = <to_be_filled_in>
response = submit_rsvp_form(rsvp_url, {
'attendee[rsvp_group_ids]': '7566',
'attendee[phone]': '+85263035703',
'attendee[answers_attributes][0][question_id]': '324', //not necessary
'attendee[answers_attributes][0][answer]': 'answer' //not necessary
})
success = (response.status == 302 && response.headers['location'].include?('/rsvp/'))
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment