Why won't my Rails function abort? - debugging

I'm trying to debug an application that someone else wrote. In my production.log, I see:
Processing by Friendster::AppsController#home as HTML
Parameters: {SOMESTUFF}
Completed 500 Internal Server Error in 3ms
So I go to the app/controller/friendster/apps_controllers and look at the home function and it is:
def home
show_app_container
end
So I changed it to:
def home
puts "container"
abort "SHAMOON"
show_app_container
end
Just so I can see some sort of error or log. But nothing shows up anywhere. Nothing renders differently. I don't know if there's caching going on or if I'm in the right function. Any help debugging this would be greatly appreciated.
I also ran a bundle exec rake routes and got:
friendster_app_home POST /publishers/:publisher_id/apps/:app_id/home(.:format) {:action=>"home", :controller=>"friendster/apps"}
GET /publishers/:publisher_id/apps/:app_id/home(.:format) {:action=>"home", :controller=>"friendster/apps"}
Although there are quite a few routes with GET /publishers/:publisher_id/apps/:app_id/home(.:format), so I'm not sure what that means. This is the only friendster one.
EDIT: Adding Base controller parent
class Friendster::BaseController < AppsController
protected
end

Any help debugging this would be greatly appreciated.
Include the pry gem, call binding.pry inside of #home and Pry will spawn an interactive debugger in the console.
def home
binding.pry
show_app_container
end

Related

Not able to call method in a gem

This might be an easy question but I was unfortunately not able to find the answer on Google.
Context:
I am working on a project of my own, and I am externalizing some code in a gem (FrenchTaxSystem). It is the first I create a gem and I have difficulties using it properly.
Problem:
When calling a method (like testit) defined in the main file (french_tax_system.rb) of my gem I get a "NoMethodError: undefined method `testit' for FrenchTaxSystem:Module", though I can call constants from this same file (like FISCAL_NB_PARTS_FOR_MARRIED_COUPLE) and it puzzles me.
E.g in IRB I get that when calling a method:
[
And it is the same in my Rspecs tests inside my gem
However when calling a constant I have no error:
Main file in my gem:
french_tax_system.rb
module FrenchTaxSystem
class Error < StandardError; end
# Constants
...
FISCAL_NB_PARTS_FOR_MARRIED_COUPLE = 2
...
# Methods
## Main method
def testit
"test me"
end
end
Gem file structure:
Thank you in advance for your help,
Mth0158
This should work:
module FrenchTaxSystem
def self.testit
"test me"
end
end

How to write a simple Cucumber script

I'm following the tutorial to run my first Cucumber script:
Feature: guru99 Demopage Login
In order to Login in Demopage we have to enter login details
Scenario:
Register On Guru99 Demopage without email
Given I am on the Guru99 homepage
When enter blank details for register
Then error email shown
I have the project in Idea but when I run it I get errors.
When using chrome:
Failed to open TCP connection to 127.0.0.1:9515 (No connection could be made because the target machine actively refused it.
I have no idea how to resolve it.
When using Firefox, the script successfully opens the browser but fails after that:
require 'watir'
require 'colorize'
Selenium::WebDriver::Firefox::Binary.path='C:\soft\Mozilla Firefox\firefox.exe'
case ENV['BROWSER']
when 'chrome'
browser = Watir::Browser.new :chrome
when 'firefox'
browser = Watir::Browser.new :firefox
end
Given(/^I am on the Guru99 homepage$/)do
#browser = Watir::Browser.new :firefox
#browser.goto "http://demo.guru99.com"
end
When(/^enter blank details for register$/) do
browser.text_filed(:name,"emaiid").set("")
browser.button(:name,"btnLogin").click
end
Then(/^error email shown$/) do
puts "Email is Required!".red
browser.close
end
And returns:
NoMethodError: undefined method `text_filed' for nil:NilClass
on this line:
browser.text_filed(:name,"emaiid").set("")
I found some references that I need to write a class to call a method. I tried it but didn't succeed.
Connection refused, I'm unsure but "Watir+Cucumber Connection refused" looks a fix.
Copy pasta:
AfterConfiguration do |config|
yourCodeStartUp() # Put your SETUP code here including the launch of webdriver
at_exit
yourCodeTearDown() # Put your CLOSING routine here
puts 'stopped'
end
end
The code error is a typo, it should be browser.text_field(...
Regarding the issue you are observing on chrome, it sounds like you need to update chromedriver (and make sure the exe is in PATH). If you are running chrome v56-58, you need ChromeDriver 2.29.
Regarding the NoMethodError: undefined method error, you have a typo when you call the text_field method (i.e. browser.text_filed).
Nope, I was mistaken, I had an older version of chromedriver. Now it's running in chrome as well. Thank you very much. Appreciate your time!
So, the answers are:
1. Update chromedriver.
2. Check your code for typos one more time.
Was really easy but took me a lot of time%

Sinatra - Error Handling

I'm trying to make my sinatra app show a custom error page when an error is raised on the server (e.g. an IOError or ArgumentError).
Currently I'm using AJAX to load the results into a certain #results div, but if and when an error arises on the server, I would like an error page to open up on a new page.
Currently, the IOError is shown on the server and a error is seen in the console (the server responded with a status of 500 (Internal Server Error)). Other than that, nothing happens.
I think that I have to play about with the Javascript (as well as the Sinatra::Base class) but I've spent the whole of yesterday and this morning not getting anywhere.
I would be very grateful for any help. I've created an oversimplified version of my app which I have shown below...
Sinatra_app.rb
require 'sinatra/base'
require9 'sinatra'
require 'slim'
# A helper module
module GVhelpers
def create_results(name)
# raise IOError, "There's a problem..."
return "<p>The Server Says 'Hey #{name}'</p>"
end
end
class GVapp < Sinatra::Base
helpers GVhelpers
set :root, File.dirname(__FILE__)
error do
#error = env['sinatra.error']
slim :"500", :locals => {:error => error}
end
get '/' do
slim :index
end
post '/form' do
name = params[:personName]
create_results(name)
end
end
GVapp.run!
index.slim (in views folder)
script src="/jquery.min.js"
script src="/Gvapp.js"
form#sayHey action="/form" method="post"
| Name:
input type="text" name="personName"
br
input type="submit"
#output
500.slim (in views folder)
h1 Oops! Something went Wonky!
p Apologies, there was an error with your request:
strong request.env['sinatra.error'].message
p If the error persists, please contact the administrator.
Gvapp.js (in public folder)
$(document).ready(function() {
$('#sayHey').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/form',
data: $('#sayHey').serialize(),
success: function(response){
$('#output').html(response);
}
})
})
})
Sinatra swallows exceptions when run in the development environment by default and shows its debugging error page instead. So, to trigger your custom error handlers, you have to either run the application inside a Rack environment other than development (probably production), or preferably, tell Sinatra to not use its default error handlers in development mode.
Consider the following, standalone Sinatra application example:
require "sinatra"
#disable :show_exceptions
get "/" do
raise RuntimeError.new("boom")
end
error RuntimeError do
"A RuntimeError occured"
end
If you run this application using the default development environment like this:
$ ruby foo.rb
Then you will get Sinatra’s default error page. If you uncomment the disable line in the example, the error handler will be triggered instead, displaying a page containing "A RuntimeError occured". Alternatively, you can, as explained, run the application in an environment other than development as only that one pre-sets the show_exception setting. You can do that by setting the RACK_ENV environment variable:
$ RACK_ENV=production ruby foo.rb
For development purposes, setting RACK_ENV to production is not the correct way of course. Use disable :show_exceptions instead. You can use a configure block as outlined in the Sinatra README to conditionally disable the setting for the development environment.
configure :development do
disable :show_exceptions
end
That behaviour is documented in Sinatra’s documentation on configuration, along with several other useful settings.

How do I change the aws-ruby log location?

I've found the method set_log in the documentation, I just can't figure out the syntax to call it. Here's what I tried:
require 'ruby-aws'
Amazon::Util::Logging.set_log('my.log')
NoMethodError: undefined method `set_log' for Amazon::Util::Logging:Module
You can see that Amazon::Util::Logging is a module and set_log is a 'Public Instance method'. So you need
class NewClass
include Amazon::Util::Logging
def foo
set_log('file.txt')
log 'debug_message'
end
end
I ran into this problem when trying to deploy a Ruby-on-Rails site that uses 'aws-ruby' to heroku (I got the "Permission denied - ruby-aws.log" error).
To change the log file location from 'ruby-aws.log' to 'log/ruby-aws.log', I added the following to an initializer. Make sure this is called before you use any of the aws-ruby library. Notice the change on the "set_log..." line.
module Amazon
module Util
module Logging
def log( str )
set_log 'log/ruby-aws.log' if ##AmazonLogger.nil?
##AmazonLogger.debug str
end
end
end
end
A simpler way would be to add this line:
set_log("/dev/null")

Ruby Daemons causing ActiveRecord logger IOError

I'm writing a project at the moment in Ruby which makes use of the ActiveRecord gem for database interaction and I'm trying to log all the database activity using the ActiveRecord::Base.logger attribute with the following code
ActiveRecord::Base.logger = Logger.new(File.open('logs/database.log', 'a'))
This works fine for migrations etc (which for some reason seem to require that logging be enabled as it gives a NilClass error when it's disabled) but when I try to run the project which includes a threaded daemon calling the ActiveRecord object the script fails with the following error
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/logger.rb:504:in `write': closed stream (IOError)
Any ideas on how to solve this problem would be greatly appreciated. For the moment I've started to look through other code to see if people have other ways of implementing ActiveRecord logging in a more thread-safe manner
Thanks
Patrick
I ran into the same issue. You need to daemonize first, and then load the Rails environment.
the delayed_job have used daemons and activerecord,
before daemonize,get the files have opend,and then reopen in daemonize
#files_to_reopen = []
ObjectSpace.each_object(File) do |file|
#files_to_reopen << file unless file.closed?
end
Daemons.run_proc("xxxxx_name",:dir=>pid_file,:dir_mode=>:normal) do
Dir.chdir(Rails.root)
# Re-open file handles
#files_to_reopen.each do |file|
begin
file.reopen file.path
file.sync = true
rescue ::Exception
end
end
end
It turns out that for migrations to work the ActiveRecord::Base.logger variable cannot be nil, which explains the first half of the problem. I am as yet unable to fix the IOError though when a file is used instead of STDERR.

Resources