apn_for_rails gem implementation problem - ruby-on-rails

I have the apn_for_rails gem installed and configured correctly, the problem I'm running into is probably a syntax problem due to my newness to Ruby on Rails.
I have this in /models under the file push_notification.rb
class ApnDevice < ActiveRecord::Base
end
in routes.rb
match '/api/v2.0/RegisterIOSDevice', :to => Api::V_2_0::ApiNotifications
and then I have another file in /lib/api/v_2_0 called api_notifications.rb
require 'rubygems'
require 'sinatra/base'
require 'nokogiri'
require 'apn_on_rails'
module Api
module V_2_0
class ApiPushNotification < sinatra::Base
include ApplicationHelper
include Api::V_2_0::ApiResponse
include ApiUtil
def push_notification(params)
status = -1
error = nil
begin
if params[:device_token].blank?
return status_respnse(params,status,'device_token cant be blank')
end
existing_device_token = ApnDevice.find_by_token(params[:device_token])
if existing_device_token
return status_response(params,status,'Token already exists for device')
end
token = ApnDevice.create!(:token => params[:device_token])
rescue Exception => e
error = e.message
Rails.logger.info "#{e.class} : #{e.message}"
Rails.logger.info e.backtrace.join("\n")
rescue => e
  error = e
Rails.logger.info "Caught exception: #{e}"
Rails.logger.info e.backtrace.join("\n")
end #end of rescue
status_response(params,status,error)
end
get '/api/v2.0/RegisterIOSDevice.:format' do
push_notification(params)
end
post '/api/v2.0/RegisterIosDevice.:format' do
push_notification(params)
end
end #end of class ApiPushNotification
end #end of module V_2_0
end #end of module Api
but it gives me this huge error when I run my server, I won't post the whole thing, but it says this basically
/lib/api/v_2_0/api_notifications.rb:7: invalid multibyte char (US-ASCII) (SyntaxError)
/lib/api/v_2_0/api_notifications.rb:7: syntax error, unexpected $end, expecting keyword_end
this is followed by a stack trace which I will not post but I can't seem to find the problem, any ideas?
Edit:
ok I added the utf-8 suggestion, now I'm getting a new error:
lib/api/v_2_0/api_notifications.rb:46: syntax error, unexpected keyword_end, expecting $end (SyntaxError)

I don't know what you are doing there, but why are you using Rails if you use Sinatra instead in lib?
To your error, add the following code at the first line:
# encoding: utf-8

Related

Why am I getting sporadic disconnects when using capybara-webkit gem in Rails 4?

I use the capybara-webkit gem to scrape data from certain pages in my Rails application. I've noticed, what seems to be "random" / "sporadic", that the application will crash with the following error:
Capybara::Webkit::ConnectionError: /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/bin/webkit_server failed to start.
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/server.rb:56:in `parse_port'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/server.rb:42:in `discover_port'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/server.rb:26:in `start'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/connection.rb:67:in `start_server'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/connection.rb:17:in `initialize'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/driver.rb:16:in `new'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit/driver.rb:16:in `initialize'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit.rb:15:in `new'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-webkit-1.11.1/lib/capybara/webkit.rb:15:in `block in <top (required)>'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/session.rb:85:in `driver'
from /home/daveomcd/.rvm/gems/ruby-2.3.1/gems/capybara-2.7.1/lib/capybara/session.rb:233:in `visit'
It happens even after it's already connected and accessed a website multiple times before. Here's a code snippet of what I'm using currently...
if site.url.present?
begin
# Visit the URL
session = Capybara::Session.new(:webkit)
session.visit(site.url) # here is where the error occurs...
document = Nokogiri::HTML.parse(session.body)
# Load configuration options for Development Group
roster_table_selector = site.development_group.table_selector
header_row_selector = site.development_group.table_header_selector
row_selector = site.development_group.table_row_selector
row_offset = site.development_group.table_row_selector_offset
header_format_type = site.config_header_format_type
# Get the Table and Header Row for processing
roster_table = document.css(roster_table_selector)
header_row = roster_table.css(header_row_selector)
header_hash = retrieve_headers(header_row, header_format_type)
my_object = process_rows(roster_table, header_hash, site, row_selector, row_offset)
rescue ::Capybara::Webkit::ConnectionError => e
raise e
rescue OpenURI::HTTPError => e
if e.message == '404 Not Found'
raise "404 Page not found..."
else
raise e
end
end
end
I've even thought perhaps I don't find out why it's happening necessarily - but just recover when it does. So I was going to do a "retry" in the rescue block for the error but it appears the server is just down - so I get the same result when retrying. Perhaps someone knows of a way I can check if the server is down and restart it then perform a retry? Thanks for the help!
So after further investigating it appears that I was generating a new Capybara::Session for each iteration of my loop. I moved it outside of the loop and also added Capybara.reset_sessions! at the end of my loop. Not sure if that helps with anything -- but the issue seems to have been resolved. I'll monitor it for the next hour or so. Below is an example of my ActiveJob code now...
class ScrapeJob < ActiveJob::Base
queue_as :default
include Capybara::DSL
def perform(*args)
session = Capybara::Session.new(:webkit)
Site.where(config_enabled: 1).order(:code).each do |site|
process_roster(site, session)
Capybara.reset_sessions!
end
end
def process_roster(site, session)
if site.roster_url.present?
begin
# Visit the Roster URL
session.visit(site.roster_url)
document = Nokogiri::HTML.parse(session.body)
# processing code...
# pass the session that was created as the final parameter..
my_object = process_rows( ..., session)
rescue ::Capybara::Webkit::ConnectionError => e
raise e
rescue OpenURI::HTTPError => e
if e.message == '404 Not Found'
raise "404 Page not found..."
else
raise e
end
end
end
end
end

Ruby on Rails Error Handling, Catching Error and Message

I'm trying to figure out the best way to catch a specific error thrown AND the error's message in Ruby on Rails. My use case is that I encounter a timeout error every now and then which is thrown with a general error and I want to treat the timeout error differently than other errors within the same general error. I'm not sure what other type of errors could be thrown in the general error but I assume more of them exist. I have some sample code below of how I'm currently handling it, but I was thinking there might be a better way which I haven't found yet?
tries = 0
begin
tries += 1
<code>
rescue Foo::Bar => e
case e.to_s
when 'More specific timeout error message'
retry unless tries >= 5
else
# Let me see other error messages
log.info("Error: #{e.to_s}")
end
end
You can use multi rescue, to handle different errors.
begin
# DO SOMETHING
rescue Net::Timeout => e # change it to the error your want to catch, check the log.
# handle it
rescue SyntaxError => e # just an example
# handle it
rescue => e # any error that not catch by above rescue go here.
# handle it
end
Read more:
http://phrogz.net/programmingruby/tut_exceptions.html
You can try Rollbar, it help report error on production.
Take a look at retriable gem. It seems like a good fit for what you're proposing. Usually you'd rescue from an specific error type, but retriable also gives you the choice to rescue based on the error message.
begin
Retriable.retriable on: { Foo::Bar => /More specific timeout error message/ }, tries: 3 do
# will retry if an error of type Foo::Bar is raised
# and its message matches /More specific timeout error message/
# code here...
end
rescue => e # rescue for everything else
puts e.message # same as e.to_s
end

Show template code near error in ERB

If ERB.new(...).result raises an exception how do I get the code and backtrace near it?
Like rails does with it's templates.
I tried what #Nathan suggested before:
begin
ERB.new('<%= fail %>').result
rescue Exception => e
p e
end
=> RuntimeError
That doesn't tell me the position of the error
Try:
begin
ERB.new(...).result
rescue Exception => e
# puts e
# or
# binding.pry if you use the pry gem
end

Fabrication::MisplacedFabricateError while using Fabrication Gem on Rails 2.3.16

I am using Fabrication gem v-2.5.0 on Rails 2.3.16 but get the following errors when I run the unit test cases:
Below is the code snippet :
First case
Fabricate(:some_modal)
Fabrication::MisplacedFabricateError: # from /Users/user_xyz/.rvm/gems/ree-1.8.7- 2011.03#project/gems/fabrication-2.5.0/lib/fabrication.rb:51:in `Fabricate' from (irb):3
Second case
Fabricate(:some_other_modal)
SyntaxError: /Users/user_xyz/.rvm/gems/ree-1.8.7-2011.03#project/gems/fabrication-2.5.0/lib/fabrication/generator/active_record.rb:8: syntax error, unexpected ':', expecting ')' ...ttributes, without_protection: true)
Can someone please help me resolve these.
Modal Class :
class ErrorCode
attr_accessor :mappings
has_many :error_code_mappings
end
Fabricator :
Fabricator(:error_code) do
application_id 77
error_code_mappings(:count => 3) { |error_code, i| Fabricate.build(:error_code_mapping, :error_code => Fabricate.build(:error_code, :code => error_code.code + i))}
end
Unit test file:
require 'test_helper'
class ErrorCodeTest < ActiveSupport::TestCase
context "ErrorCode" do
setup do
#error_code = Fabricate.build(:error_code)
assert(#error_code.valid?)
end
should "have setter for mapping attribute" do
assert_respond_to(#error_code, :mappings=)
end
end
Fabrication requires Ruby 1.9 and higer version. And the current version of ruby that is being used as per the given code snippets is REE 1.8.7.
Upgrade your ruby version & then u can get it working!

Ruby on Rails Developer

Andrew
I am new for ROR Developer. i have one table to insert car images. but, that images are remote url. I have to insert 60,000 rows. i got like this "error execution terminated". Can you help how do i fix this issue?
Here My Code:
namespace :db do
task :load_photo => :environment do
require 'rubygems'
require 'open-uri'
require 'net/http'
require 'paperclip'
Website.find_in_batches(:conditions=>["image_url is not null"]) do |websites|
websites.each do |website|
begin
url = URI.parse(website.image_url)
Net::HTTP.start(url.host, url.port) do |http|
if http.head(url.request_uri).code == "200"
Car.update_attribute(:photo,open(url))
end
end
rescue Exception => e
end
end
end
end
end
I would suggest you to not rescue all Exception like you did with :
rescue Exception => e
end
then you will have (and be able to give us) more information about the error generated.
Notice that it is a good practice to rescue only exception you want.

Resources