How to make a post request with httparty [duplicate] - ruby-on-rails

I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.

I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}

Related

Creating "shell object" to submit form params via Change.org API

I am using the change-ruby gem to take form params and submit them via the Change.org API. I am new to Rails and so I am likely not fully understanding how to properly implement this library and use it in my controller.
I have a form that posts some params to the #sign action in ChangeController. In this controller I attempt to include the change-ruby gem, as well as its resources.
Currently, though, when I submit the form I am given the error: uninitialized constant Petitions::ChangeController::Petition on the line where I attempt to create a new Petition object (petition = Petition.new(client)). What am I missing?
To be clear, my app uses Engines and this one happens to be called Petitions.
ChangeController code:
# Visit https://github.com/ericisaiah/change-ruby for documentation
require 'change-ruby'
module Petitions
include Change::Resources
class ChangeController < ApplicationController
def sign
client = Change::Requests::Client.new({ :api_key => ENV["CHANGE_API_KEY"], :secret_token => ENV["CHANGE_SECRET"] })
# Get the petition (this is where the error occurs)
petition = Petition.new(client)
# Get the petition id from the Petition URL
petition_id = petition.get_id(params[:petition_url][:value])
# Load the petition
petition.load(petition_id)
# Get the petition auth key
petition.request_auth_key({
:requester_email => params[:requester_email][:value],
:source => params[:page_slug][:value],
:source_description => "Campaign page that is gathering signatures to help the petition."
})
# Submit signature
petition.signatures.add_signature({
:email => params[:sig_email],
:first_name => params[:sig_first],
:last_name => params[:sig_last],
:address => params[:sig_street],
:city => params[:sig_city],
:state_province => params[:sig_state],
:postal_code => params[:sig_zip],
:country_code => params[:sig_country],
:hidden => params[:sig_hidden]
})
end
end
end
Answer was simple: the include Change::Resources line needed to be inside the ChangeController class, otherwise it wasn't accessible to the controller.

Google + moments not visible on user's feed using google_api_client gem

I am trying to post to user's stream using google api client, I am using below mentioned code
require 'google/api_client'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
client = Google::APIClient.new
client.authorization.client_id = CLIENT_ID
client.authorization.client_secret = CLIENT_SECRET
client.authorization.access_token = USER_ACCESS_TOKEN
plus = client.discovered_api('plus', 'v1')
moment = {
:type => 'http://schemas.google.com/AddActivity',
:target => { :id => Time.now.to_i.to_s,
:description => 'well this is it',
:name => 'Well this is it'
}
}
req_opts = { :api_method => plus.moments.insert,
:parameters => { :collection => 'vault', :userId => 'me', },
:body_object => moment
}
response = client.execute!(req_opts).body
After executing the above code I am getting the response as follow
{"kind"=>"plus#moment",
"type"=>"http://schemas.google.com/AddActivity",
"target"=>{"kind"=>"plus#itemScope", "id"=>"1422863753", "description"=>"well this is it", "name"=>"Well this is it"}}
But when I go to user's profile then I am not able to see this activity anywhere in profile.
Note: The moment methods do not write directly to a user's Google+ stream. They instead write to a user's profile, and are not necessarily viewable by others depending on the user's preferred sharing settings.
Manage app activities in Google
To find where moments are visible, view the profile about page and look for the "Apps with Google+ Sign-in" section.

How to use Rails detect in Rails on incoming Params

So recently I was helped out finding a way of using detect in rails to grab a url from text... however that would come very useful for me also in a controller if its possible.
My controller grabs some info and created a new entry into the DB based on incoming params, looks something like this;
#received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new')
Now, I was hoping that using detect in my controller on the create action, I could search the :content for specific text or symbol and allow my users to define few things in content but I would assign that to a different column. I'm sure this isn't clear so let me show by example.
EXAMPLE:
Let's say my user send a message with content like so;
"Hey there, you should check this type of website out and make sure that its good to go"
Now, I'm assigning a USER_ID for the user that submitted this message, but the original owner could be someone else before the user submitted it. So I thought I would allow my user_id to enter #John into their message, meaning the original owner of the message was JOHN.. the new message would look something like this;
"Hey there, you should check this type of website out and make sure that its good to go #John"
Now in my controller when that message is created as a record, I'd like to take JOHN and assign it to the column username for example; I thought something like this would work but its giving me error .detect undefined..
#received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => (params[:Text].detect {|original_sender| original_sender.start_with? "#"))
Maybe too many brackets?
you are missing } at the end
#received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => (params[:Text].detect {|original_sender| original_sender.start_with? "#"}))
you can also use the below for what you want
#received_msg = Message.create(:content => params[:Text], :user_id => user.id, :status => 'new', :username => params[:Text].split.find{|w| w.start_with?("#")})

Check username availability using jquery and Ajax in rails

I am using rails with jquery and ajax to check the availability of username. I am using
the following plugin for jquery validation purpose.
https://github.com/posabsolute/jQuery-Validation-Engine
In my controller i am using the following method to check the username availability.
def check_name
name = params[:name]
if name.strip == ""
render :json => { :available => false }
return
end
user = User.find(:first, :conditions => [ "name = ?", name])
if user
render :json => ["name", false , "This name is already taken"]
else
render :json => ["name", true , ""]
end
end
Is this the correct way to write the method? I checked many of the username availability
posts in this forum, but nothing worked out.
I am adding the answer. Sorry for the delay guys.
First credit to the plugin:https://github.com/posabsolute/jQuery-Validation-Engine .
Used the plugin for validations in the application.
In the view, i had
<%= f.username_field :username, :id => 'free-user', :placeholder=>'User Name', :class => "validate[required, ajax[ajaxUserCall]]", "data-prompt-position" => "topLeft:0,9"%>
In the same view, in java script:
<script type="text/javascript">
$(document).ready(function(){
$("#free-user").bind("jqv.field.result", function(event, field, errorFound, prompText){
if(errorFound){
$(".continue").attr("disabled", false); // .continue is a button
} else{
$(".continue").attr("disabled", true);
}
})
});
</script>
In routes.rb i have the following route.
match '/check-user' =>"users#check_user" // creating route for ajax call
In jquery.validationEngine-en.js file i have following:
"ajaxUserCall": {
"url": "/check-user",
// you may want to pass extra data on the ajax call
"alertText": "* This user is already taken",
"alertTextLoad": "* Validating, please wait"
},
In users controller, i have the following method
def check_user
user = params[:fieldValue]
user = User.where("username = ?", username).first
if user.present?
render :json => ["free-user", false , "This User is already taken"]
else
render :json => ["free-user", true , ""]
end
end
To check the Username/Email Availability do the following:
Using the https://github.com/posabsolute/jQuery-Validation-Engine
edit the validationsEngines-en.js file for the AJAX calls, one for the email will look like the following:
"ajaxEmailAvailable": {
"url": "/route_to_send_the_parameters",
// you may want to pass extra data on the ajax call
"alertTextOk": "* This email is available",
"alertText": "* This email is already taken",
"alertTextLoad": "* Validating, please wait"
},
Make sure you configure your routes.rb file to match the route you want to use, the default action with the call is a GET HTTP Request.
Next set up the proper action in your controller to handle the request (I included a helper in the Application Controller so that the input value can be sanitized before queried in the database:
CONTROLLER HANDLING THE REQUEST
def username_availability
scrubb = help.sanitize(params[:fieldValue], :tags => '')
user = User.find_by_email(scrubb)
if user.blank?
render :json => ["INPUT_ID", true , ""]
else
render :json => ["INPUT_ID", false , "This email is already taken"]
end
end
If you are unsure of the proper INPUT ID, watch the server logs for the parameters passed during the call and do a simple copy-paste. By default the request passes the INPUT ID and INPUT VALUE.
To gain access to this helper add the following:
APPLICATION CONTROLLER
def help
Helper.instance
end
class Helper
include Singleton
include ActionView::Helpers::TextHelper
end
Now on the form itself, your input should read as the following:
<%= c.text_field :email, "data-validation-engine"=>"validate[required, custom[email], ajax[ajaxEmailAvailable]]" %>
As per the proper functionality always place the AJAX call as the last validation.
Don't forget to include jquery.js, jquery.validationEngine-en.js, jquery.validationEngine.js and validationEngine.jquery.css in the head of the document [in that order of js] and to call a
<script type="text/javascript">$(function() {$("#FORM_ID").validationEngine();});</script>
If you want to do this for username, just edit the above appropriately.

POST JSON to API using Rails and HTTParty

I would like for a user within my ruby on rails app to be able to submit a ticket to my external ticket management system, squishlist.com. They have an api and instructions as follows. You need to authenticate and get a token and then submit the ticket with the token. From squishlist.
# get the token
https://api.squishlist.com/auth/?cfg=testcorp&user_key=privatekey&api_key=TEST-KEY-12345
=> {"token": "authtoken",
"expires": "2010-06-16 13:31:56"}
# and then the ticket with the token
https://api.squishlist.com/rest/?cfg=testcorp&token=authtoken&method=squish.issue.submit&prj=demo
POST data: {'issue_type': 1, 'subject': 'Hello, world.', 4: 'Open', 5: 10}
For testing purposes, I created a controller, route and view (page) for testing. On my controller I have the following
require 'httparty'
require 'json'
class SubmitticketController < ApplicationController
def submit_a_ticket
#cfg = 'xxxsupport'
#user_key = '4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b'
#api_key = 'MrUser411'
#project = 'excelm-manoke'
#url_new_string = 'https://api.squishlist.com/auth/?cfg='+#cfg+'&user_key='+#user_key+'&api_key='+#api_key
# https://api.squishlist.com/auth/?cfg=xxxsupport&user_key=4787fsdbbfbfsdbhbfad5aba91129a3f1ed1b743321f7b&api_key=MrUser411 - this is what is created by #url_new_string
response = HTTParty.get(#url_new_string.to_str) #submit the string to get the token
#parsed_and_a_hash = JSON.parse(response)
#token = #parsed_and_a_hash["token"]
#make a new string with the token
#urlstring_to_post = 'https://api.squishlist.com/rest/?cfg='+#cfg+'&token='+#token+'&method=squish.issue.submit&prj='+#project
#submit and get a result
#result = HTTParty.post(#urlstring_to_post.to_str, :body => {:subject => 'This is the screen name', :issue_type => 'Application Problem', :status => 'Open', :priority => 'Normal', :description => 'This is the description for the problem'})
end
end
And then I have a page that I go to to see the result of the controllers actions and it has the following code.
<p><%= #result %></p>
I know that it is working in general because of responses I have received along the way. My json is different from the example because of fields I have defined in squishlist. Can anyone help me out on this issue?
I guess the real problem is that I can't really see what the json looks like and if it is even close to match. I really don't know much about json. Should I be using something that might be easy. Should I be using ajax to submit this. Any help is greatly appreciated. I love the community here.
I solved this by adding .to_json and some heading information
#result = HTTParty.post(#urlstring_to_post.to_str,
:body => { :subject => 'This is the screen name',
:issue_type => 'Application Problem',
:status => 'Open',
:priority => 'Normal',
:description => 'This is the description for the problem'
}.to_json,
:headers => { 'Content-Type' => 'application/json' } )
The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)
query_string_normalizer: ->(query){query.to_json}

Resources