Undefined method `escape' for URI:Module - ruby-on-rails

I'm a noob studying Ruby on Rails. I am trying to integrate my ruby on rails app to Quickbooks. I'm following the steps of this video. And I am stuck when I try to authenticate by pressing the "Connect to QuickBooks" button.
I get this error;
I did a little research and found out that this error was about the URI.escape() command. I think they removed it in Ruby 3. How can I resolve this issue? I can't even figure out where this URI.escape() command is located.
This is from vendors_controller.rb
def authenticate
callback = oauth_callback_vendors_url
token = $qb_oauth_consumer.get_request_token(:oauth_callback => callback)
session[:qb_request_token] = token
# If Rails >= 4.1 you need to do this => session[:qb_request_token] = Marshal.dump(token)
redirect_to("https://appcenter.intuit.com/Connect/Begin?oauth_token=#{token.token}") and return
end
def oauth_callback
at = session[:qb_request_token].get_access_token(:oauth_verifier => params[:oauth_verifier])
# If Rails >= 4.1 you need to do this => at = Marshal.load(session[:qb_request_token]).get_access_token(:oauth_verifier => params[:oauth_verifier])
session[:token] = at.token
session[:secret] = at.secret
session[:realm_id] = params['realmId']
redirect_to root_url, notice: "Your QuickBooks account has been successfully linked."
end
My initializer quickbooks.rb
QB_KEY = "I PASTED MY CLIENT ID KEY HERE"
QB_SECRET = "I PASTED MY CLIENT SECRET HERE"
$qb_oauth_consumer = OAuth::Consumer.new(QB_KEY, QB_SECRET, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_url => "https://appcenter.intuit.com/Connect/Begin",
:access_token_path => "/oauth/v1/get_access_token"
})
My rails version Rails 6.1.4
My ruby version ruby 3.0.1p64
Thank you for your time.

I know many people say that URI.escape wasn't good, but it was good enough for me when all I wanted from it is to escape urls with non-English characters.
So I just monkey patched it
Add the following under /config/initializers/functions_overrides.rb
(the file name can be anything you want)
require 'uri'
module URI
class << self
def escape(str)
alpha = "a-zA-Z"
alnum = "#{alpha}\\d"
unreserved = "\\-_.!~*'()#{alnum}"
reserved = ";/?:#&=+$,\\[\\]"
unsafe = Regexp.new("[^#{unreserved}#{reserved}]")
str.gsub(unsafe) do
us = $&
tmp = ''
us.each_byte do |uc|
tmp << sprintf('%%%02X', uc)
end
tmp
end.force_encoding(Encoding::US_ASCII)
end
end
end

Use the https://developer.intuit.com/app/developer/qbo/docs/develop/sdks-and-samples-collections/ruby
OAuth Ruby Client
Intuit offers an OAuth 2.0 Client which provides a set of methods that make it easier to work with Intuit’s OAuth and OpenID implementation.
Community Supported Ruby SDK
The Community Supported Ruby SDK makes it easy to integrate your web app with the QuickBooks Online API. This guide assumes that you have an existing web app that you want to integrate with QuickBooks Online.

URI#escape was deprecated and later removed - https://github.com/ruby/uri/commit/61c6a47ebf1f2726b60a2bbd70964d64e14b1f98
From the commit :
# This method is obsolete and should not be used. Instead, use
# CGI.escape, URI.encode_www_form or URI.encode_www_form_component
# depending on your specific use case.
Ruby 3.0.0 onwards URI#escape does not work.
Use CGI.escape or URI.encode_www_form as mentioned in the deprecation warning

Related

How to integrate SoundCloud in Ruby on Rails?

I am new to RubyOnRails and SoundCloud.
I want to integrate SoundCloud API in my ruby on rails application.
For this I have registered on SoundCloud And I got the ClientID and ClientSecret. Also I have downloaded the SDK.
Now I have copied the files and folders from lib and spec directory to my applications lib and spec directory. Also I have added gem 'soundcloud' in the Gemfile.
After this I made simple code (copied from doc) in My Interactor:
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => YOUR_CLIENT_ID)
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
But here I'm getting the error -
uninitialized constant MyApp::Interactors::MyInteractor::MyAction::SoundCloud
I followed the steps from APIDoc. Is there any step by step example for integrating SoundCloud in Ruby on Rails so that I can follow?
How can I resolve this error?
MyInteracor.rb
module MyApp
module Interactors
module MyInteractor
class MyAction < Struct.new(:user, :params)
def run
# SoundCloud
# register a client with YOUR_CLIENT_ID as client_id_
client = SoundCloud.new(:client_id => 'my-client-id')
# get 10 hottest tracks
tracks = client.get('/tracks', :limit => 10, :order => 'hotness')
# print each link
tracks.each do |track|
puts track.permalink_url
end
end
end
end
end
end
There's a typo in the soundcloud github page change the line:
client = SoundCloud.new(:client_id => 'my-client-id')
to
client = Soundcloud.new(:client_id => 'my-client-id')
[notice the lowercase c in Soundcloud]
Also you are going to need your client secret for SoundCloud's API to verify you.
Perhaps put client method and in it have client = SoundCloud.new(your-client-id,your-secret-key-your-redirect-uri) in a controller or helper with your client_id, client_secret, and redirect uri values protected in a .env file.
I think by leaving out your redirect_uri and client secret you might be getting this error in MyInteractor.rb
Hope this helps

"Missing authorization code" error when trying to use Google Calendar API

The following is the code I am using to allow users to allow users to authorise my app to access their Google Calendar via OAuth. I based it off this sample code.
It works most of the time, but sometimes, there is an ArgumentError: Missing authorization code error on the client.authorization.fetch_access_token! line in the create_google_calendar action in the services controller. If I comment out that line, all of the client.authorization attributes are null.
I am using Rails 3.2.0 and Ruby 1.9.2.
What is causing this?
Gemfile
gem 'google-api-client', :require => 'google/api_client'
service.rb
def self.google_calendar_client google_calendar_service=nil
client = Google::APIClient.new
client.authorization.client_id = xxx
client.authorization.client_secret = xxx
client.authorization.scope = 'https://www.googleapis.com/auth/calendar'
url_prefix = Rails.env.production? ? xxx : 'http://localhost:3000'
client.authorization.redirect_uri = "#{url_prefix}/create_google_calendar"
if google_calendar_service.present?
client.authorization.update_token! :access_token => google_calendar_service.token, :refresh_token => google_calendar_service.google_calendar_refresh_token, :expires_in => google_calendar_service.google_calendar_expires_in, :issued_at => Time.at(google_calendar_service.google_calendar_issued_at)
client.authorization.fetch_access_token! if client.authorization.expired?
end
client
end
services_controller.rb
def connect_google_calendar
#google_calendar_url = Service.google_calendar_client.authorization.authorization_uri.to_s
end
def create_google_calendar
client = Service.google_calendar_client
client.authorization.code = params[:code]
client.authorization.fetch_access_token!
current_user.services.create :provider => 'google_calendar', :token => client.authorization.access_token, :google_calendar_refresh_token => client.authorization.refresh_token, :google_calendar_expires_in => client.authorization.expires_in, :google_calendar_issued_at => client.authorization.issued_at
end
The truth is, I don't know. Your code looks right to me. But I can at least tell you what the error means. Missing authorization code means that it thinks you're trying to do an "authorization code" grant type when you fetch the access token. If you're actually trying to obtain an access token off a refresh token as opposed to doing it on the first pass after obtaining authorization from the user, then you may not have correctly set up the authorization object.
You can check this by inspecting the client.authorization.grant_type value. In very recent versions of the client you can manually set the grant_type value to force a particular mode, which may give you more informative error messages, depending on what the actual issue is.

instagram-ruby-gem undefined method `query_values'

Hi there i have been working on a project that graps the users instagram photos and let them to download it. To authenticate i use the gem called instagram-ruby-gem
which is an offical ruby gem for instagram
def instagram_callback
response = Instagram.get_access_token(params[:code], :redirect_uri => "http://0.0.0.0:3000/oauth/callback")
client = Instagram.client(:access_token => response.access_token)
user = client.user
raise client.user_recent_media.inspect
end
def instagram_login
return redirect_to Instagram.authorize_url(:redirect_uri => "http://0.0.0.0:3000/oauth/callback")
end
When the instagram callback method is called there is an errors pops-up
undefined method `query_values' for #URI::HTTPS:0x0000010441f028 and it shows the line
response = Instagram.get_access_token(params[:code], :redirect_uri => "http://0.0.0.0:3000/oauth/callback")
I guess this is a gem bug maybe not but i am having the problem there is a issue about about it in the git-hub page did any one have any solution for this ?
I commented workaround on github page.
Please try to use faraday version "0.7.6".

Dropbox Ruby API

I want to use Dropbox Ruby API, I installed the gem and when I want to create a dropbox session I got this message:
uninitialized constant DropboxController::Dropbox
Is there anything to do if I want to use this api except install the gem?
The code is:
def authorize
if params[:oauth_token] then
dropbox_session = Dropbox::Session.deserialize(session[:dropbox_session])
dropbox_session.authorize(params)
session[:dropbox_session] = dropbox_session.serialize # re-serialize the authenticated session
redirect_to :action => 'upload'
else
dropbox_session = Dropbox::Session.new('your_consumer_key', 'your_consumer_secret')
session[:dropbox_session] = dropbox_session.serialize
redirect_to dropbox_session.authorize_url(:oauth_callback => url_for(:action => 'authorize'))
end
end
This is a rails controller not for ruby.
For ruby you may refer to this tutorial and here is the DOCs for Ruby
Require the dropbox file in your current file.

invalid URI - How to prevent, URI::InvalidURIError errors?

I got the following back from delayed_job:
[Worker(XXXXXX pid:3720)] Class#XXXXXXX failed with URI::InvalidURIError: bad URI(is not URI?): https://s3.amazonaws.com/cline-local-dev/2/attachments/542/original/mac-os-x[1].jpeg?AWSAccessKeyId=xxxxxxxx&Expires=1295403309&Signature=xxxxxxx%3D - 3 failed attempts
The way this URI comes from in my app is.
In my user_mailer I do:
#comment.attachments.each do |a|
attachments[a.attachment_file_name] = open(a.authenticated_url()) {|f| f.read }
end
Then in my attachments model:
def authenticated_url(style = nil, expires_in = 90.minutes)
AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => attachment.s3_protocol == 'https')
end
That being said, is there some type of URI.encode or parsing I can do to prevent a valid URI (as I checked the URL works in my browser) for erroring and killing delayed_job in rails 3?
Thank you!
Ruby has (at least) two modules for dealing with URIs.
URI is part of the standard library.
Addressable::URI, is a separate gem, and more comprehensive, and claims to conform to the spec.
Parse a URL with either one, modify any parameters using the gem's methods, then convert it using to_s before passing it on, and you should be good to go.
I tried ' open( URI.parse(URI.encode( a.authenticated_url() )) ' but that errord with OpenURI::HTTPError: 403 Forbidden
If you navigated to that page via a browser and it succeeded, then later failed going to it directly via code, it's likely there is a cookie or session state that is missing. You might need to use something like Mechanize, which will maintain that state while allowing you to navigate through a site.
EDIT:
require 'addressable/uri'
url = 'http://www.example.com'
uri = Addressable::URI.parse(url)
uri.query_values = {
:foo => :bar,
:q => '"one two"'
}
uri.to_s # => "http://www.example.com?foo=bar&q=%22one%20two%22"

Resources