Sinatra error with dashingio and rest-client - ruby

I'm using rest-client in a dashingio job. Since adding code for rest-client I get the following error on dashing start
/Users/emcevoy/.rbenv/versions/2.1.1/lib/ruby/gems/2.1.0/gems/sinatra-1.4.6/lib/sinatra/base.rb:1595:in `define_method': tried to create Proc object without a block (ArgumentError)
Gemfile
source 'https://rubygems.org'
gem 'dashing'
## Remove this if you don't need a twitter widget.
gem 'twitter', '>= 5.9.0'
myjob.rb
require "rubygems"
require "json"
require "rest-client"
require "requests"
require "pp"
...
def post(theJson)
theUrl = $location + $endpoint.to_str
begin
response = RestClient.post(theUrl, theJson, :content_type => :json)
if(response.code > 204)
$stderr.puts("Failed to post Json to endpoint " + theUrl + "\nReturn code: " + response.code.to_s)
exit 1
end
rescue Errno::ECONNREFUSED
$stderr.puts("Server refusing connection!")
exit 1
end
if(JSON.parse(response).has_key?("error")) then
$stderr.puts("Returned an error...")
$stderr.puts JSON.parse(response)["error"]
exit 1
end
return(response)
end

Related

Why is server.rb throwing this error in terminal

I am following along with this stripe tutorial but the server.rb in the example from Stripe's Github is throwing an error when I run Ruby server.rb
I am very new to ruby so I could be doing things wrong.
What I did was:
Installed Ruby, Rails, Stripe CLI, Sinatra, and dotenv
Downloaded the example from the site by typing Stripe samples create
developer-office-hours
cd'd into the server directory and ran ruby
server.rb
this is the error
1: from server.rb:10:in '<main.'
server.rb:10:in 'join': no implicit conversation of nil into string (TypeError)
here is the server.rb file
require 'stripe'
require 'sinatra'
require 'dotenv'
# Replace if using a different env file or config
Dotenv.load
Stripe.api_key = ENV['STRIPE_SECRET_KEY']
set :static, true
set :public_folder, File.join(File.dirname(__FILE__), ENV['STATIC_DIR'])
set :views, File.join(File.dirname(__FILE__), ENV['STATIC_DIR'])
set :port, 4242
get '/' do
content_type 'text/html'
send_file File.join(settings.public_folder, 'index.html')
end
post '/webhook' do
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
webhook_secret = ENV['STRIPE_WEBHOOK_SECRET']
payload = request.body.read
if !webhook_secret.empty?
# Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil
begin
event = Stripe::Webhook.construct_event(
payload, sig_header, webhook_secret
)
rescue JSON::ParserError => e
# Invalid payload
status 400
return
rescue Stripe::SignatureVerificationError => e
# Invalid signature
puts "⚠️ Webhook signature verification failed."
status 400
return
end
else
data = JSON.parse(payload, symbolize_names: true)
event = Stripe::Event.construct_from(data)
end
# Get the type of webhook event sent - used to check the status of PaymentIntents.
event_type = event['type']
data = event['data']
data_object = data['object']
if event_type == 'some.event'
puts "🔔 Webhook received!"
end
content_type 'application/json'
{
status: 'success'
}.to_json
end
stripe login
This is a crucial step.
stripe samples create adding-sales-tax
cd adding-sales-tax/server
bundle install
If you don't have bundler, gem install bundler
bundle exec ruby server.rb
Open http://localhost:4242

Not sure why my rake seed file isn't running

here is my seed file :
require 'pry'
require 'rest-client'
require 'json'
require 'faker'
Consumer.delete_all
AlcoholicBeverage.delete_all
Intake.delete_all
100.times do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
#ingredients_data.collect do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
consumer_id = rand(1..100)
alcoholic_beverage_id = rand(1..100)
Intake.create!(consumer_id: consumer_id, alcoholic_beverage_id:alcoholic_beverage_id)
end
here is my gemfile:
# frozen_string_literal: true
source "https://rubygems.org"
gem "activerecord", '~> 5.2'
gem "sinatra-activerecord"
gem "sqlite3", '~> 1.3.6'
gem "pry"
gem "require_all"
gem "faker"
gem 'rest-client'
I've already ran my migrations fine.. so I'm not sure why nothing is showing up when I enter rake db:seed into my terminal.
Any advice or help will be much appreciated. I've also tried including require 'faker' in my seed file as well but it didn't change a thing.
This alternative approach will help you avoid missing data, by not depending on your ids being from 1 to 100:
consumers = 100.times.map do
name = Faker::Name.first_name
sex= Faker::Gender.binary_type
weight= Faker::Number.between(from: 1, to: 10)
Consumer.create!(name:name,sex:sex,weight:weight)
end
ingredients=RestClient.get("https://raw.githubusercontent.com/teijo/iba-cocktails/master/recipes.json")
#ingredients_data=JSON.parse(ingredients)
beverages = #ingredients_data.map do |x,y|
AlcoholicBeverage.create(cocktail_name: x["name"],glass: x["glass"],garnish: x["garnish"],preparation: x["preparation"])
end
100.times do
Intake.create!(consumer: consumers.shuffle.first, alcoholic_beverage: beverages.shuffle.first)
end

Ruby Minitest assert_equal fails

I have a gemfile with the following:
# frozen_string_literal: true
source "https://rubygems.org"
gem 'cucumber'
gem 'minitest', '~> 5.10', '>= 5.10.3'
gem 'minitest-focus'
gem 'minitest-reporters', '~> 1.1.9'
gem 'rspec'
...
A Cucumber .env file with this to load and require the gems:
require 'bundler'
Bundler.require
And a Ruby file with the following:
require 'minitest/autorun'
require_relative './../../../../RubyProjects/mksta-common/common'
class VerifyApi < MiniTest::Test
include Common
def initialize(has_authorization)
#has_authorization = has_authorization
end
def test_id_correct
assert_equal(20, 20)
end
end
I am receiving this error when attempting to do that assert:
undefined method `+' for nil:NilClass
In Assertions.rb:
def assert_equal exp, act, msg = nil
msg = message(msg, E) { diff exp, act }
result = assert exp == act, msg
if exp.nil? then
if Minitest::VERSION =~ /^6/ then
refute_nil exp, "Use assert_nil if expecting nil."
else
where = Minitest.filter_backtrace(caller).first
where = where.split(/:in /, 2).first # clean up noise
warn "DEPRECATED: Use assert_nil if expecting nil from #{where}. This will fail in Minitest 6."
end
end
result
end
def assert test, msg = nil
self.assertions += 1
unless test then
msg ||= "Expected #{mu_pp test} to be truthy."
msg = msg.call if Proc === msg
raise Minitest::Assertion, msg
end
true
end
Error occurs at the line: "self.assertions += 1" so i am not sure where "assertions" is not being set..
I am wondering if my require process is incorrect, or if i am missing a requirement. Or perhaps Cucumber / Rspec is getting in the way? Any help would be appreciated.
Well, the problem is when you initialize VerifyApi, you did not initialize MiniTest::Test. So the self.assertions is nil.
To solve this problem, you just need to add one more line in the initialize function
super(name)
Of course, you need add one parameter in the function.

problem with task rake, ruby

I have got a task in rake that run my server sinatra , it doesn't work , the same script in ruby works. Why ?? can I run server sinatra in rake task??
task :server do
begin
require 'rubygems'
require 'sinatra'
rescue LoadError
p "first install sinatra using:"
p "gem install sinatra"
exit 1
end
get '/:file_name' do |file_name|
File.read(File.join('public', file_name))
end
exit 0
end
Create a class that is inherited from a Sinatra::Base class
#app.rb
require 'sinatra'
class TestApp < Sinatra::Base
get '/' do
"Test"
end
end
And then run your application from rake:
#Rakefile
$:.unshift File.join(File.dirname(__FILE__), ".")
require 'rake'
require 'app'
task :server do
TestApp.run!
end

ruby sendmail after pattern found in IO

I'm sure that I am missing something. Basicaly I want to monitor a logs IO and if a FATAL ERROR is logged to send an email with the error enclosed.
#!/usr/bin/ruby -w
require 'rubygems'
def mailer(line)
date = `date +%D-%T`
f = File.open("/root/error.mail", "w")
f.puts("Subject: Fatal Error on SERVER #{date}\n\n#{line}")
f.close
system("sendmail guy#foo.com.com < /root/error.mail")
end
def fatal_check(file, pattern)
f = File.open(file, "r")
f.seek(0,IO::SEEK_END)
while true do
select([f])
line = f.gets
mailer("#{line}") if line=~pattern
#system("./mailer.rb #{line}") if line=~pattern
end
end
fatal_check("/root/test.log", /FATAL ERROR/)
How about this. You'll need a couple of gems:
gem install file-tail
gem install pony
And then your script:
require 'rubygems'
require 'pony'
require 'file/tail'
def fatal_check(file, pattern)
File::Tail::Logfile.open(file, :backward => 0) do |log|
log.tail do |line|
date = `date +%D-%T`
Pony.mail(:to => 'you#example.com', :from => 'me#example.com', :subject => "There was a nasty error on #{date}", :body => line)
end
end
end
fatal_check(File.dirname(__FILE__) + "/test.log", /FATAL/)

Resources