rails no bitesize error to 3rd party API response - ruby-on-rails

I have a rails app and I'm trying to get calendar freebusy events from google. When I run the following code I get undefined method "bytesize" for #<Hash.. error for the result = client.execute(.... method. I checked out some other stackoverflow answers, but I can't see what I'm doing wrong. Anyone can tell me how I should deal with this problem?
controller
include GoogleCalendarApi
......
#user = current_user
#google = #user.socials.where(provider: "google_oauth2").first
unless #google.blank?
# #client = get_busy_events(#google)
# #result = open_gcal_connection(get_busy_events, #client, #google)
#result = get_busy_events(#google)
end
.....
lib/google_calendar_api.rb
def init_google_api_calendar_client(google_account)
#method only called if google_oauth2 social exists
client = Google::APIClient.new
client.authorization.access_token = google_account.token
client.authorization.client_id = ENV['GOOGLE_API_KEY']
client.authorization.client_secret = ENV['GOOGLE_API_SECRET']
client.authorization.refresh_token = google_account.refresh_token
return client
end
def get_busy_events(social_object)
client = init_google_api_calendar_client(social_object)
old_token = client.authorization.access_token
service = client.discovered_api('calendar', 'v3')
result = client.execute(
api_method: service.freebusy.query,
body: { timeMin: '2015-12-24T17:06:02.000Z',
timeMax: '2016-01-30T17:06:02.000Z',
items: [{ id: social_object.email }]},
headers: {'Content-Type' => 'application/json'})
new_token = client.authorization.access_token
if old_token != new_token
social_object.update_attribute(token: new_token)
end
return result
end
full error:
Google::APIClient - Initializing client with options {}
21:33:15 puma.1 | Google::APIClient - Please provide :application_name and :application_version when initializing the client
21:33:15 puma.1 | Google::APIClient::Request Sending API request get https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest {"User-Agent"=>"google-api-ruby-client/0.8.6 Mac OS X/10.10.4\n (gzip)", "Accept-Encoding"=>"gzip", "Content-Type"=>""}
21:33:15 puma.1 | Decompressing gzip encoded response (12528 bytes)
21:33:15 puma.1 | Decompressed (103479 bytes)
21:33:15 puma.1 | Google::APIClient::Request Result: 200 {"expires"=>"Thu, 31 Dec 2015 05:36:09 GMT", "date"=>"Thu, 31 Dec 2015 05:31:09 GMT", "etag"=>"\"ye6orv2F-1npMW3u9suM3a7C5Bo/U5WRLEvUgzkUohB7qwzTs2ir15o\"", "vary"=>"Origin, X-Origin", "content-type"=>"application/json; charset=UTF-8", "x-content-type-options"=>"nosniff", "x-frame-options"=>"SAMEORIGIN", "x-xss-protection"=>"1; mode=block", "content-length"=>"12528", "server"=>"GSE", "age"=>"126", "cache-control"=>"public, max-age=300, must-revalidate, no-transform", "alternate-protocol"=>"443:quic,p=1", "alt-svc"=>"quic=\":443\"; ma=604800; v=\"30,29,28,27,26,25\"", "connection"=>"close"}
21:33:15 puma.1 | Google::APIClient::Request Sending API request post https://www.googleapis.com/calendar/v3/freeBusy {"User-Agent"=>"google-api-ruby-client/0.8.6 Mac OS X/10.10.4\n (gzip)", "Content-Type"=>"application/json", "Accept-Encoding"=>"gzip", "Authorization"=>"Bearer ya29.WQKv43gUEb0Jt3jTBevBs0_Z9VurfGxmbH8Knv8E9Sqbw4zxeCHjydwUeyo3MSAotYj0", "Cache-Control"=>"no-store"}
21:33:15 puma.1 | Completed 500 Internal Server Error in 382ms (ActiveRecord: 0.8ms)
21:33:15 puma.1 |
21:33:15 puma.1 | NoMethodError - undefined method `bytesize' for #<Hash:0x007fb6d25b9330>:
21:33:15 puma.1 | /Users/Silo/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/net/http/generic_request.rb:182:in `send_request_with_body'
21:33:15 puma.1 | /Users/Silo/.rvm/rubies/ruby-2.2.3/lib/ruby/2.2.0/net/http/generic_request.rb:120:in `exec'

From Pardeep's link, try
result = client.execute(
api_method: service.freebusy.query,
body: URI.encode_www_form({ timeMin: '2015-12-24T17:06:02.000Z',
timeMax: '2016-01-30T17:06:02.000Z',
items: [{ id: social_object.email }]}),
headers: {'Content-Type' => 'application/json'})
The problem is that the body could not be sent as a hash. You should encode as an string.

Related

Display image on browser, where image get from the API response

I am working on sample application, where I have to show generated QR code. I am using http://goqr.me/api/ for generating the API.
Here is my sample code
class HomeController < ApplicationController
def index
end
def submit_qr
code = params[:code]
url = "https://api.qrserver.com/v1/create-qr-code/?data=#{params[:code]}&size=220x220&margin=0"
#response = HTTParty.get(url).parsed_response
end
end
When I check the call from rails console I am getting following
irb(main):004:0> url = "https://api.qrserver.com/v1/create-qr-code/?data=test&size=220x220&margin=0"
=> "https://api.qrserver.com/v1/create-qr-code/?data=test&size=220x220&margin=0"
irb(main):005:0> response = HTTParty.get(url)
=> #<HTTParty::Response:0x8efada0 parsed_response="\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x00\xDC\x00\x00\x00\xDC\x01\x03\x00\x00\x00!\x94]\xC2\x00\x00\x00\x06PLTE\xFF\xFF\xFF\x00\x00\x00U\xC2\xD3~\x00\x00\x01\x02IDATX\x85\xED\xD7\xBB\x11\x840\f\x04\xD0e\b\b)\xC1\xA5P\x1A\x94\xE6R(\x81\x90\x80A\x87\xFC\x05\x06\xCE\xC7\xA5\xAC\"\x8F\x1F\xD1\x0E\xB2lH\xAC\x01\xB5\x00\x8D\xA0\x8B;\x13\x88\x8A\x16Z\xB5\ff\x01\xCC\ft\xB3\xDBAO\f\xD8jRu\x88\x0F\x8A\xD5\xB6\xB3\x12\x9Fa\xCE\x96x\x13\x1F\\\xB3\x12\x9Faj\xDEmk\xD4\xE3\xED\xB2\xB3_\x8Ci\x00l\x7F\x9F\xC7\xDD\x00 \x16\xF0P\xBA\x85\xBBz+\x86\xA4j\xF1\xD0\x88\xD8fE7U\xDA\xB0\xC4\"Z\xE8i\xB6\xA0\x1F\xE1\xFF>(\xA6\xE3\x8D\xB8U\x15\xE6\xA7\x068\xC7\xAF\xC5M\x04b\tS\x8C&6n\xA3\xB4\xBA%1\xA1\xBF\xC2\xE6\xF8|\x7F\x12\x8B\x98\xCAH(\xBD~\xB8[\e\xF1t\xC3\x90\xF8\b?M\a\xE2\x17\xB4.\xD8\xF0\xC44!\xDB\xCE7/\xD1\xE1\xEE\x89\x99\xE7g\x8C\x8F\xF8\x17~\xCD\xF6\xCD\x18\a\x80m\x89?bl^\x97\xAD\xAE\xF5\x15#\xCC\x98\a\xC0!>9M\a\xE2\x15~\x00\xA9\xB7\xB6\x8EW\xEAb\xBE\x00\x00\x00\x00IEND\xAEB`\x82", #response=#<Net::HTTPOK 200 OK readbody=true>, #headers={"date"=>["Fri, 20 Mar 2020 10:33:39 GMT"], "server"=>["Apache/2"], "access-control-allow-origin"=>["*"], "access-control-allow-methods"=>["POST, GET, OPTIONS, DELETE, PUT"], "access-control-max-age"=>["7200"], "access-control-allow-headers"=>["Accept, Accept-Language, Content-Language, Content-Type, Origin, Authorization, X-Requested-With, Client-Security-Token"], "x-powered-by"=>["PHP/5.4.16"], "content-length"=>["333"], "connection"=>["close"], "content-type"=>["image/png"]}>
So how can I show the image on browser.
response = "\x89PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x00\xDC\x00\x00\x00\xDC\x01\x03\x00\x00\x00!\x94]\xC2\x00\x00\x00\x06PLTE\xFF\xFF\xFF\x00\x00\x00U\xC2\xD3~\x00\x00\x01\x02IDATX\x85\xED\xD7\xBB\x11\x840\f\x04\xD0e\b\b)\xC1\xA5P\x1A\x94\xE6R(\x81\x90\x80A\x87\xFC\x05\x06\xCE\xC7\xA5\xAC\"\x8F\x1F\xD1\x0E\xB2lH\xAC\x01\xB5\x00\x8D\xA0\x8B;\x13\x88\x8A\x16Z\xB5\ff\x01\xCC\ft\xB3\xDBAO\f\xD8jRu\x88\x0F\x8A\xD5\xB6\xB3\x12\x9Fa\xCE\x96x\x13\x1F\\\xB3\x12\x9Faj\xDEmk\xD4\xE3\xED\xB2\xB3_\x8Ci\x00l\x7F\x9F\xC7\xDD\x00 \x16\xF0P\xBA\x85\xBBz+\x86\xA4j\xF1\xD0\x88\xD8fE7U\xDA\xB0\xC4\"Z\xE8i\xB6\xA0\x1F\xE1\xFF>(\xA6\xE3\x8D\xB8U\x15\xE6\xA7\x068\xC7\xAF\xC5M\x04b\tS\x8C&6n\xA3\xB4\xBA%1\xA1\xBF\xC2\xE6\xF8|\x7F\x12\x8B\x98\xCAH(\xBD~\xB8[\e\xF1t\xC3\x90\xF8\b?M\a\xE2\x17\xB4.\xD8\xF0\xC44!\xDB\xCE7/\xD1\xE1\xEE\x89\x99\xE7g\x8C\x8F\xF8\x17~\xCD\xF6\xCD\x18\a\x80m\x89?bl^\x97\xAD\xAE\xF5\x15#\xCC\x98\a\xC0!>9M\a\xE2\x15~\x00\xA9\xB7\xB6\x8EW\xEAb\xBE\x00\x00\x00\x00IEND\xAEB`\x82"
decoded_image = Base64.strict_encode64(response)
base64_img = "data:image/png;base64," + decoded_image
Something like this

How send email with BCC header via GMAIL API?

How can I send email with BCC via GMAIL API? I send emails to TO or CC but BCC doesn't work. I use Base64.urlsafe_encode64(email.to_s)and this code create string without BCC. My working code example:
email = Mail.new
email.date = Time.now
email.subject = subject
email.to = email_array_to_email_to(to)
email.cc = email_array_to_email_to(cc)
email.bcc = email_array_to_email_to(bcc)
email.reply_to = email_array_to_email_to(reply_to)
email.html_part do
body message
end
request = {
api_method: #google_api.users.messages.to_h['gmail.users.messages.send'],
parameters: { userId: 'me' },
body_object: {
raw: Base64.urlsafe_encode64(email.to_s)
},
}
Do I have to call again GMAIL API and send this email with thread id and BCC as TO?
I use google-api-client 0.7.1
EDIT:
Mail object:
#<Mail::Message:70336725981360,
Multipart: true,
Headers: <Date: Tue,
01 Dec 2015 14:09:08 +0100>,
<Reply-To: >,
<To: ["quatermain32 <my_email#gmail.com>"]>,
<Cc: ["quatermain32 <my_email#gmail.com>"]>,
<Bcc: ["my_email#gmail.com"]>,
<Subject: Test subject>,
<Content-Type: multipart/mixed>>
Mail object with to_s:
"Date: Tue, 01 Dec 2015 14:09:08 +0100\r\n
To: my_email <my_email#gmail.com>\r\n
Cc: my_email <my_email#gmail.com>\r\n
Message-ID: <565d9c6e3cf0b_058b7#Olivers-MacBook-Pro.local.mail>\r\n
Subject: Test subject\r\n
Mime-Version: 1.0\r\n
Content-Type: multipart/mixed;\r\n
boundary=\"--==_mimepart_565d9bf468e77_cb0d35e200577a\";\r\n
charset=UTF-8\r\n
Content-Transfer-Encoding: 7bit\r\n
\r\n
\r\n
----==_mimepart_565d9bf468e77_cb0d3ff88645e200577a\r\n
Content-Type: text/html;\r\n
charset=UTF-8\r\n
Content-Transfer-Encoding: 7bit\r\n
\r\n
<p>Test content</p>\r\n
----==_mimepart_565d9bf468e77_cb0d3ff88645e200577a--\r\n
"
You have to manually add the bcc header to the email, it will not be sent to the recipients. Same as gmail-ruby-api does it https://github.com/jhk753/gmail-ruby-api/blob/e0d62a751bc31397926c5800532f26e185e00b16/lib/gmail/message.rb
encoded = mail.encoded
if bcc = mail.bcc.join(",").presence
encoded.prepend "Bcc: #{bcc}\n"
end
... send email ...

Cannot save a post to a database

I have an Event app, where I am using a calendar. I have created 2 external routes and controller action to #save and #load data and I have 2 templates for them. One is save.json.erb other one is load.json.erb. For now, I have hardcoded the load data from load.json.erb, looks like;
{"2015-05-06": {"available":"1",
"bind":0,
"info":"",
"notes":"",
"price":"20",
"promo":"",
"status":"available"
},
"2015-05-07": {"available":"1",
"bind":0,
"info":"",
"notes":"",
"price":"20",
"promo":"",
"status":"available"
}}
So, it shows the hardcoded data on the calendar.
My problem is, when I press submit, it does not give an error but it does not save it to database. I could not figure out the strong params either. I am using permit! for now to see it saves to database. Maybe my Event Model and its columns are wrong. Because I could not figure it out what it posts (integer, string etc..)
Here is my events_controller
....
def load
end
def save
#THIS IS WRONG I SHOULD PUT SMTH ELSE
#event = Event.new
#event.save
end
def event_params
params.require(:event).permit!
end
when I select data from calendar press submit it sends this;
HEADER:
event_id:0
event:{"2015-05-06":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-07":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-27":{"available":"1","bind":0,"info":"demo","notes":"demodemodemo","price":"15","promo":"2","status":"available"}}
Also from the log; Is this data JSON?, or I have to use JSON.parse somewhere?
Started POST "/events/save" for ::1 at 2015-05-02 18:39:42 +0300
Processing by EventsController#save as */* #HERE IT SENDS THE PARAMETERS, BUT I COULD NOT GET THEM
Parameters: {"event_id"=>"0", "event"=>"{\"2015-05-06\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"20\",\"promo\":\"\",\"status\":\"available\"},\"2015-05-07\":{\"available\":\"1\",\"bind\":0,\"info\":\"\",\"notes\":\"\",\"price\":\"20\",\"promo\":\"\",\"status\":\"available\"},\"2015-05-27\":{\"available\":\"1\",\"bind\":0,\"info\":\"demo\",\"notes\":\"demodemodemo\",\"price\":\"15\",\"promo\":\"2\",\"status\":\"available\"}}"}
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "events" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-05-02 15:39:42.823906"], ["updated_at", "2015-05-02 15:39:42.823906"]]
(2.4ms) commit transaction
Rendered events/save.json.erb (0.1ms)
Completed 200 OK in 21ms (Views: 12.9ms | ActiveRecord: 3.0ms)
When I try;
def save
#event = Event.new(event_params)
#event.save
end
def event_params
params.require(:event).permit!
end
It gives an error of ;
NoMethodError in EventsController#save
undefined method `permit!' for #<String:0x007fcbb99d24c0>
So I think it is posted as a string instead of a hash.
For me, there is something wrong with the data it sends to database or the database can not configured for these datas. Because of #save action has #events = Event.new all the time it creates new event in the database and saves it.So I have to get the POSTed data but I could not get those parameters. I think I have to take the POSTed data and with for loops I have to take those data and save it to database. Could not find a way. Hope someone helps
Here is the full HEADER:
Cache-Control:no-cache
Connection:Keep-Alive
Content-Length:0
Content-Type:application/json; charset=utf-8
Date:Sat, 02 May 2015 18:42:54 GMT
Server:WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)
Set-Cookie:_demo_session=Snh1Nm5CNWJzTHNITXp5SkRDejNmZzRXRkdoVm5SeEkwUW82WmE5QkFndThkeUdyTEdBK2s3ZVR1aEUxQXpGclpqR202WTIzSGkzNWtIQUdWZXFFeUtmSVpBbnZZNmJnN090YUxXS2c5eFFPVzZOaXJjTGJndGRsS0xBcUhaU0VlMFAvRVdtT05RMHpLcUYrSy9wSElnPT0tLUI2SWFiOHZXRlpqMmpteVloV3Zsb2c9PQ%3D%3D--3533fcf1e966b5c1e766dcc099caa6df4b5c284f; path=/; HttpOnly
X-Content-Type-Options:nosniff
X-Frame-Options:SAMEORIGIN
X-Request-Id:7863cf16-0162-4760-8719-d155202eca7a
X-Runtime:0.030455
X-Xss-Protection:1; mode=block
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:3126
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:_Paint_session=NXN5NVUvemhXcHF2UnF1ZlBXTHhtZVVWODlyVWFoL0tEWU9vWCtOYVp6ck9EUVF6OUs0WTJYV21yWW5VeVhqdndST2JUYTdCdnNnamNzZDJjQXFLNE1CYzlQT3dtcVJiRTJLcmlwaXR3aFdKZUZBVXN4VitWamMzaWdZUUtTQU1mcWhIRFg3SnJwQ2FBK1hmclZ3WmtiODRuTUpVRUVLKzYzQTNuUGxCTURYMHhKN3Z6eUZtbURLS2MybVlNejNoTmo5MVZteUQzcG8wTnB6WUFlR2pRK2UwSHFnUTVua0hUM0VzWitLUTdya1BXVVZ1eTVKUmNCR3pQaEh2djlpcFo3dFU1WmhZYlhSWS9wYTBVSHRTYXc9PS0tbDJHT3A3NVJ1Tm5OczVIREM2emNLQT09--f2703914b69129404c69d1d9dbb446fde16c6442; _Resim_session=cXQ5cEE5ZjFPNU1Jby9ZY0lKWis2TVY1NVlaN2dVZGtSaDdzc3B1QU9saS9yNXNUUHE5N2d1Ym1CZjcxYlNNZjAwbnhPNm9oeEN0aUpNUXZYMXM1Q2ZHWHJuZ3lhdjhxRmxteVR3ZXFvNHdxMFJZcXp6NWZMbk1qWVJyZG5GVFdBWVVtRkp5MHZsZWVNTzZ1aGs4ejAxUzFoZWE2VHVlWCtuWFBpclZnQU5GR2dzeUFZZFBWeEZaSCsxWUhHNmRkQVhwYk9uWW5oVjd4VVA5L2xvRzR3amt2RmE4VTdjUzRHRHQvRC80Rys0V0ZWQ2FCTW01cWtNQ2E2SHUwYWFFQ080VVJkUEduUWxpUjNaUkZldWZsOWc9PS0tcnM2M2UyVCttTEJBbW13SVJQN3RNQT09--3233372784be95cd2d6e2630f7e5e22c17eeff17; _Carrierwave_session=cE4vek43aGlxZ3BrSFNXWU1JaDZQekcxdlVVSnRzNFRMbGNXRGxjOGhNZ0hGNHRaSFpzODQ1YU95WXVnb1VKUlM3Y0xBVFBjYW1paG5FSTh5dVVzYm1LWXNHVXd2RGJnNktaZ0YxY1JtM25Rb1hLMkhUWm5XTElZS1JUejAxSmFvcnE3VzVXTVFoYmdPbTczOE02Wjk4N2hsaTJDRFdLY2pRc1NxYVRNVFBHdkFHbmEvb1U4aEN4T2FOVDZWZGlUMnpJMU0yNkdHNW1acVpYN3NzRkxwQkN2TzRzS0ZBNlMwMGtIMGJ5bWN2QVp5Q3cxQUNIVnExajFDSldsZWhJek1zUjJxVzJyRHRsUDBjQnJsdlB1RFE9PS0tSjViSGdocSs5blRLdTNnUk1GWk9qZz09--068ded1e78c2d70739361e662b995b5470a059c4; _raddit_session=Vy9USHZBa1FodGxON1BMOWFZOHBIazk3eWVSOXh0OW9yUjRmSjJ5Tmg1OXpsMnI2Tm5ZTGQwOHdEMVJnUWhFNG5jRVZEcVhLL3ZCSVdsM1g5S2FTMjYvZWo4U1ovT0xNdkZVT2dJS0VWTkRMcXdRQ0lzTlFRWC9EZ1ZxbDRtYmtLQ1dkZzM3THltSEFvdzJTN010MHVnYytJMzE1R2F0cUVkQlh2bERBRUM4c0NVNnFsTFdmbVB1cURJeDVHUkhKOWZUOG5pUlhFZkxOSkJ3c01uU2paTW50WXRrRW8zRmJtTTBrUm5GWlJvbz0tLUh4ckZqdnA3WGQzRjdmNnAzMXdMcmc9PQ%3D%3D--622d3f9adb9afb871e118d0715921aaf986f82d2; _Cal_session=cjRlSlc0Q2FITHJJTmlTbU5TZjk5aFNFaTczTHRQZW9TR0h1MG4xYVovZG9xaUxyNittWENjbXdib3FLc1J6cXh3dHA5YitaVkZYbFVtaFI2bGxUKzJyM1kvRzJlRFV4b0JibzJ1TTdQS0ZkdVE2eVJJSlZQVXY0Q0thS1NBRzhGUzlaQ1ZRaHppYzJES2V2eXRmVWtBPT0tLWEzVWFIcWl0WnJBRVdnanJ0em1Renc9PQ%3D%3D--03a65bd6c5338108d2d3db62295843f8b3e3eaaa; _fullcalendar_and_rails_example_session=M1h0eFJieVY1ek16OWRtR1JRUGc1eCtsdFZnTDdqWkd3NndWQTFuUzFKdHJpOHlRYSsweHZ6UGZubTV1eEdJZm14NVZxbE1IUHZzRG1id2NVeENERzFlaFF3NzFNWHk0RlltbS8yNmc2aEtnYjJDcGZmY3pZWG0vU0RsU29ST005NDVpdVpYSWtNTURkM3M2RmVvZU8vUStwdUxFNk1TaVJTRDY1Z2FKcEd4QkxZMlpGeUlsUGl5UlNCVWhPNk5qR082T25lZlZ4NkIxY012MjRJaVVTKzFqdUZFMUVjc1VxVnA0UXFwSVFEbW1acE9KMWw1N0xzQWJlYUd6R200Q1VCdkJjUWpTbElrbFhlZ2ZBdnY2WnB1NHdHU2tBQTlQandzekR5SmJkbnVhU08vNWpLNjFuY1UyVUxuZWt2ZWotLTY3TU9jZklCcVR6ZXZQRy9UUCtHTmc9PQ%3D%3D--9bcb70f5196a063e7915b11622953f7935d9166c; _takvim_session=WVJmQVpEbEJUOE9KeVdLK3ZyODRpejI0dzA2aWJPd2dqOGRCaysxOU5VT3lhVkNnNzNIZytvYlpqL2FRZGhTWXZFcWxLc3JYVmoyUVRibGFuelpCczl4eFVjaFVLdkZiRURpUC84cysyUldFbC9VT295SURnMkpDQnFtdldLdUhHeDhRL3NGOG90WS9mWUI1WitocndBPT0tLVp6Mk1VS2VaT0hmMGtwcnhNcnpYMkE9PQ%3D%3D--a215e9c8f635c5c638ccdcd55105c3bdc452760e; SQLiteManager_currentLangue=2; request_method=GET; _Last_session=VnErWEFwazE3dWFBdm94WUVhMXdYWFhKVnViUmtQWUFja0xENjNDTmYxWVAxbjVyVDZrK3pxRlVjUnp0MGQ3R240UWZSK2lNcld5bDVKM2ZYb3JwMTJ1QXpPa0p1cFJOYXFXUllIakVrdnBzVHh2V09YQlZGTHNjTWtNLzFDOXNTdUhYZGNXei80enRwclZkdzBCUzZFcUtEQVFqeDFock15anMrVnVIUHRRPS0tci9lSEMvNFBtVWJ5eW1BSTQ0VUpadz09--46ddca06b8e604506dcfff84e7cc8111c7a1b679; _demo_session=TzE2bi93R2E3ZXVNSHdkZ0MvVnRCTm5BeG1VQ0luMVQrWFJ5a1FhbTc4amNCSGFNazJYTVhVYlRxbEhGejlnREowTTJDVFByYkoveHRpeEx6SlZvRnpaQ3R3UEdWaVRlK25UK29SQmx5Nmplbk9Gb1NNZ0pYdm9PQ3FLeTFKZ25CdkF4USt0clpGN1dMUkxrekxTM3lRPT0tLTZoQ1F4UHg3VExsa3JaMWRxQ1IvTFE9PQ%3D%3D--a430ecd15a69103694b06ec430875e21b66f5e62
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/events
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
X-CSRF-Token:GT/gFRykJMorJu4yPLmLwwGz1EZIwlVSp8XWeO1SOvIVYITeJLAPa1YcYkJOswrkXqMUUFb/jk/DP8JtvLhQYQ==
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
event_id:0
event:{"2015-05-06":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-07":{"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"},"2015-05-13":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-14":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-15":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-16":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-17":{"available":"1","bind":0,"info":"","notes":"","price":"35","promo":"","status":"available"},"2015-05-20":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-21":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-22":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-23":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-24":{"available":"","bind":0,"info":"","notes":"","price":"","promo":"","status":"booked"},"2015-05-28":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-29":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-30":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"},"2015-05-31":{"available":"1","bind":0,"info":"","notes":"","price":"25","promo":"","status":"available"}}
and Here is my database schema;
ActiveRecord::Schema.define(version: 20150502145455) do
create_table "events", force: :cascade do |t|
t.string "title"
t.text "description"
t.datetime "start_time"
t.datetime "end_time"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "status"
t.float "price"
t.float "promo"
t.integer "available"
t.text "info"
t.text "notes"
t.boolean "bind"
t.string "time"
t.string "p"
t.string "event_id"
end
end
EDIT 1:
Here is the Jquery request;
<script>
$(document).ready(function() {
$('#backend').DOPBackendBookingCalendarPRO({
'DataURL': '/events/load', #TO LOAD DATA
'SaveURL': '/events/save' #TO SAVE DATA
});
});
</script>
I have shared load.js.erb file as it is harcoded right now. But save.js.erb file is empty. When I created the url, rails asked me to define template. But #create action does not have a template,right?.
This calendar was written for php but I am trying to use it on RoR. The guy who wrote it, I do not know why, they defined 2 post urls one to retrieve data one to send data. Normally, one of them should be get, right?. That is why I created 2 post urls in routes.rb.Anyway. If you can help, I can send the calendar project I do not know how, but you see their backend.js file. Maybe I should change something there. Thank you
Here at the top of the backend.js file, I have ;
Schedule = {},
And there is this function in backend..js file to load data
parseCalendarData:function(){
$.post(DataURL, {event_id:ID}, function(data){
console.log(typeof data); //THIS RETURNS OBJECT
if(typeof data === 'object') {
Schedule = data;
}
else {
data = $.trim(data).replace(/\\/gi, '');
if (data != ''){
Schedule = JSON.parse(data);
}
}
methods.initCalendar();
});
},
Before save data, here is the code to set submitted data, probably the problem is there;
setData:function(){// Set submited data.
var y, m, d, noDays, key,
startDate, sYear, sMonth, sDay,
endDate, eYear, eMonth, eDay,
fromMonth, toMonth, fromDay, toDay,
availableValue = $('#DOPBCP_available').val(),
bindValue = 0,
infoValue = $('#DOPBCP_info').val().replace(/\n/gi, '<br />'),
notesValue = $('#DOPBCP_notes').val().replace(/\n/gi, '<br />'),
priceValue = $('#DOPBCP_price').val() != undefined ? $('#DOPBCP_price').val():'',
promoValue = $('#DOPBCP_promo').val() != undefined ? $('#DOPBCP_promo').val():'',
statusValue = $('#DOPBCP_status').val();
startDate = dayStartSelection < dayEndSelection ? dayStartSelection.split('_')[1]:dayEndSelection.split('_')[1];
endDate = dayStartSelection < dayEndSelection ? dayEndSelection.split('_')[1]:dayStartSelection.split('_')[1];
sYear = parseInt(startDate.split('-')[0], 10);
sMonth = parseInt(startDate.split('-')[1], 10);
sDay = parseInt(startDate.split('-')[2], 10);
eYear = parseInt(endDate.split('-')[0], 10);
eMonth = parseInt(endDate.split('-')[1], 10);
eDay = parseInt(endDate.split('-')[2], 10);
if (Schedule[methods.previousDay(startDate)] != undefined){
if (Schedule[methods.previousDay(startDate)]['bind'] == 1){
Schedule[methods.previousDay(startDate)]['bind'] = 0;
}
else if (Schedule[methods.previousDay(startDate)]['bind'] == 2){
Schedule[methods.previousDay(startDate)]['bind'] = 3;
}
}
if (Schedule[methods.nextDay(endDate)] != undefined){
if (Schedule[methods.nextDay(endDate)]['bind'] == 2){
Schedule[methods.nextDay(endDate)]['bind'] = 1;
}
else if (Schedule[methods.nextDay(endDate)]['bind'] == 3){
Schedule[methods.nextDay(endDate)]['bind'] = 0;
}
}
for (y=sYear; y<=eYear; y++){
fromMonth = 1;
if (y == sYear){
fromMonth = sMonth;
}
toMonth = 12;
if (y == eYear){
toMonth = eMonth;
}
for (m=fromMonth; m<=toMonth; m++){
noDays = new Date(y, m, 0).getDate();
fromDay = 1;
if (y == sYear && m == sMonth){
fromDay = sDay;
}
toDay = noDays;
if (y == eYear && m == eMonth){
toDay = eDay;
}
for (d=fromDay; d<=toDay; d++){
key = y+'-'+prototypes.timeLongItem(m)+'-'+prototypes.timeLongItem(d);
if ($('#DOPBCP_group').is(':checked')){
if (key == startDate){
bindValue = 1;
}
else if (key == endDate){
bindValue = 3;
}
else{
bindValue = 2;
}
}
//HERE IS THE PROBLEM I GUESS
Schedule[key] = {"available": availableValue,
"bind": bindValue,
"info": infoValue,
"notes": notesValue,
"price": priceValue,
"promo": promoValue,
"status": statusValue};
}
}
}
methods.saveData();
},
Lastly the save function in js file;
saveData:function(){// Save data.
var today = new Date(),
dd = prototypes.timeLongItem(today.getDate()),
mm = prototypes.timeLongItem(today.getMonth()+1),
yyyy = today.getFullYear();
for (var day in Schedule){
if (day < yyyy+'-'+mm+'-'+dd){
delete Schedule[day];
}
}
methods.hideForm();
methods.generateCalendar(StartYear, dayStartSelectionCurrMonth);
$.post(SaveURL, {event_id:ID, event:JSON.stringify(Schedule)}, function(data){});
},
PS: I have tried this in the events controller;
def save
respond_to do |format|
#event = Event.new(event_params)
#event.save
format.html
format.json { render :json => #event, :content_type => 'application/json' }
end
end
But content type did not change.
EDIT 2:
Sorry for giving you so much trouble but I am really trying to learn. I have changed $.post to $.ajaxand I changed the controller as you suggested. Now it try to post array and I am planing to iterate over the hash to get datas and save it. As you said I can then loop over params[:event] as it contains all the data, right?.Because of the multiple data it gives an nil error, that is why I would like to loop over them(I changed the #create as you said);
NoMethodError in EventsController#create
undefined method `new' for nil:NilClass
I think this is because Schedule; (key is the selected date)
Schedule[key] = {"date": key,
"available": availableValue,
"bind": bindValue,
"info": infoValue,
"notes": notesValue,
"price": priceValue,
"promo": promoValue,
"status": statusValue};
}
This is what comes from the Network tab;
Connection:Keep-Alive
Content-Length:94953
Content-Type:text/plain; charset=utf-8
Date:Sun, 03 May 2015 15:26:09 GMT
Server:WEBrick/1.3.1 (Ruby/2.2.1/2015-02-26)
X-Request-Id:1d59e6cd-726f-4eb0-afdf-92205c8a0974
X-Runtime:0.390420
Request Headers
view source
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
Connection:keep-alive
Content-Length:1687
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:_Paint_session=NXN5NVUvemhXcHF2UnF1ZlBXTHhtZVVWODlyVWFoL0tEWU9vWCtOYVp6ck9EUVF6OUs0WTJYV21yWW5VeVhqdndST2JUYTdCdnNnamNzZDJjQXFLNE1CYzlQT3dtcVJiRTJLcmlwaXR3aFdKZUZBVXN4VitWamMzaWdZUUtTQU1mcWhIRFg3SnJwQ2FBK1hmclZ3WmtiODRuTUpVRUVLKzYzQTNuUGxCTURYMHhKN3Z6eUZtbURLS2MybVlNejNoTmo5MVZteUQzcG8wTnB6WUFlR2pRK2UwSHFnUTVua0hUM0VzWitLUTdya1BXVVZ1eTVKUmNCR3pQaEh2djlpcFo3dFU1WmhZYlhSWS9wYTBVSHRTYXc9PS0tbDJHT3A3NVJ1Tm5OczVIREM2emNLQT09--f2703914b69129404c69d1d9dbb446fde16c6442; _Resim_session=cXQ5cEE5ZjFPNU1Jby9ZY0lKWis2TVY1NVlaN2dVZGtSaDdzc3B1QU9saS9yNXNUUHE5N2d1Ym1CZjcxYlNNZjAwbnhPNm9oeEN0aUpNUXZYMXM1Q2ZHWHJuZ3lhdjhxRmxteVR3ZXFvNHdxMFJZcXp6NWZMbk1qWVJyZG5GVFdBWVVtRkp5MHZsZWVNTzZ1aGs4ejAxUzFoZWE2VHVlWCtuWFBpclZnQU5GR2dzeUFZZFBWeEZaSCsxWUhHNmRkQVhwYk9uWW5oVjd4VVA5L2xvRzR3amt2RmE4VTdjUzRHRHQvRC80Rys0V0ZWQ2FCTW01cWtNQ2E2SHUwYWFFQ080VVJkUEduUWxpUjNaUkZldWZsOWc9PS0tcnM2M2UyVCttTEJBbW13SVJQN3RNQT09--3233372784be95cd2d6e2630f7e5e22c17eeff17; _Carrierwave_session=cE4vek43aGlxZ3BrSFNXWU1JaDZQekcxdlVVSnRzNFRMbGNXRGxjOGhNZ0hGNHRaSFpzODQ1YU95WXVnb1VKUlM3Y0xBVFBjYW1paG5FSTh5dVVzYm1LWXNHVXd2RGJnNktaZ0YxY1JtM25Rb1hLMkhUWm5XTElZS1JUejAxSmFvcnE3VzVXTVFoYmdPbTczOE02Wjk4N2hsaTJDRFdLY2pRc1NxYVRNVFBHdkFHbmEvb1U4aEN4T2FOVDZWZGlUMnpJMU0yNkdHNW1acVpYN3NzRkxwQkN2TzRzS0ZBNlMwMGtIMGJ5bWN2QVp5Q3cxQUNIVnExajFDSldsZWhJek1zUjJxVzJyRHRsUDBjQnJsdlB1RFE9PS0tSjViSGdocSs5blRLdTNnUk1GWk9qZz09--068ded1e78c2d70739361e662b995b5470a059c4; _raddit_session=Vy9USHZBa1FodGxON1BMOWFZOHBIazk3eWVSOXh0OW9yUjRmSjJ5Tmg1OXpsMnI2Tm5ZTGQwOHdEMVJnUWhFNG5jRVZEcVhLL3ZCSVdsM1g5S2FTMjYvZWo4U1ovT0xNdkZVT2dJS0VWTkRMcXdRQ0lzTlFRWC9EZ1ZxbDRtYmtLQ1dkZzM3THltSEFvdzJTN010MHVnYytJMzE1R2F0cUVkQlh2bERBRUM4c0NVNnFsTFdmbVB1cURJeDVHUkhKOWZUOG5pUlhFZkxOSkJ3c01uU2paTW50WXRrRW8zRmJtTTBrUm5GWlJvbz0tLUh4ckZqdnA3WGQzRjdmNnAzMXdMcmc9PQ%3D%3D--622d3f9adb9afb871e118d0715921aaf986f82d2; _Cal_session=cjRlSlc0Q2FITHJJTmlTbU5TZjk5aFNFaTczTHRQZW9TR0h1MG4xYVovZG9xaUxyNittWENjbXdib3FLc1J6cXh3dHA5YitaVkZYbFVtaFI2bGxUKzJyM1kvRzJlRFV4b0JibzJ1TTdQS0ZkdVE2eVJJSlZQVXY0Q0thS1NBRzhGUzlaQ1ZRaHppYzJES2V2eXRmVWtBPT0tLWEzVWFIcWl0WnJBRVdnanJ0em1Renc9PQ%3D%3D--03a65bd6c5338108d2d3db62295843f8b3e3eaaa; _fullcalendar_and_rails_example_session=M1h0eFJieVY1ek16OWRtR1JRUGc1eCtsdFZnTDdqWkd3NndWQTFuUzFKdHJpOHlRYSsweHZ6UGZubTV1eEdJZm14NVZxbE1IUHZzRG1id2NVeENERzFlaFF3NzFNWHk0RlltbS8yNmc2aEtnYjJDcGZmY3pZWG0vU0RsU29ST005NDVpdVpYSWtNTURkM3M2RmVvZU8vUStwdUxFNk1TaVJTRDY1Z2FKcEd4QkxZMlpGeUlsUGl5UlNCVWhPNk5qR082T25lZlZ4NkIxY012MjRJaVVTKzFqdUZFMUVjc1VxVnA0UXFwSVFEbW1acE9KMWw1N0xzQWJlYUd6R200Q1VCdkJjUWpTbElrbFhlZ2ZBdnY2WnB1NHdHU2tBQTlQandzekR5SmJkbnVhU08vNWpLNjFuY1UyVUxuZWt2ZWotLTY3TU9jZklCcVR6ZXZQRy9UUCtHTmc9PQ%3D%3D--9bcb70f5196a063e7915b11622953f7935d9166c; _takvim_session=WVJmQVpEbEJUOE9KeVdLK3ZyODRpejI0dzA2aWJPd2dqOGRCaysxOU5VT3lhVkNnNzNIZytvYlpqL2FRZGhTWXZFcWxLc3JYVmoyUVRibGFuelpCczl4eFVjaFVLdkZiRURpUC84cysyUldFbC9VT295SURnMkpDQnFtdldLdUhHeDhRL3NGOG90WS9mWUI1WitocndBPT0tLVp6Mk1VS2VaT0hmMGtwcnhNcnpYMkE9PQ%3D%3D--a215e9c8f635c5c638ccdcd55105c3bdc452760e; SQLiteManager_currentLangue=2; request_method=GET; _Last_session=VnErWEFwazE3dWFBdm94WUVhMXdYWFhKVnViUmtQWUFja0xENjNDTmYxWVAxbjVyVDZrK3pxRlVjUnp0MGQ3R240UWZSK2lNcld5bDVKM2ZYb3JwMTJ1QXpPa0p1cFJOYXFXUllIakVrdnBzVHh2V09YQlZGTHNjTWtNLzFDOXNTdUhYZGNXei80enRwclZkdzBCUzZFcUtEQVFqeDFock15anMrVnVIUHRRPS0tci9lSEMvNFBtVWJ5eW1BSTQ0VUpadz09--46ddca06b8e604506dcfff84e7cc8111c7a1b679; _demo_session=R1dIMnpjMU1BTkszczFzZTR2Zmk3cFMyUVU2Yk12eEwyZ2poR2RWUzhQWEtPbEM5UkMrQXRJb21oc1grWkFNNlpVM2VwMElvMnI1YUN2UlFVeXR2KytqYzJyN3AxeS9lM3gxVlNhLysxQzNLMklQOGszdUZBaEREMGQwZVMzc09BNFVndjRZaGQzY25KZGwrR0wyME5nPT0tLUEreS9acGZTWUhzdXdOc0hrVW5WYVE9PQ%3D%3D--9a636d832705858099e968c44c959b12980b6e99
Host:localhost:3000
Origin:http://localhost:3000
Referer:http://localhost:3000/events
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36
X-CSRF-Token:BaHKI75O/nhl2kbiQDxSvJeZHiUAlTttTPGd0b/usf4J/q7ohlrV2RjgypIyNtObyIneMx6o4HAoC4nE7gTbbQ==
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
event[2015-05-06][available]:1
event[2015-05-06][bind]:0
event[2015-05-06][info]:
event[2015-05-06][notes]:
event[2015-05-06][price]:20
event[2015-05-06][promo]:
event[2015-05-06][status]:available
event[2015-05-07][available]:1
event[2015-05-07][bind]:0
event[2015-05-07][info]:
event[2015-05-07][notes]:
event[2015-05-07][price]:20
event[2015-05-07][promo]:
event[2015-05-07][status]:available
event[2015-05-20][date]:2015-05-20
event[2015-05-20][available]:1
event[2015-05-20][bind]:0
event[2015-05-20][info]:
event[2015-05-20][notes]:
event[2015-05-20][price]:
event[2015-05-20][promo]:
event[2015-05-20][status]:available
event[2015-05-21][date]:2015-05-21
event[2015-05-21][available]:1
event[2015-05-21][bind]:0
event[2015-05-21][info]:
event[2015-05-21][notes]:
event[2015-05-21][price]:
event[2015-05-21][promo]:
event[2015-05-21][status]:available
event[2015-05-22][date]:2015-05-22
event[2015-05-22][available]:1
event[2015-05-22][bind]:0
event[2015-05-22][info]:
event[2015-05-22][notes]:
event[2015-05-22][price]:
event[2015-05-22][promo]:
event[2015-05-22][status]:available
event[2015-05-23][date]:2015-05-23
event[2015-05-23][available]:1
event[2015-05-23][bind]:0
event[2015-05-23][info]:
event[2015-05-23][notes]:
event[2015-05-23][price]:
event[2015-05-23][promo]:
event[2015-05-23][status]:available
EDIT 3:
h = {"event"=>{"2015-05-06"=>{"available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"20", "promo"=>"", "status"=>"available"}, "2015-05-07"=>{"available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"20", "promo"=>"", "status"=>"available"}, "2015-05-18"=>{"date"=>"2015-05-18", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-19"=>{"date"=>"2015-05-19", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-20"=>{"date"=>"2015-05-20", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-21"=>{"date"=>"2015-05-21", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-22"=>{"date"=>"2015-05-22", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}, "2015-05-23"=>{"date"=>"2015-05-23", "available"=>"1", "bind"=>"0", "info"=>"", "notes"=>"", "price"=>"30", "promo"=>"", "status"=>"available"}}}
h.each do |key, value|
puts key
value.each do |key2, value2|
puts key2
value2.each do |k, v|
puts k
puts v
end
end
end
Something like the code works fine to get the key and values, however I do not know if that works if I put it to controller.Then I should save it to database. I surely think there must be a easier way. But I am dependent on the calendar js code that the person wrote. Sorry again asking too much. If you can guide me I appreciate. Thank you again
In my controller #create action I am able to iterate over key and values;
Now I have to figure out how to save them
def create
h = params[:event]
h.each do |key, value|
puts key
value.each do |key2, value2|
puts key2
puts value2
end
end
end
You haven't detailed how you are actually sending the JSON request but two things are going wrong:
Your save action expects a hash with the key event with:
{
event: {
title: "foo"
# more attributes ...
}
}
But you're trying to send the parameters for several dates at the same time.
event:{
"2015-05-06": {"available":"1","bind":0,"info":"","notes":"","price":"20","promo":"","status":"available"}
#... more events
}
Also you sending the request with the wrong `Content-Type
Your request is sent with:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Not:
Content-Type: application/json; charset=utf-8;
differences in application/json and application/x-www-form-urlencoded
Added in response to edit of the question:
Use jQuery.ajax instead of jQuery.post and it will stringify the data for you - that way jQuery will take care of browsers which don't have native JSON support.
$.ajax(SaveURL, {
method: 'POST',
data: { event: Schedule },
dataType: 'json'
});
Now that you are sending the correct request type jQuery will merge the post data into params.
But this still doesn't fix the issue that Schedule contains the attributes for multiple Events. I would start by creating a simple route which accepts the parameters for a single event. In Rails conventions we call that action create not save.
class EventsController
# ...
# POST /events
def create
#event.new(params[:event])
if (#event.save)
render json: #event, status: :created
else
# ... what do we do if validation fails?
end
end
# ...
private
def create_params
params.permit(:event).allow(:available, :bind, :info, :notes, :price, :promo, :status)
end
end
You can generate a full set of restful routes for events by adding this to your config/routes.rb:
resources :events
which generates the following routes:
Prefix Verb URI Pattern Controller#Action
events GET /events(.:format) events#index
POST /events(.:format) events#create
new_event GET /events/new(.:format) events#new
edit_event GET /events/:id/edit(.:format) events#edit
event GET /events/:id(.:format) events#show
PATCH /events/:id(.:format) events#update
PUT /events/:id(.:format) events#update
DELETE /events/:id(.:format) events#destroy
At your skill level I would not bother trying to create a controller action which creates several Events at once, and I'm not going to instruct how to do it here since it would be really lengthy.

how to use the bitbucket API with ruby and access token

I am trying to use the bitbucket API. I have successfully got the flow working where I am able to retrieve the access token and access token secret. After that, I have not been able to get anything to work. I can't find any example on to get this to work with Ruby. The closest I think I've found is this link:
https://gist.github.com/erikeldridge/383159
However in this example, he doesn't add the user's token and token secret, so I've updated it, here's his utility code:
# A utility for signing an url using OAuth in a way that's convenient for debugging
# Note: the standard Ruby OAuth lib is here http://github.com/mojodna/oauth
# License: http://gist.github.com/375593
# Usage: see example.rb below
require 'uri'
require 'cgi'
require 'openssl'
require 'base64'
class OauthUtil
attr_accessor :consumer_key, :consumer_secret, :token, :token_secret, :req_method,
:sig_method, :oauth_version, :callback_url, :params, :req_url, :base_str
def initialize
#consumer_key = ''
#consumer_secret = ''
#token = ''
#token_secret = ''
#req_method = 'GET'
#sig_method = 'HMAC-SHA1'
#oauth_version = '1.0'
#callback_url = ''
end
# openssl::random_bytes returns non-word chars, which need to be removed. using alt method to get length
# ref http://snippets.dzone.com/posts/show/491
def nonce
Array.new( 5 ) { rand(256) }.pack('C*').unpack('H*').first
end
def percent_encode( string )
# ref http://snippets.dzone.com/posts/show/1260
return URI.escape( string, Regexp.new("[^# {URI::PATTERN::UNRESERVED}]") ).gsub('*', '%2A')
end
# #ref http://oauth.net/core/1.0/#rfc.section.9.2
def signature
key = percent_encode( #consumer_secret ) + '&' + percent_encode( #token_secret )
# ref: http://blog.nathanielbibler.com/post/63031273/openssl-hmac-vs-ruby-hmac-benchmarks
digest = OpenSSL::Digest::Digest.new( 'sha1' )
hmac = OpenSSL::HMAC.digest( digest, key, #base_str )
# ref http://groups.google.com/group/oauth-ruby/browse_thread/thread/9110ed8c8f3cae81
Base64.encode64( hmac ).chomp.gsub( /\n/, '' )
end
# sort (very important as it affects the signature), concat, and percent encode
# #ref http://oauth.net/core/1.0/#rfc.section.9.1.1
# #ref http://oauth.net/core/1.0/#9.2.1
# #ref http://oauth.net/core/1.0/#rfc.section.A.5.1
def query_string
pairs = []
#params.sort.each { | key, val |
pairs.push( "#{ percent_encode( key ) }=#{ percent_encode( val.to_s ) }" )
}
pairs.join '&'
end
# organize params & create signature
def sign( parsed_url )
#params = {
'oauth_consumer_key' => #consumer_key,
'oauth_nonce' => nonce,
'oauth_signature_method' => #sig_method,
'oauth_timestamp' => Time.now.to_i.to_s,
'oauth_version' => #oauth_version
}
# if url has query, merge key/values into params obj overwriting defaults
if parsed_url.query
#params.merge! CGI.parse( parsed_url.query )
end
# #ref http://oauth.net/core/1.0/#rfc.section.9.1.2
#req_url = parsed_url.scheme + '://' + parsed_url.host + parsed_url.path
# create base str. make it an object attr for ez debugging
# ref http://oauth.net/core/1.0/#anchor14
#base_str = [
#req_method,
percent_encode( req_url ),
# normalization is just x-www-form-urlencoded
percent_encode( query_string )
].join( '&' )
# add signature
#params[ 'oauth_signature' ] = signature
return self
end
end
and here's my modified code:
require 'oauth_util.rb'
require 'net/http'
o = OauthUtil.new
o.consumer_key = MY_CONSUMER_KEY
o.consumer_secret = MY_SECRET
o.token = ACCESS_TOKEN_RETURNED_FROM_BB
o.token_secret = ACCESS_TOKEN_SECRET_RETURNED_FROM_BB
url = 'https://bitbucket.org/api/1.0/user'
parsed_url = URI.parse( url )
Net::HTTP.start( parsed_url.host ) { | http |
req = Net::HTTP::Get.new "#{ parsed_url.path }?#{ o.sign(parsed_url).query_string }"
response = http.request(req)
print response.read_body
}
Sadly, all I get is
301 Moved Permanently
301 Moved Permanently
nginx/1.5.10
Anyone have any luck using the BB API in Ruby after getting an access token back? Thanks for any help,
Kevin
EDIT:
There is a bitbucket API wrapper gem that has authentication built-in.
ORIGINAL:
I'm wondering if the "301 moved permanently" error is caused by the code making an http request instead of https.
without ssl:
result = Net::HTTP.get(URI.parse('http://bitbucket.org/api/1.0/user'))
# this returns 301 Moved Permanently
But when I used ssl instead (without the oauth headers/params) I got 401 Unauthorized.
with ssl:
1.9.3-p194 :063 > uri = URI.parse('https://bitbucket.org/api/1.0/user')
=> #<URI::HTTPS:0x007f846c5822d8 URL:https://bitbucket.org/api/1.0/user>
1.9.3-p194 :064 > http = Net::HTTP.new(uri.host, uri.port)
=> #<Net::HTTP bitbucket.org:443 open=false>
1.9.3-p194 :065 > http.use_ssl = true
=> true
1.9.3-p194 :066 > request = Net::HTTP::Get.new(uri.request_uri)
=> #<Net::HTTP::Get GET>
1.9.3-p194 :067 > response = http.request(request)
=> #<Net::HTTPUnauthorized 401 UNAUTHORIZED readbody=true>

Rails signature does not match amazon s3

I had uploads to Amazon s3 working with AngularJS and NodeJS but now am using Rails as the backend. So I figured all I'd have to do is translade NodeJS code to Rails. Source: https://github.com/nukulb/s3-angular-file-upload/blob/master/lib/controllers/aws.js
and my conversion:
def aws_signature
mime_type = "image/jpeg"
expiration = Date.new(Time.now.year + 1, 01, 01) #Time.now.utc.strftime('%Y/%m/%d %H:%M:%S+00:00')
s3_policy = {
expiration: expiration,
conditions: [
['starts-with', '$key', '/'],
{bucket: ENV["BUCKET"] },
{acl: 'public-read'},
['starts-with', '$Content-Type', mime_type],
{success_action_status: '201'}
]
}
puts s3_policy.inspect
string_policy = s3_policy.to_json
puts string_policy.inspect
base64_policy = URI.escape(Base64.encode64(string_policy).strip)
puts base64_policy.inspect
digest = OpenSSL::Digest::Digest.new('sha1')
signature = OpenSSL::HMAC.digest(digest, ENV["S3_SECRET"], base64_policy)
puts signature.inspect
s3_credentials = {
s3Policy: base64_policy,
s3Signature: signature,
AWSAccessKeyId: ENV["S3_KEY"]
}
render json: s3_credentials
end
Now I am getting a 304 response from Amazon with SignatureDoesNotMatch in xml.
Did I miss something in the conversion to rails code?
Is there a way to compare the unencrypted params received in amazon?

Resources