RoR - Validate string on website, no error - ruby-on-rails

In my Ruby on Rails app I have build a function to validate if a piece of javascript is added to a certain website. When I run this code I don't get any errors in my log, but my app says:
We're sorry, but something went wrong.
If you are the application owner check the logs for more information.
But when I check the logs I don't see any errors. The code I have used is the following:
def validate_installation
data = HTTParty.get(self.website)
url = "http://www.smartnotif.com/sn.js"
if data.body.include? url
return true
else
return false
end
end
When I run this code on my local development machine it runs fine, but when I try to runs this production machine on DigitalOcean I have this problem with the same code, no errors.

Try to include
require 'httparty'
Restart rails server
rails s
Also check the permission of log folder, why it is not writing error in log folder
Also try: Use self keyword as you are calling it as class method
def self.validate_installation
data = HTTParty.get(self.website)
url = "http://www.smartnotif.com/sn.js"
if data.body.include? url
return true
else
return false
end
end

Related

Rails system test cannot access location of browser

Upon running a system test, the following error is documented:
.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/webdrivers-4.4.1/lib/webdrivers/chrome_finder.rb:21:in `location': Failed to find Chrome binary. (Webdrivers::BrowserNotFound)
Examining the chrome_finder.rb file, location method:
chrome_bin = user_defined_location || send("#{System.platform}_location")
return chrome_bin unless chrome_bin.nil?
raise BrowserNotFound, 'Failed to find Chrome binary.'
thus chrome_bin is not being populated either by the system.platform_location nor a user defined location.
The user_defined_location method implies setting Selenium::WebDriver::Chrome.path
def user_defined_location
if Selenium::WebDriver::Chrome.path
Webdrivers.logger.debug "Selenium::WebDriver::Chrome.path: #{Selenium::WebDriver::Chrome.path}"
return Selenium::WebDriver::Chrome.path
end
return if ENV['WD_CHROME_PATH'].nil?
Webdrivers.logger.debug "WD_CHROME_PATH: #{ENV['WD_CHROME_PATH']}"
ENV['WD_CHROME_PATH']
end
How can this be achieved for this rails application?

How to run heroku restart from inside of a rails app?

I understand that from the console I can run heroku restart. What I'd like to do is to have a button in my app (admin console), where pushing that button runs a heroku restart. Does anyone know how to do that and if it's possible? So the code would look something like this:
<button id="heroku_restart">Restart</button>
$("#heroku_restart").click(function() {
$.post('/restart', {}).done(function(response) {
alert(response)
})
})
class AdminsController
# this is the action mapped to the route /restart
def restart
# code for heroku restart
end
end
So per #vpibano, as of this writing, doing it with the platform-api is a breeze. Here's the action POSTed to by a button on my website:
def restart
heroku = PlatformAPI.connect_oauth(ENV["heroku_oauth_token"])
heroku.dyno.restart_all("lastmingear")
render nothing: true
end
As per the description mentioned in the post, the one way of doing it is :
1) First locate the server.pid file
pid_file = Rails.root.join("tmp", "pids", "server.opid")
2) Now, truncate the contents of the file
File.open(pid_file, "w") {|f| f.truncate(0)}
3) Finally, run the server using Kernel module:
Kernel.exec("rails s")
Note: As rightly, mentioned by #vpibano you will need authentication to access your app.
This is not a working model but a way to achieve the requirement.
Hope it helps!!

Stubbing instance method for OpenTok object

The gem I'm using to integrate OpenTok in my Rails application is at: https://github.com/opentok/Opentok-Ruby-SDK. I based the core of the application on this example: http://www.tokbox.com/blog/building-a-video-party-app-with-ruby-on-rails.
In the relevant part of code, I'm creating an #opentok object in the config_opentok method:
def config_opentok
if #api_key.nil? or #api_secret.nil?
if Rails.env.development?
#api_key = API_KEY
#api_secret = API_SECRET
else
#api_key = ENV['API_KEY']
#api_secret = ENV['API_SECRET']
end
end
if #opentok.nil?
#opentok = OpenTok::OpenTokSDK.new(#api_key, #api_secret)
end
end
And I'm creating a session with the following code:
config_opentok
if Rails.env.development?
session = #opentok.create_session('localhost')
else
session = #opentok.create_session(request.remote_addr)
end
The trouble is, the create_session seems to throw an error
SocketError: getaddrinfo: nodename nor servname provided, or not known
whenever I run my Rspec tests without an internet connection. So I'd like to stub that method so that it returns just a hash {:sessionId => 1}. But I'm having trouble figuring out how to stub the method. I can't just stub the OpenTok module or the OpenTok::OpenTokSDK class. How would I go about stubbing the create_session method?
here's what I've been doing that works:
First, what I tend to do is to initialize the OpenTok object when the app loads so I'm not creating an OpenTok object on every request. To do this, I create a ruby file (apis.rb) in my config/initializers folder.
My apis.rb looks like this:
TB_KEY = ENV['TB_KEY']
TB_SECRET = ENV['TB_SECRET']
OTSDK = OpenTok::OpenTokSDK.new TB_KEY, TB_SECRET
In my controller, to generate a session I'll simply call OTSDK.createSession, similar to what you already have.
To test with rspec, you can simply write in your test file:
OTSDK.stub(:createSession).and_return( {:sessionId => "1MX_2A3453095J0TJ30..."} )
If you run rspec with wifi turned off calling createSession should no longer throw an error.
Here's the documentation for rspec stubbing: http://rubydoc.info/gems/rspec-mocks/frames
Good Luck!
The trouble is, the create_session seems to throw an error whenever I run my Rspec tests without an internet connection.
Instead of attempting to stub, why not give your tests a mock internet connection with VCR?
After initial set up, VCR lets you run all of your tests as if you were actively connected to the internet. This allows you to run tests offline, speeds up all the tests that needed an active connection, and gives you a consistent set of results.
If you have a subscription to RailsCasts, Ryan made a video about VCR in episode 291

Rails, start remote debugger with an initializer only when --debugger is used

I want to be able to use the rails remote debugger, I really like the notion of using a separate console over TTY to debug my application. Right now I have an initializer which does does this:
# debugger.rb
Debugger.wait_connection = true
Debugger.start_remote
Now the issue is that I don't know how to only run this initializer only when the --debugger parameter is sent when the server is started? Like how from inside my application can I evaluate this as true:
if '--debugger'
Debugger.wait_connection = true
Debugger.start_remote
end
Otherwise I have to start a remove console whenever the app boots, even for rake tasks and such.
You can do this:
if ARGV.include?('--debugger') || ARGV.include?('-u')
Debugger.wait_connection = true
Debugger.start_remote
end

Getting super_exception_notifier to work

I've installed super_exception_notifier by running:
sudo gem install super_exception_notifier
and then I've tried enabling it in my project (which already has mailing working, since it sends emails for other purposes) like this. On environment.rb I added
# Notification configuration
require 'exception_notifier'
ExceptionNotifier.configure_exception_notifier do |config|
config[:exception_recipients] = %w(info#isitsciencefiction.com)
config[:notify_error_codes] = %W( 404 405 500 503 )
end
and on my application_controller.rb I have:
require 'exception_notifiable'
class ApplicationController < ActionController::Base
include ExceptionNotifiable
Am I missing something? because no matter what error I generate. Either a 404, a route error, division by zero in a controller or in the console, in development or production mode, I get no emails and no error messages or anything at all.
Any ideas?
Pablo,
Thanks for pointing out the holes in the documentation. I will setup a blank rails project and then clearly enumerate the steps. I have already updated the Readme in response to the tickets you created on github.
To help with you immediate problem this is how I have it setup, (and it works for me! :)
Not all parts of this are essential to it working, but I'm not editing it (much), so you can see what I have:
I have this in my environment.rb:
config.load_paths += %W( #{RAILS_ROOT}/app/middlewares #{RAILS_ROOT}/app/mixins #{RAILS_ROOT}/app/classes #{RAILS_ROOT}/app/mailers #{RAILS_ROOT}/app/observers )
I have an initializer in config/initializers/super_exception_notification.rb
#The constants ($) are set in the config/environments files.
ExceptionNotifier.configure_exception_notifier do |config|
config[:render_only] = false
config[:skip_local_notification] = false
config[:view_path] = 'app/views/errors'
config[:exception_recipients] = $ERROR_MAIL_RECIPIENTS
config[:send_email_error_codes] = $ERROR_STATUS_SEND_EMAIL
#config[:sender_address] = %("RINO #{(defined?(Rails) ? Rails.env : RAILS_ENV).humanize} Error" )
config[:sender_address] = "errors#swankywebdesign.com"
config[:email_prefix] = "[RINO #{(defined?(Rails) ? Rails.env : RAILS_ENV).capitalize} ERROR] "
end
Then in my application.rb I have this:
include ExceptionNotifiable, CustomEnvironments
alias :rescue_action_locally :rescue_action_in_public if Environments.local_environments.include?(Rails.env)
self.error_layout = 'errors'
self.exception_notifiable_verbose = false
self.exception_notifiable_silent_exceptions = [MethodDisabled]
Then I also have this mixin in my app/mixins directory:
module CustomEnvironments
module Environments
def self.local_environments
%w( development test )
end
def self.deployed_environments
%w( production staging )
end
end
end
One other thing, this plugin does not abolish the rails standard which is that things in public are trump. So if you have 404.html in public, it will always get rendered for 404's.
Peter
Maybe it has has something to do with this:
http://github.com/pboling/exception_notification
Email notifications will only occur when the IP address is determined not to be local. You can specify certain addresses to always be local so that you’ll get a detailed error instead of the generic error page. You do this in your controller (or even per-controller).
consider_local "64.72.18.143", "14.17.21.25"
You can specify subnet masks as well, so that all matching addresses are considered local:
consider_local "64.72.18.143/24"
The address "127.0.0.1" is always considered local. If you want to completely reset the list of all addresses (for instance, if you wanted "127.0.0.1" to NOT be considered local), you can simply do, somewhere in your controller:
local_addresses.clear

Resources