send_data or send_file(ruby) not working in safari browser? - ruby

I used following code to send or downlaod file at client's browser.
That is perfectly working in all browser BUT in safari after clicking on link when i refresh the page it makes my session nil.
def export_csv
csv = CSV.generate(:force_quotes => true) do |line|
line <<["Employee Code", "Name", "Status", "Skills"]
end
send_data csv,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=EmployeeSkillsData-#{Time.now.strftime('%d-%m-%y--%H-%M')}.csv"
end
I tried this code with some other application also but result is same.
Please help to resolve this.
Thanks.

send_data csv,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "inline", # optional
:filename=>"EmployeeSkillsData-#{Time.now.strftime('%d-%m-%y--%H-%M')}.csv"

Related

Rspec is different from the app

I'm currently working on a Ruby/Sinatra App and now I'm stuck because my rspec testing is not working properly on the controller. But when I tried my API using curl or web the code just works!.
Here are my file, spesificly on that line of code
listproduct_controller.rb
get '/' do
products = Product.all
payload = []
products.each do |product|
payload.push({ :exhibit_name => product.exhibit_name, :icon => product.icon })
end
return {
:status => 'SUCCESS',
:message => 200,
:payload => payload
}.to_json
end
and here are my spec file
listproduct_controller_spec.rb
context "GET to /products" do
before { allow(Product).to receive(:all) }
before { allow(Product).to receive(:find_by) }
it "returns status 200 OK" do
get '/'
puts(last_response)
expect(last_response).to be_ok
end
it "show a list of product's name and its icon" do
get '/'
#products = Product.all.to_a
expect(last_response.body).to include_json(#products)
end
end
When I puts the last_response on spec it shows this
500
{"Content-Type"=>"text/html", "Content-Length"=>"212150"}
#<Rack::BodyProxy:0x0000000480b1d8>
but when im using curl or apps it just works and return
200 status code with the payload
Can anyone help me what I did wrong?
UPDATE :
I solved it, it was the problem on the database, where all the product in the development database were not on the test database so it returns 500 of empty database.

convert embedded ruby file to PDF file instead of only HTML file using Rails 3

I want to convert my embedded ruby file to PDF file after clicking on a link using Rails 3.I became able to convert simple html file to PDF file using pdfkit gem.I am explaining my code below.
users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
#html = render_to_string(:action => "/users/download_pdf.html.erb")
#kit = PDFKit.new('http://google.com')
#kit = PDFKit.new(html)
#send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
kit = PDFKit.new("<h1>Hello</h1><p>This is PDF!!!</p>", :page_size => "A4")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
#file = kit.to_file('my_file_name.pdf')
end
end
In this controller page i did and got success to convert from HTML to PDF.
users/index.html.erb:
<p>
<%= link_to "Download pdf",download_pdf_path(:format => 'pdf') %>
</p>
When user will click on the above "download_pdf" link the download.html.erb will convert to PDF file and it should display as well as download in specified folder.The download.html.erb file is given below.
users/download.html.erb:
<h1>Hello Rails</h1>
The above file should convert into PDF file with proper css .If i have css for this like below.
application.css:
h1{
width:100px;
height:100px;
background-color:red;
}
How can i include this CSS in that PDF file.My other files are given below.
pdfkit.rb:
PDFKit.configure do |config|
#config.wkhtmltopdf =Rails.root.join('bin', 'wkhtmltopdf-i386').to_s
config.wkhtmltopdf='C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
#config.default_options[:ignore_load_errors] = true
end
Please help me to resolve this issue and make this successfully.
By using wicked_pdf gem i am getting the following error.
error:
RuntimeError in UsersController#download_pdf
Error: Failed to execute:
["C:/wkhtmltopdf/bin/wkhtmltopdf.exe", "file://C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html", "C:/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf_generated_file20150527-3204-59mbli.pdf"]
Error: PDF could not be generated!
Command Error: Loading pages (1/6)
[> ] 0%
[======> ] 10%
Error: Failed loading page file://c/DOCUME~1/SUBHRA~1/LOCALS~1/Temp/wicked_pdf20150527-3204-calx6j.html (sometimes it will work just to ignore this error with --load-error-handling ignore)
Exit with code 1 due to network error: ContentNotFoundError
check the below code for this gem.
users/users_controller.rb:
class UsersController < ApplicationController
def index
end
def download_pdf
render pdf: 'test',
layout: '/layouts/test',
template: '/users/test',
handlers: [:erb],
formats: [:pdf],
:save_to_file => Rails.root.join('public', "test.pdf")
end
end
wicked_pdf.rb:
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => 'C:/wkhtmltopdf/bin/wkhtmltopdf.exe'
}
You can include your stylesheets by following:
def download_pdf
kit = PDFKit.new(File.open(Rails.root.join('app', 'views', 'users', 'download.html.erb')))
kit.stylesheets << Rails.root.join("app","assets","application.css")
send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline')
end

Ruby - Webmock: Match URI using regular expression

I'm working with rspec and webmock and I'm looking into stubbing request. I do have a problem when I try to use regex to match the URI.
Everything was working fine when I used the stub below, without matching a specific URI (/.*/)
it "returns nil and stores an error when the response code is not OK" do
stub_request(:get, /.*/).
with(
:headers => insertion_api.send(:default_headers, false).merge('User-Agent'=>'Ruby'),
:body => {}
).
to_return(
:status => Insertion.internal_server_error.to_i,
:body => "{\"message\": \"failure\"}",
:headers => { 'Cookie' => [session_token] }
)
expect(insertion_api.get_iou(uid)).to be_nil
expect(insertion_api.error).to eq("An internal server error occurred")
end
Since I want to be more specific in my test to improve readability, if I try to match a this specific URI:
/insertion_order/012awQQd?fields=name,type&depth=4
using the stub below:
it "returns nil and stores an error when the response code is not OK" do
stub_request(:get, %r{insertion_order/\w+\?fields\=[\w,]+\&depth\=[0-9]}).
with(
:headers => insertion_api.send(:default_headers, false).merge('User-Agent'=>'Ruby'),
:body => {}
).
to_return(
:status => Insertion.internal_server_error.to_i,
:body => "{\"message\": \"failure\"}",
:headers => { 'Cookie' => [session_token] }
)
expect(insertion_api.get_iou(uid)).to be_nil
expect(insertion_api.error).to eq("An internal server error occurred")
end
running the test I've got:
WebMock::NetConnectNotAllowedError:
Real HTTP connections are disabled. Unregistered request: GET https://mocktocapture.com/mgmt/insertion_order/0C12345678 with body '{}' with headers {'Accept'=>'application/vnd.xxx.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'}
You can stub this request with the following snippet:
stub_request(:get, "https://mocktocapture.com/mgmt/insertion_order_units/0C12345678").
with(:body => "{}",
:headers => {'Accept'=>'application/vnd.dataxu.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'}).
to_return(:status => 200, :body => "", :headers => {})
registered request stubs:
stub_request(:get, "/insertion_order\/\w+\?fields\=[\w,]+\&depth\=[0-9]/").
with(:body => {},
:headers => {'Accept'=>'application/vnd.xxx.mgmt+json; version=2.0', 'Cookie'=>'y0Urv3ryLon6s3cur1tYT0k3ng0zeh3r3', 'User-Agent'=>'Ruby'})
The regex I've used is correct, but I don't understand why I've got this error message.
The request you got is :
https://mocktocapture.com/mgmt/insertion_order/0C12345678
You have given the regexp :
%r{insertion_order/\w+\?fields\=[\w,]+\&depth\=[0-9]}
In the regexp you have specified with the "\?" that it is mandatory that the request should contain "?" (or a query) after "insertion_order/\w+". In the request you got there aren't any query parameters. That's why it isn't matching the request.
One way you can fix that is to make the part that comes after "insertion_order/\w+" in the regexp optional. I would do it like this :
%r{insertion_order/\w+(\?fields\=[\w,]+\&depth\=[0-9])?}

How can I upload files to Redmine via ActiveResource / REST API?

I am trying to batch-upload images to Redmine and link them each to a certain wiki pages.
The docs (Rest_api, Using the REST API with Ruby) mention some aspects, but the examples fail in various ways. I also tried to derive ideas from the source - without success.
Can anyone provide a short example that shows how to upload and link an image from within Ruby?
This is a bit tricky as both attachments and wiki APIs are relatively new, but I have done something similar in the past. Here is a minimal working example using rest-client:
require 'rest_client'
require 'json'
key = '5daf2e447336bad7ed3993a6ebde8310ffa263bf'
upload_url = "http://localhost:3000/uploads.json?key=#{key}"
wiki_url = "http://localhost:3000/projects/some_project/wiki/some_wiki.json?key=#{key}"
img = File.new('/some/image.png')
# First we upload the image to get attachment token
response = RestClient.post(upload_url, img, {
:multipart => true,
:content_type => 'application/octet-stream'
})
token = JSON.parse(response)['upload']['token']
# Redmine will throw validation errors if you do not
# send a wiki content when attaching the image. So
# we just get the current content and send that
wiki_text = JSON.parse(RestClient.get(wiki_url))['wiki_page']['text']
response = RestClient.put(wiki_url, {
:attachments => {
:attachment1 => { # the hash key gets thrown away - name doesn't matter
:token => token,
:filename => 'image.png',
:description => 'Awesome!' # optional
}
},
:wiki_page => {
:text => wiki_text # original wiki text
}
})

Favicon not showing with camping

I want to learn about webapps. I decided to learn by doing and chose to start simple with Camping as (i). it is small & (ii). i know some ruby.
The favicon is not showing. I am using a favicon taken from another site so it know its file format is valid.
Here is the code from the controller.
class Favicon < R '/favicon\.ico'
# Load the favicon into memory
FAVICON = File.read('favicon.ico')
def get
#headers['Content-Type'] = "image/x-icon"
FAVICON
end
end
Here is the code from the view:
I purposely placed a link to the favicon twice as an experiment. No joy.
def layout
html do
head do
title 'Custom Made Kameez'
link :rel => 'icon', :href => 'favicon.ico', :type => 'image/x-icon'
link :rel => 'shortcut icon', :href => 'favicon.ico', :type => 'image/x-icon'
link :rel => 'stylesheet', :type => 'text/css', :href => '/styles.css', :media => 'screen'
end
I have tried clearing my cache and using Firefox and IE, same issue.
Two problems as far as I can see.
You should use an absolute path to the favicon:
link :rel => 'icon', :href => '/favicon.ico', :type => 'image/x-icon'
You should read the file as binary:
FAVICON = File.binread('favicon.ico')
I took your code and it worked just fine, and that was before I uncommented the link directives: browsers are just really keen to go get /favicon.ico .
Is your problem the fact that your favicon never showed in the first place, or that your original favicon is now stubbornly refusing to change?

Resources