Rails 400 and 500 error page in development mode - ruby-on-rails-3

I am trying to display the 500 error page whenever exception occurs. below is my setting
in development.rb file
config.consider_all_requests_local = false
and also override the method local_request in application_controller.rb file
def local_request?
false
end
But still not able to display 500 page on local machine in case of exception. I also tried to run app on production mode, but still getting same result.However i can successfully display 500 web page using IP address.plz help

Are you routing them properly? You can do custom error pages by putting in your application.rb:
# For error handling
config.exceptions_app = self.routes
Then in your routes.rb file:
## Routes for Exceptions
match '/404', to: "static#not_found", as: "not_found"
match '/422', to: "static#rejected", as: "rejected"
match '/500', to: "static#something_wrong", as: "something_wrong"
Assuming you have a "static" controller (use whatever you want). Then render out the templates as you normally would.

Related

Cache files always created with wrong permissions in Yii 2

I get this error in my log files every time a cache file doesn't exist it seems. On the first page load, I always get this error
[message] => filemtime(): stat failed for [...]/runtime/cache/my/myapp03eab921185f7b68bbca50d8debc0dda.bin
[file] => [...]/vendor/yiisoft/yii2/caching/FileCache.php
[line] => 113
It doesn't happen anymore on next page loads but that one time is really annoying since the slack bot watcher is spamming our channel with this useless warning. Is there a way to avoid that, or is it a permission problem?
The "runtime", "cache" and "my" folders all have 775.
Update
Turns out the issue is that I'm using error_get_last() that is also getting warning-level errors. So it's a different issue entirely, not Yii-related
Make sure that you don't have enabled scream in your php.ini. Warnings from this filemtime() call should be suppressed by # operator, but scream setting can override this operator and generate warning anyway.
if (#filemtime($cacheFile) > time()) {
// ...
}
You must be getting this in PHP 7.1. try to run this with PHP 5.5 and see if you are getting the same error.
To reproduce you need to delete all files from runtime/cache directory
Then start app again(reload page) and look into runtime/cache. It is empty
Yii2 doesn't make cache again
Got same issue in Yii. The error was on the same string (FileCache.php:113)
if (#filemtime($cacheFile) > time()) {...
In my case reason was that my custom php error handler (heir
of the class yii\base\ErrorHandler) didn't check if
error type need to be handled according error_reporting().
Custom handlers allways gets every error, even muted by Error Control operator (#)
https://www.php.net/manual/en/function.set-error-handler.php
error_reporting() settings will have no effect and your error handler will be called regardless

Unable to get Ruby Page-Object gives error "undefined method"

I am new to using PageObject::PageFactory.
I can’t get this simple scenario to work. Can someone Help me with this?
My Feature file
Feature: Find Pens
Scenario:
Given a user goes to Amazon website
When they search for “pens”
Then they are able to find “pens”
My Step_definition
Given(/^a user goes to Amazon website$/) do
visit HomePage
end
When(/^they search for “(.*?)”$/) do |page|
on HomePage do
page.look_pens
end
end
Then(/^they are able to find “(.*?)”$/) do |arg1|
pending # express the regexp above with the code you wish you had
end
Page Object file
QUESTION: Is it right to put this file in Support folder or should this be living elsewhere?
class HomePage
include PageObject
page_url(‘http://www.amazon.co.uk’)
text_field(:name, :id=> ‘twotabsearchtextbox’) #:id is the web-element from the actual webpage. Should this be something else?
button(:search, :value=>’Go’)
def look_pens(name,search)
self.name = pens
self.search
end
end
The Given part when run with Cucumber-SeleniumWebdriver does open the Amazon browser, but after that gives the following error for the When part
The Error
p.rb:1
When they search for “pens” # features/step_definitions/buy_pens_ste
p.rb:5
undefined method `look_pens’ for “pens”:String (NoMethodError)
./features/step_definitions/buy_pens_step.rb:7:in `block (2 levels) in ‘
./features/step_definitions/buy_pens_step.rb:6:in `/^they search for “(.*?
)”$/’
features\buy_pens.feature:5:in `When they search for “pens”‘
My env.rb in the support folder contains:
require ‘page-object’
require ‘selenium-webdriver’
require ‘page-object/page_factory’
Before do
#browser = Selenium::WebDriver.for(:firefox)
end
After do
#browser.close
end
World(PageObject::PageFactory)
Typically page object files are maintained in a separate folder that is at the same level as the features directory. You will need to use additional require statements so that Ruby knows that they are located in that folder.
Re the error: Looks like the compiler is having difficulty recognizing that look_pens is a method of the HomePage class. Try moving the |page| from the end of the When step def to the second line, so that it looks like code below.
When(/^they search for “(.*?)”$/) do
on HomePage do |page|
page.look_pens
end
end

How to debug QWebView's failure to load a web page?

I use QWebView to load a page, then I only keep reloading it with reload()slot. loadFinished(bool) signal often undicates false. I also use QwebView's network access manager's finished signal to get http response code - it's set to 0.
The same page loads fine with all browsers, no matter how fast I try to relaod it in browser. How to debug this problem, what could be wrong?
Have you tried to get the reply's error code and error message, like this:
class Browser(object):
def __init__(self):
self.network_manager = QNetworkAccessManager()
self.network_manager.finished.connect(self._request_finished)
self.web_page = QWebPage()
self.web_page.setNetworkAccessManager(self.network_manager)
self.web_view = QWebView()
self.web_view.setPage(self.web_page)
def _request_finished(self, reply):
print reply.error()
print reply.errorString()

Rails 3 send_data issue; difference between production and development

I have a strange bug in my Rails 3 app. I am using this code to send images that are not public:
image = open(f, "rb") { |io| io.read }
send_data(image, :disposition => 'inline')
I am using this code to display images in admin pages and user pages. If I use development environment this code works OK and the images are displayed on both pages. But if I use production environment, this images are displayed only in admin pages but not user pages. I can click on the images that are not displayed, and select "properties". Under image type I see:
application/xhtml+xml
But other public images has under the type JPG image/PNG image or something like this.
Which difference between the environemnts could be causing images not to work and how can I fix this, so the images will be properlly displayed on the all pages?
I had a distinctly similar symptom. I know this is an old issue and already resolved but I thought I would contribute the findings of my situation which turned out to be a different cause.
I was building a CSV file and using send_file to send the file to the browser. In development it worked great, in production the browser reported a page not found.
Here is the action from the controller.
def export
#campaign = LiveEmailCampaign.find params[:id]
#campaign.recipients_csv do |csv_file|
send_file csv_file,
filename: #campaign.name,
type: Mime::CSV
end
end
And the CSV is build from this code in a model.
def recipients_csv
tempfile = Tempfile.new(self.name.downcase.dasherize)
CSV.open tempfile, 'w' do |csv|
recipients.each do |recipient|
csv << [recipient]
end
end
yield tempfile
end
After a few minutes of research I determined that the culprit was a conflict between the XSendFile directive in Apache on the production server and the temporary path being used to write the CSV data to. In my case XSendFile was set for only the app root and the temp file was in /tmp on the server.
Instead of tampering with the XSendFile config at the server level I just instructed Tempfile to use the tmp folder in the Rails app.
So, I changed the call to Tempfile in the model method to this
tempfile = Tempfile.new(self.name.downcase.dasherize)
Now, Rails and Apache are friends again. I just need to refactor this code because it doesn't explicitly unlink the created temporary file. Best practice is to explicitly unlink temporary files.

Paperclip processor can't find it's file

Formerly: Running a model method on a paperclip attachment after create or update (paperclip callbacks don't seem to work)
Edit (later that day)
I figured out my problem. The processor apparently works with the file that is updated, but doesn't save any files until after processing. I changed my Zip::ZipFile to open 'file' rather than 'attachment.path' since the attachment path doesn't actually hold anything yet. This fixed the first problem. Now I'm having other problems that I'll need to track down. But the answer below is mostly correct.
Edit (1/31/2011):
So I have taken the advice to create a processor for my attachment which will perform all the necessary actions. So far, it looks like it should work; the processor starts and does all the initialization stuff, apparently. However, when I get the point where I want to access the zip file that gets uploaded, I get an error saying that the file cannot be found. The code for my processor is below:
class Extractor < Processor
attr_accessor :resolution, :whiny
def initialize(file, options = {}, attachment = nil)
super
#file = file
#whiny = options[:whiny].nil? ? true : options[:whiny]
#basename = File.basename(#file.path, File.extname(#file.path))
#attachment = attachment
#instance = attachment.instance
end
def make
# do your conversions here, you've got #file, #attachment and #basename to work with
export_path = attachment.path.gsub('.zip', '_content')
Zip::ZipFile.open(attachment.path) { |zip_file|
zip_file.each { |image|
image_path = File.join(export_path, image.name)
FileUtils.mkdir_p(File.dirname(image_path))
unless File.exist?(image_path)
zip_file.extract(image, image_path)
# ..stuff that it does..
end
}
}
# clean up source files, but leave the zip
FileUtils.remove_dir(export_path)
# you return a file handle which is the processed result
dst = File.open result_file_path
end
end
And here is the contents of the error that I get:
Zip::ZipError in GalleriesController#create
File /home/joshua/railscamp/moments_on_three/public/assets/archives/delrosario.zip not found
Rails.root: /home/joshua/railscamp/moments_on_three
Application Trace | Framework Trace | Full Trace
config/initializers/extractor.rb:16:in `make'
app/controllers/galleries_controller.rb:32:in `new'
app/controllers/galleries_controller.rb:32:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"0s4L4MrlqjDTMjzjgkUdvUxeHklZNOIShDhT6fgOICY=",
"gallery"=>{"name"=>"DelRosario",
"public"=>"0",
"owner_id"=>"1",
"shoot_date(1i)"=>"2011",
"shoot_date(2i)"=>"1",
"shoot_date(3i)"=>"31",
"category_id"=>"1",
"archive"=>#<ActionDispatch::Http::UploadedFile:0x00000004148d78 #original_filename="delrosario.zip",
#content_type="application/zip",
#headers="Content-Disposition: form-data; name=\"gallery[archive]\"; filename=\"delrosario.zip\"\r\nContent-Type: application/zip\r\n",
#tempfile=#<File:/tmp/RackMultipart20110131-9745-14u347v>>},
"commit"=>"Create Gallery"}
From what I can tell it's looking for the file in the right place, but the file doesn't seem to be uploaded yet to access it. As far as I'm aware, Paperclip is smart enough to know and wait for the attachment to upload before it tries to process it. Can anyone spot what I'm doing wrong here?
Thanks a lot.
Old stuff:
I'm developing a photo gallery app using Rails 3 and Paperclip. The Admin is able to create a gallery and upload a zip file containing a bunch of images.
What I want to happen:
Enter gallery info and zip file to upload into the form.
Hit 'Create Gallery' button.
Form posts, gallery saves, and zip file gets uploaded.
After zip file is uploaded, run the method :extract_photos (btw, this code
works).
4.a. At the end of this method, zip file is destroyed.
Admin is redirected to gallery page with all the photos in it (where
gallery has_many photos).
I've tried to make this work several different ways.
Before, I created a controller method which would allow the Admin to click a link which ran the :extract_photos method. This worked on my computer, but for some reason the server had trouble routing this on the client's computer. So it's a no go. Plus I thought it was an ugly way of doing it.
Recently, I tried using callback methods. after_save didn't work because it apparently interrupts the form POST and the file doesn't get uploaded and the :extract_photos method can't find the file.
I checked out callback methods on the Paperclip github page, and it talks about the callbacks:
Before and after the Post Processing
step, Paperclip calls back to the
model with a few callbacks, allowing
the model to change or cancel the
processing step. The callbacks are
"before_post_process" and
"after_post_process" (which are called
before and after the processing of
each attachment), and the
attachment-specific
"beforepost_process" and
"afterpost_process". The callbacks are
intended to be as close to normal
ActiveRecord callbacks as possible, so
if you return false (specifically -
returning nil is not the same) in a
before filter, the post processing
step will halt. Returning false in an
after filter will not halt anything,
but you can access the model and the
attachment if necessary.
I've tried using before_post_process and after_post_process, but it can't find the file to run the process, so the file obviously isn't getting uploaded by the time those methods are getting called (which I think is strange). Additionally, when I try beforepost_process and afterpost_process, I get a NoMethodError.
So how do I call a method on an attachment when it is created or updated, but after the file is uploaded and in the right place?
UPDATE
I tried the code below, moving my extraction method code into the make method of the processor. I've gotten farther than I have did before with trying to write a processor, but it's still a no-go. The process throws an exception as soon as I try and open the uploaded file for processing, saying the file doesn't exist. The naming scheme is correct and everything, but still nothing is getting uploaded before the process is getting triggered. Does anyone have any idea why this is happening?
You can write your own processor to accomplish this.
in your model when declaring the paperclip stuff add a custom processor
has_attached_file :my_attachment, {
:styles => {:original => {:processors => [:my_processor]}}
}.merge(PAPERCLIP_SETTINGS)
then write your own processor and put it config/initializers:
module Paperclip
class MyProcessor < Processor
attr_accessor :resolution, :whiny
def initialize(file, options = {}, attachment = nil)
super
#file = file
#whiny = options[:whiny].nil? ? true : options[:whiny]
#basename = File.basename(#file.path, File.extname(#file.path))
#attachment = attachment
end
def make
# do your conversions here, you've got #file, #attachment and #basename to work with
# you return a file handle which is the processed result
dst = File.open result_file_path
end
end
end
I am using a custom processor to things similar to what you are doing with lots of processing and converting of the file in the middle and it seems to work well.