Configuring Ruby On Rails Application With Iex-Ruby-Client Gem - ruby-on-rails

I am a beginner programmer. I recently built an application that uses the iex-ruby-client gem to pull stock quotes for me that I enter into a webpage form. It worked perfectly.
However, in early June, IEX changed their API so that you have to have a publishable token from the IEX cloud console. I got my publishable token from IEX cloud console.
The updated gem docs (https://github.com/dblock/iex-ruby-client) say that I have to "Configure" the application now. I simply don't know how or where I would implement the configuration code. Here is the suggested code from the gem documentation. I just don't know where to put it.
Configure IEX::Api.configure do |config|
config.publishable_token = 'token' # defaults to
ENV['IEX_API_PUBLISHABLE_TOKEN']
config.endpoint = 'https://sandbox.iexapis.com/v1' # defaults to
'https://cloud.iexapis.com/v1'
end
The documents also state, "You can also configure an instance of a client directly."
client = IEX::Api::Client.new(
publishable_token: 'token',
endpoint: 'https://sandbox.iexapis.com/v1'
)
I am adding extra code to clarify what I have done based on the response here. Here is my new config/initializers/iex-ruby-client.rb file (token info isn't the real one).
IEX::Api.configure do |config|
config.publishable_token = 'pk_3b38fsdadfsafjsdalfjdsakfjlda12f519'
config.endpoint = 'https://sandbox.iexapis.com/v1'
end
Here is the relevant method in the controller where I require the library:
def index
require 'iex-ruby-client'
if params[:id] == ""
#nothing = "You forgot to enter a symbol ;)."
elsif
if params[:id]
begin
#stock = IEX::Resources::Quote.get(params[:id])
#company = IEX::Resources::Company.get(params[:id])
rescue StandardError
#error = "That stock symbol doesn't seem to exist. Please enter
another symbol."
end
end
end
end
So I have created the config file and required the gem at the top of the method, but I am still getting an error. I'm sure there is some flaw in my implementation of this token requirement. If you have any additional suggestions, I welcome them. But if this is too much to ask on Stack Overflow, I understand. Thanks.

Well, you clearly have two choices:
use initializer by creating a config file(i.e: iex_client.rb) under the directory /config/initializers and add:
Configure IEX::Api.configure do |config|
config.publishable_token = 'token' # defaults to
ENV['IEX_API_PUBLISHABLE_TOKEN']
config.endpoint = 'https://sandbox.iexapis.com/v1' # defaults to
'https://cloud.iexapis.com/v1'
end
just use the client object wherever you want like this:
client = IEX::Api::Client.new(
publishable_token: 'token',
endpoint: 'https://sandbox.iexapis.com/v1'
)
You probably need to replace token with a correct one. You also need to make sure to require the library wherever you wanna use it.

After unsuccessfully attempting to configure the IEX-ruby-client gem (as described in my question here on stack overflow), I switched over to the stock_quote gem. That gem is built off of the same IEX API, and I had no problems configuring the app with a stock_quote.rb file saved inside config/initializers.

Related

How to access AWS Comprehend using aws-sdk-comprehend gem?

I'm working on getting my Rails app interacting with the AWS Comprehend service for text entity extraction. I'm using the aws-sdk-comprehend gem. I have successfully gotten my app working with the AWS Rekognition service for image analysis using the aws-sdk-rekognition gem.
I can't seem to get the AWS Comprehend authentication correct as all of my calls result in an Aws::Comprehend::Errors::InvalidRequestException.
I have all of the following ENV variables set:
AWSAccessKeyId
AWSSecretKey
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
My code looks something like this:
class MyApp::Aws::ComprehendService < MyApp::ServiceBase
def call
#credentials = Aws::Credentials.new(ENV['AWSAccessKeyId'], ENV['AWSSecretKey'])
#client = Aws::Comprehend::Client.new(region: "us-west-1", credentials: credentials)
#client.detect_entities({text: "this is a simply little blob of text", language_code: "en"})
end
end
This resulted in Aws::Comprehend::Errors::InvalidRequestException. So I also tried:
class MyApp::Aws::ComprehendService < MyApp::ServiceBase
def call
# use ENV credential format I've seen in examples...
#credentials = Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
#client = Aws::Comprehend::Client.new(region: "us-west-1", credentials: credentials)
#client.detect_entities({text: "this is a simply little blob of text", language_code: "en"})
end
end
I found an example that didn't use the #credential approach. The example claimed "The initialize method will load the credentials environment variables by itself". So I tried this:
class MyApp::Aws::ComprehendService < MyApp::ServiceBase
def call
# ignore setting the credentials
#client = Aws::Comprehend::Client.new(region: "us-west-1")
#client.detect_entities({text: "this is a simply little blob of text", language_code: "en"}).
end
end
This also resulted in Aws::Comprehend::Errors::InvalidRequestException.
Can you see anything I'm doing wrong? Has anyone had success in using this gem to interact with the Comprehend API?
Per the Documentation for Aws::Comprehend::Client#detect_entities
If the system detects a document-level error in your input document, the API returns an InvalidRequestException error response. For details about this exception, see Errors in semi-structured documents in the Comprehend Developer Guide.
So it appears your usage is not necessarily the issue but rather the input documents themselves.
The response however should include what the actual issue is according to the Developer Guide:
Document-level errors
If the ClassifyDocument or DetectEntities API operation detects a document-level error in your input document, the API returns an InvalidRequestException error response.
In the error response, the Reason field contains the value INVALID_DOCUMENT.
The Detail field contains one of the following values:
DOCUMENT_SIZE_EXCEEDED – Document size is too large. Check the size of your file and resubmit the request.
UNSUPPORTED_DOC_TYPE – Document type is not supported. Check the file type and resubmit the request.
PAGE_LIMIT_EXCEEDED – Too many pages in the document. Check the number of pages in your file and resubmit the request.
TEXTRACT_ACCESS_DENIED_EXCEPTION – Access denied to Amazon Textract. Verify that your account has permission to use the Amazon Textract DetectDocumentText and AnalyzeDocument API operations and resubmit the request.
The Aws::Comprehend::Errors::InvalidRequestException object is documented so it appears you could potentially figure out what is wrong via
def call
# use ENV credential format I've seen in examples...
#credentials = Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'])
#client = Aws::Comprehend::Client.new(region: "us-west-1", credentials: credentials)
begin
#client.detect_entities({text: "this is a simply little blob of text", language_code: "en"})
rescue Aws::Comprehend::Errors::InvalidRequestException => e
# interrogate the error object here e.g.
puts {reason: e.reason, detail: e.detail}
end
end

Action Mailbox saying "Missing required Mailgun API key" even though key is present

I have Mailgun set up to forward emails to my /rails/action_mailbox/mailgun/inbound_emails/mime endpoint.
When my endpoint receives the request, it gives the following error:
ArgumentError (Missing required Mailgun API key. Set
action_mailbox.mailgun_api_key in your application's encrypted
credentials or provide the MAILGUN_INGRESS_API_KEY environment
variable.)
However, MAILGUN_INGRESS_API_KEY is in fact set. When I run ENV["MAILGUN_INGRESS_API_KEY"] in the console, I see my API key. I even pasted in the API key determination code from GitHub to see if there was a problem there, but the return value I got was my actual API key.
Any ideas on what the problem could be?
Just checking few things to see if can rectify, as I understand you know much better than me about rails.
Do you have setup mailgun api_key in environment configuration like for development config/environments/development.rb
config.action_mailer.delivery_method = :mailgun
config.action_mailer.mailgun_settings = {
api_key: ENV['MAILGUN_INGRESS_API_KEY'],
domain: 'your_domain.com',
# api_host: 'api.eu.mailgun.net' # Uncomment this line for EU region domains
}
Now let us do one test, visit (bin.mailgun.net) and get paste bin url then run rails c
mg_client = Mailgun::Client.new(ENV["MAILGUN_INGRESS_API_KEY"], "bin.mailgun.net", "aecf68de_you_got_visiting_site", ssl = false)
message_params = { from: 'bob#sending_domain.com',
to: 'sally#example.com',
subject: 'The Ruby SDK is awesome!',
text: 'It is really easy to send a message!'
}
result = mg_client.send_message("your_sending_setup_on_mailgun_domain.com", message_params)
puts result.inspect
See what message came and you may get idea. There could be environment configuration issue also for development you have to setup different then for production. Also check on paste-bin does it got any hit.

Retrieving Youtube comments with fullscreen/yt

I'm using https://github.com/Fullscreen/yt to interact with Youtube API, but after a couple of hours of testing I'm unable to fetch comments from a video.
I suspect the reason is I'm requesting the wrong permissions, but I can't find anything clear in Google docs about what scope to ask. I appears from the OAuth playground it's https://www.googleapis.com/auth/youtube.force-ssl
but still, I'm not able to make it work.
This is the omniauth provider line to request a new token:
provider :google_oauth2, key, secret, {:scope => 'http://gdata.youtube.com,email,profile,youtube,youtube.force-ssl'}
And this is how I try to retrieve the comments:
Yt.configure do |config|
config.client_id = key
config.client_secret = secret
end
youtube_client = Yt::Account.new access_token: 'yadayada'
video = Yt::Video.new id: 'foobar', auth: youtube_client
puts video.comments
What I get is:
Yt::Errors::Forbidden: A request to YouTube API was considered forbidden by the server:
{"error"=>{"errors"=>[{"domain"=>"global", "reason"=>"insufficientPermissions", "message"=>"Insufficient Permission"}], "code"=>403, "message"=>"Insufficient Permission"}}
I've tried pretty much the same on channels too, same problem, that's why I guessed there's something wrong with my access_token.
Has someone done this? What am I doing wrong? Any example?
As per the documentation on the page you have shared the link of, I am not able to see this line of code:
account = Yt::Account.new authorization_code: '4/Ja60jJ7_Kw0', redirect_uri: redirect_uri
Every user who authorizes your app will be redirected to the redirect_uri with an extra code parameter that looks something like 4/Ja60jJ7_Kw0. Just pass the code to the following method to authenticate and initialize the account:
If this does not workout try Configuring with environment variables
As an alternative to the approach above, you can configure your app with variables. Setting the following environment variables:
export YT_CLIENT_ID="1234567890.apps.googleusercontent.com"
export YT_CLIENT_SECRET="1234567890"
export YT_API_KEY="123456789012345678901234567890"
is equivalent to configuring your app with the initializer:
Yt.configure do |config|
config.client_id = '1234567890.apps.googleusercontent.com'
config.client_secret = '1234567890'
config.api_key = '123456789012345678901234567890'
end
so use the approach that you prefer. If a variable is set in both places, then Yt.configure takes precedence.
Hope this Helps!!

Paypal-express gem, working in dev but not in prod

So I have an issue I can't figure out alone.
I have run some test on my app and when launch in dev it's working perfectly but as soon as it's on Prod and so it uses the real identificator, it doesn't work anymore.
I got this error:
Paypal::Exception::APIError (PayPal API Error: 'Security error'):
/offers_controller.rb:218:in choose_step'
if Rails.env.production?
response = request.setup(
payment_request,
"http://www.workiz.com/recruteurs/paypal_callback/" + params[:app_id],
"http://www.workiz.com/recruteurs/offres",
paypal_options # Optional
)
else # Development ou Test
response = request.setup(
payment_request,
"http://localhost:3000/recruteurs/paypal_callback/" + params[:app_id],
"http://localhost:3000/recruteurs/offres",
paypal_options # Optional
)
end
That is the line that crash, so it's when I call request.setup
The request is created like that:
if Rails.env.development?
Paypal.sandbox!
Paypal::Express::Request.new(
username: ENV['PAYPAL_SANDBOX_USERNAME'],
password: ENV['PAYPAL_SANDBOX_CLI_ID'],
signature: ENV['PAYPAL_SANDBOX_SECRET']
)
elsif Rails.env.production?
Rails.logger.info "Paypal SETUP PRODUCTION"
Paypal::Express::Request.new(
username: ENV['PAYPAL_USERNAME'],
password: ENV['PAYPAL_CLI_ID'],
signature: ENV['PAYPAL_SECRET']
)
end
And yes the logger "Paypal SETUP PRODUCTION" appear and the value set are the good one from the ENV variables.
I had to put Paypal.sandbox! in the config/development.rb to make it work for the sandbox but I cannot find a way to make it work for the production...
Any help is welcome. Thank you very much.
I have display the error, it look like that:
ERROR IS: #<Paypal::Exception::APIError::Response:0x007fa61661e040
#raw={
:TIMESTAMP=>"2015-05-24T15:01:30Z",
:CORRELATIONID=>"f3067f049ad",
:ACK=>"Failure",
:VERSION=>"88.0",
:BUILD=>"1675131",
:L_ERRORCODE0=>"10002",
:L_SHORTMESSAGE0=>"Security error",
:L_LONGMESSAGE0=>"Security header is not valid",
:L_SEVERITYCODE0=>"Error"},
#ack="Failure", #build="16751317", #correlation_id="f3067f049a", #timestamp="2015-05-24T15:01:30Z", #version="88.0", #order_time=nil, #pending_reason=nil, #payment_status=nil, #payment_type=nil, #reason_code=nil, #transaction_type=nil,
#error_code="10002",
#severity_code="Error",
#long_message="Security header is not valid",
#short_message="Security error"
Have a detailed look at the exception you're getting.
According to https://github.com/nov/paypal-express/blob/master/lib/paypal/exception/api_error.rb the error should have more useful information from the API response.
Simply catch the exception, and print it's contents:
begin
response = request.setup...
rescue Paypal::Exception::APIError => error
puts error.inspect
raise error
end
You're probably missing some configuration in your PayPal account. The detailed error message and error code should point you in the right direction.
Ok I have finally found my mistake.
It appear, you shouldn't use the CLI ID, PWD and SIGNATURE from the "live page" on your application.
But instead:
Log in to PayPal.com
You must have a PayPal Business account to make calls to the live PayPal servers. Log in to your Business account on the following page: https://www.paypal.com.
Navigate to the API Access page
Click the Tools tab and navigate to Manage your business > API Access.
Here you go, those are the good one...
Very confusing !
Hope it helps
First, double check that the 2 sets of credentials are different. You need a different account for sandbox than production.
PAYPAL_SANDBOX_USERNAME != PAYPAL_USERNAME
PAYPAL_SANDBOX_CLI_ID != PAYPAL_CLI_ID
PAYPAL_SANDBOX_SECRET != PAYPAL_SECRET
Second, double check that the production credentials are correct, i.e. no extra characters or typos.

Session timeout using Clearance in a Rails app

I'm using Clearance for authentication in my Rails app. Does anyone know of a way to configure a session timeout? It's been logging me out within 5 minutes of when I login and I can't seem to locate anything that specifies how to set the timeout.
When you installed Clearance, I think it should have added a config/initializers/clearance.rb file. You can configure the session timeout in there through the use of the cookie_expiration config. From their docs, it can look like this:
#example
Clearance.configure do |config|
config.mailer_sender = 'me#example.com'
config.cookie_expiration = lambda { 2.weeks.from_now.utc }
config.password_strategy = MyPasswordStrategy
config.user_model = MyNamespace::MyUser
end
So, just give cookie expiration a lambda that returns a Time object that occurs sometime in the future.
Looking at the rdoc, there's a cookie_expiration method on the Clearance configuration class. Here it is -- look at the source for the method:
By default, it looks like it's 1 year:
def initialize
#mailer_sender = 'donotreply#example.com'
#cookie_expiration = lambda { 1.year.from_now.utc }
end
So I'd look at overriding that in the configuration.
http://rdoc.info:8080/github/thoughtbot/clearance/Clearance/Configuration#cookie_expiration-instance_method
If you're unable to find it, sometimes you can ask on the Thoughtbot IRC channel #thoughtbot on freenode. Sometimes the developers hang out there and they'll field questions.

Resources