google_visualr chart rendering error - ruby-on-rails

i am trying Google-Visualr gem and got the above error.
As described here.
i installed the gem and in MyModel (we can use controller/model) i copied the demo code for line-chart from here.
i have a UserMailer,where i wanted to render html page along with my chart and using pdfkit i am converting rendered html to pdf.
class UserMailer < ActionMailer::Base
def my_report
#chart =MyModel.line_chart
html_data = render :template => "user_mailer/my_report"
kit = PDFKit.new(html_data,:page_size => 'Letter')
pdf = kit.to_pdf
end
in my my_report view i included
<script src='https://www.google.com/jsapi'></script>
in <head>
included this in <body> part
<div id='chart'></div>
<%= render_chart(#chart, 'chart') %>
But it is leading to me to undefined method "render_chart" error.
Any suggestion that how can i render chart with my html data?
where i am going wrong?
i am using rails 4
and 'google_visualr', '>= 2.1'

Related

Generating a PDF with Sidekiq & Wicked PDF: Undefined local variable or method for worker#

I've been trying to get PDF's generated via sidekiq and wicked_pdf in a rails 5.1 app but keep getting this error:
2017-11-01T02:20:33.339Z 1780 TID-ovys2t32c GeneratePdfWorker JID-b3e9487113db23d65b179b1c INFO: start
2017-11-01T02:20:33.369Z 1780 TID-ovys2t32c GeneratePdfWorker JID-b3e9487113db23d65b179b1c INFO: fail: 0.03 sec
2017-11-01T02:20:33.371Z 1780 TID-ovys2t32c WARN: {"class":"GeneratePdfWorker","args":[2,1],"retry":false,"queue":"default","jid":"b3e9487113db23d65b179b1c","created_at":1509502833.334234,"enqueued_at":1509502833.3345}
2017-11-01T02:20:33.380Z 1780 TID-ovys2t32c WARN: NameError: undefined local variable or method `quote' for #<GeneratePdfWorker:0x007fb6d5cea070>
Did you mean? #quote
2017-11-01T02:20:33.380Z 1780 TID-ovys2t32c WARN: /Users/stefanbullivant/quottes/app/workers/generate_pdf_worker.rb:18:in `perform'
I get this error even with no locals being passed in the av.render method. Any ideas on what's causing it are appreciated.
quotes_controller.rb calling the worker
def create_pdf
#quote = Quote.find(params[:id])
GeneratePdfWorker.perform_async(#quote.id, current_account.id)
redirect_to #quote
end
Generate_pdf_worker.rb
class GeneratePdfWorker
include Sidekiq::Worker
sidekiq_options retry: false
def perform(quote_id, account_id)
#quote = Quote.find(quote_id)
#account = Account.find(account_id)
# create an instance of ActionView, so we can use the render method outside of a controller
av = ActionView::Base.new()
av.view_paths = ActionController::Base.view_paths
# need these in case your view constructs any links or references any helper methods.
av.class_eval do
include Rails.application.routes.url_helpers
include ApplicationHelper
end
pdf = av.render pdf: "Quote ##{ #quote.id } for #{ #quote.customer_name }",
file: "#{ Rails.root }/tmp/pdfs/quote_#{#quote.id}_#{#quote.customer_name}.pdf",
template: 'quotes/create_pdf.html.erb',
layout: 'layouts/quotes_pdf.html.erb',
disposition: 'attachment',
disable_javascript: true,
enable_plugins: false,
locals: {
quote: #quote,
account: #account
}
# pdf_html = av.render :template => "quotes/create_pdf.html.erb",
# :layout => "layouts/quotes_pdf.html.erb",
# :locals => {
# quote: #quote,
# account: #account
# }
# use wicked_pdf gem to create PDF from the doc HTML
quote_pdf = WickedPdf.new.pdf_from_string(pdf, :page_size => 'A4')
# save PDF to disk
pdf_path = Rails.root.join('tmp', "quote.pdf")
File.open(pdf_path, 'wb') do |file|
file << quote_pdf
en
end
end
quotes_pdf.html.erb PDF Layout
<!DOCTYPE html>
<html>
<head>
<title>Quottes</title>
<meta charset="utf-8" />
<meta name="ROBOTS" content="NOODP" />
<style>
<%= wicked_pdf_stylesheet_link_tag 'quote_pdf' -%>
</style>
</head>
<body>
<div class="container">
<%= yield %>
</div>
</body>
</html>
create_pdf.html.erb PDF View (for the sake of getting things running first, just two lines using each local)
<%= account.brand_name %>
<%= quote.customer_name %>
Any advice on getting this running is much appreciated. I have played around with simply generating plain html text in the pdf view without passing any variables and still get this error so I'm confused as to what's causing it.
I sometimes forget about this as well - It seems like it's very insistent that line 18 (which I can only assume is render) is looking up the quote local and can't find it, and #quote is defined at that time. If that is all your code, then I would presume the changes are not being picked up.
My best suggestion (which I hope works) is you need to restart sidekiq!

wickedpdf not rendering images?

i am using wickedpdf gem to generate pdf invoice from the html code.
gems:
gem 'wicked_pdf'
gem "wkhtmltopdf-binary"
gemfile.lock
wicked_pdf (1.0.6)
wkhtmltopdf-binary (0.9.9.3)
in controller:
def show_pdf_invoice
respond_to do |format|
format.html { render :layout => "pdf.pdf.erb" }
format.pdf do
render pdf: "show_pdf_invoice", :layout => 'pdf.pdf.erb'
#render :pdf => "pdf"#, :layout => 'pdf.html.erb'
end
end
end
in views/invoices/show_pdf_invoice.pdf.erb
<img id="image" src="https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png" alt="logo" />
<%= wicked_pdf_image_tag 'https://www.google.co.in/logos/doodles/2016/holidays-2016-day-2-6356741311692800-scta.png' %>
pdf is getting generated. But the images are not showing. in the place of images empty boxes are coming. unable to find the issue.
I've had the same problem, mine was fixed by removing https for http. Have you tried this? and for the Amazon S3 part: You could use gsub for that as in: gsub("https", "http")
Using Rails 5.2 with Active Storage in combination with Amazon S3 storage I had the same problem.
In development on my local machine the images rendered perfectly, but on Heroku
they were presented as small empty rectangles.
To get the url from the logo uploaded to Active Storage I used: #my_object.logo.service_url.
Which used the standard url with https. As mentioned before, replacing this with http resolved the issue.
Full code used in my pdf generator view:
<%= wicked_pdf_image_tag #my_object.logo.service_url.gsub("https", "http") %>
Two Options
1. Upgrade to wkhtmltopdf 0.12.5.
-or-
2. Install libssl1.0-dev with apt-get install libssl1.0-dev.
See this issue for more information: https://github.com/wkhtmltopdf/wkhtmltopdf/issues/3001

Rails app hangs when using Wicked_pdf gem and wkhtmltopdf-binary-edge

I'm trying to print a PDF of my view by using the `'wicked_pdf' gem. This is the first time I use this gem. I've read the the documentation and googled around and I also found some simular questions here on Stack Overflow But nothing seems to do the trick.
I've validated the binaries ( see edit below) they are working fine, so the problem isn´t there.
I found two strange lines in the terminal when running rails s( See edit at the bottom)
I've been searching for a solution to this for three straight days, and can't figure this out.
Am I missing something here?
the server constantly hangs with that output in the terminal
Rendered pages/partials/_travel_part.html.erb (36.6ms)
Rendered users/show.html.erb within layouts/application (531.7ms)
Rendered layouts/_navbar.html.erb (2.6ms)
Rendered shared/_footer.html.erb (0.8ms)
Completed 200 OK in 1640ms (Views: 1115.4ms | ActiveRecord: 136.0ms)
"***************[\"/usr/local/bin/wkhtmltopdf\", \"-q\", \"file:////var/folders/sm/zwm8cy0x73qb6q1pq22r4bjh0000gn/T/wicked_pdf20160913-35465-hkw9b8.html\", \"/var/folders/sm/zwm8cy0x73qb6q1pq22r4bjh0000gn/T/wicked_pdf_generated_file20160913-35465-10go9dt.pdf\"]***************"
Below is what I have so far.
I want to print views/users/show.html.erb so in the users_controller.rb I have this code in the showmethod
def show
#user = User.find(params[:id])
#users = User.order('created_at DESC').paginate(page: params[:page], per_page: 30)
#paper = current_user.papers.build
#electro = current_user.electros.build
#hwater = current_user.hwaters.build
#cleaning = current_user.cleanings.build
#transport = current_user.transports.build
#papers = current_user.papers
respond_to do |format|
format.html {render layout:'application'}
format.pdf {render pdf:"test",javascript_delay:2000,
layout:'application',template:'users/show.pdf.erb'}
end
end
In the application.html.erbI have this in the head using the wicked pdf helper
<%= wicked_pdf_stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= wicked_pdf_javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= javascript_include_tag "http://www.google.com/jsapi"%>
<%= wicked_pdf_javascript_include_tag 'chartkick'%>
<%= csrf_meta_tags %>
The button in the views/users/show.html.erb is
<%= link_to 'Download Pdf', user_path(current_user, format: :pdf) %>
in the config/initializers/mime_types.rb I have this code
Mime::Type.register "application/pdf", :pdf
in the config/initializers/wicked_pdf.rb I have this code
WickedPdf.config = {
#:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
#:layout => "pdf.html",
:exe_path => '/usr/local/bin/wkhtmltopdf'
}
And in the gemfile.rb I have those two gems:
gem 'wicked_pdf', '~> 1.0', '>= 1.0.6'
gem 'wkhtmltopdf-binary-edge'
EDIT*
Ok I've Validated the binaries are working fine by typing this wkhtmltopdf google.com google in the terminal. So my conclusion is that the problem lies somewhere else than in the wkhtmltopdf. But where? I still can't find out...
(AddingWickedPdf) $ wkhtmltopdf google.com google
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
(AddingWickedPdf) $
ANOTHER EDIT
I noticed this lines in the terminal when I started my server rails s earlier to night, I don´t know what it means, but I'm sure it has something to do with the App hanging when rendering pdf:
/Users/dadi/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack-4.2.5/lib/action_dispatch/http/mime_type.rb:163: warning: already initialized constant Mime::PDF
/Users/dadi/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/actionpack- 4.2.5/lib/action_dispatch/http/mime_type.rb:163: warning: previous definition of PDF was here
It would be so great if someone could take a look at this and guide me to the right path here.
thanks in advance
DH
The answer was originally posted here:
How rails resolve multi-requests at the same time?
Subsequently adapted for this question here (Last answer):
PDFkit hangs when generating a pdf with an image

rails 4 with CKeditor

I cannot get the galetahub ckeditor gem to work with Rails 4 for me. I searched for any problems online but cannot find any. I'm following the instructions exactly.
I include gem "ckeditor" in my Gemfile
I include gem "carrierwave" and gem "mini_magick"
I run rails generate ckeditor:install --orm=active_record --backend=carrierwave
I run rake db:migrate
Inside application.rb I include config.autoload_paths += %W(#{config.root}/app/models/ckeditor)
Inside routes.rb I have mount Ckeditor::Engine => '/ckeditor'
I'm using SimpleForm so I paste the following ERB <%= f.input :description, as: :ckeditor %> in my view.
And I think that's it. But my text area does not convert to a CKeditor area for some reason.
STEP 1: Add gem 'paperclip' and gem "ckeditor" in your gemfile.
STEP 2: Bundle Install.
STEP 3: rails generate ckeditor:install --orm=active_record --backend=paperclip
STEP 4: Place config.autoload_paths += %W(#{config.root}/app/models/ckeditor) in application.rb
STEP 5: Place mount Ckeditor::Engine => "/ckeditor" if not present in routes.rb already and run db:migrate
STEP 6: Open application.html.erb and place this <%= javascript_include_tag 'ckeditor/ckeditor.js' %> in header.
STEP 7: Place this in footer(above the body tag) in application.html.erb
<script type="text/javascript">$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});</script>
STEP 8: Restart the WEBrick SERVER.
That's it.
Else
Download the CKEditor Zip file, extract the files and place them in the sub directory “javascripts/ckeditor”, add the main JS file to the layout..
javascript_include_tag 'ckeditor/ckeditor.js'
Place this in footer(above the body tag) in application.html.erb
<script type="text/javascript">$(document).ready(function() {
if ($('textarea').length > 0) {
var data = $('textarea');
$.each(data, function(i) {
CKEDITOR.replace(data[i].id);
});
}
});</script>
I have the same problem using rails 4 and apparently the problem is that the form helper
form.cktext_area
Or in your case
f.input :description, as: :ckeditor
it's not generating what it supposed to generate, and you don't have to load the editor manually, the only thing you need to do is to is to add the class 'ckeditor' to your textarea and it will load automatically, like this:
f.cktext_area :body, :class => 'ckeditor'
Meanwhile the Galetahub gem has been updated, but it has to be updated in your app manually. Read the github page: https://github.com/galetahub/ckeditor.
ajkumar basically answered the question well already, but if you are still lost, all you need to do is download the js file, include it in your html, have a script snippet included in the HTML to activate ckeditor on a certain textarea tag ID, and then change the class of the "textarea" tag you want to change to ckeditor. Quick sample below
<!DOCTYPE html>
<html>
<head>
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
The galetahub gem is currently broken on Rails 4. This one is working fine though: https://github.com/tsechingho/ckeditor-rails
In case you are having trouble making it work with active admin, make sure to put this:
config.register_javascript 'ckeditor/ckeditor.js'
config.register_javascript 'ckeditor/init.js'
Into config/initializers/active_admin.rb

Rails 3 Datatables JSON - aData undefined

I know that this question has been asked many times before, but due to my inexperience I am unable to correct the problem using those responses. I had it working in a previous Rails project and cannot see what has changed. I started a new project using PostgreSQL rather than MySQL and I am now using Rails 3.2.8 (was 3.2.1).
Firebug showing:
TypeError: aData is undefined at:
var aData = _fnGetObjectDataFn( oSettings.sAjaxDataProp )( json );
for ( var i=0, iLen=aData.length ; i<iLen ; i++ )
I gather that this is probably caused by Datatables not getting the correct JSON. A snippet shows below, which validates in JSONLint.
[{"code":"STATE 30","created_at":"2012-12-10T06:01:34Z","id":1,"name":"ALBANY HIGHWAY","rank":null,"state":"WA","updated_at":"2012-12-10T06:01:34Z"},{"code":"ANNE BEADELL HIGHWAY","created_at":"2012-12-10T06:01:34Z","id":2,"name":"ANNE BEADELL HIGHWAY","rank":null,"state":"SA","updated_at":"2012-12-10T06:01:34Z"},...
I see that it doesn't include iTotalRecords, iTotalDisplayRecords and aaData. Is this the problem? I presume the JSON options are set by the def as_json, buy I don't explicity reference that in my render ??. The http get (as seen in Firebug) includes sEcho but not iTotalRecords.
My code is based on RailsCasts #340:
Controller: ( see the list action).
class HighwaysController < ApplicationController
respond_to :html, :json
def index
#highways = Highway.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #highways }
end
end
def list
#highways = Highway.all
logger.debug "Highway Count: #{#highways.size}"
respond_to do |format|
format.html # index.html.erb
format.json { render json: HighwaysDatatable.new(view_context)}
end
end
Associated Ruby code:
class HighwaysDatatable
delegate :params, :h,:link_to,:number_to_currency,to: :#view
def initialize(view)
#view = view
end
def as_json(options = {})
{
sEcho: params[:sEcho].to_i,
iTotalRecords: Highway.count,
iTotalDisplayRecords: highways.total_entries,
aaData: data
}
end
private
def data
highways.map do |highway|
[
h(highway.id),
h(highway.name),
h(highway.state),
h(highway.code),
h(highway.rank),
h(highway.created_at),
h(highway.updated_at)
]
end
end
def highways
#highways ||= fetch_highways
end
def fetch_highways
... (as per RailsCasts code - code wrapped and did not show properly)
end
highways
end
def page
params[:iDisplayStart].to_i/per_page + 1
end
def per_page
params[:iDisplayLength].to_i > 0 ? params[:iDisplayLength].to_i : 10
end
def sort_column
columns = %w[name state code rank]
columns[params[:iSortCol_0].to_i]
end
def sort_direction
params[:sSortDir_0] == "desc" ? "desc" : "asc"
end
end
and the list view:
<% #page_title = "Highways List" %>
<h2>Highways</h2>
<%= javascript_tag do %>
window.highwaysURL = '<%= j highways_url %>';
<% end %>
<div id="EditLink">
<%= link_to "Edit Highway", :controller => :highways, :action => :edit, :id => 1 %>
</div>
<div>
</br>
<%= link_to 'Neighbours', '/neighbours/' %>
<%= link_to 'Localities', '/localities/' %>
</br>
</div>
<div id="tools">
</div>
<table id="highways" class="display" data-source="<%= highways_url(format: "json") %>">
<thead>
<tr>
<th>Id</th>
<th>Highway</th>
<th>State</th>
<th>Code</th>
<th>Rank</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div id=editarea class='result' ></div>
My gemfile (with comments removed):
source 'https://rubygems.org'
gem 'rails', '3.2.8'
gem 'pg'
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.1'
gem 'uglifier', '>= 1.0.3'
end
gem 'libv8', '~> 3.11.8'
gem 'therubyracer', require: 'v8'
gem 'jquery-rails'
gem 'will_paginate'
gem 'debugger'
and application.js for Asset Pipeline:
//= require jquery
//= require jquery-ui
//= require jquery.dataTables
//= require TableTools
//= require ZeroClipboard
//= require datatable_highways
//= require datatable_localities
//= require datatable_neighbours
//= require_tree .
It's probably something simple, but it has been holding me up for some time. Thanks in anticipation.
UPDATE
The DataTables debugger bookmarklet indicates that the 'list' view is rendering the following which does not include the json parameters expected by DataTables.
http://localhost:3000/highways.json
and I believe it should be:
http://localhost:3000/highways/list.json.
I am not sure if this is a controller or a view problem.
UPDATE
I have made various changes but still have the same problem. BUT I see two things in the log which are significant:
Entering localhost:3000/highways/list shows that 2 views are rendered.
Processing by HighwaysController#list as HTML [1m[36mHighway Load (4.8ms)[0m [1mSELECT "highways".* FROM "highways" ORDER BY name
Highway Count: 229
Rendered highways/list.html.erb within layouts/highways (32.6ms)
then
Processing by HighwaysController#index as JSON
Parameters: {"sEcho"=>"1", "iColumns"=>"5", "sColumns"=>"", "iDisplayStart"=>"0",...
The first is HTML (via action 'list') the second as JSON (via action 'index').
So there are two problems:
The first render has an associated data request which causes an
'already initialised' warning from DataTables, and
My routes.rb explicit match statement is catching the HTML to render
the view, but the JSON response (from the AJAX call for the data rows) falls through
and is handled by resources :highways and it then uses the 'index'
action in the controller
routes.rb
match 'highways/list'=> 'highways#list'
...
resources :highways
How do I stop the data request when I just want the view (column headings etc) rendered?
What route do I need to send the JSON response to the 'list' action in the controller?
Resolved. Went back to a minimal set up, 1 table using Ryan Bates #340 code - so using index action/view to get around the 2 render issue above. Still not working. Removed gem to rweng github and loaded DataTables files to ./vendor/assets. Now works. The index or list action can probably be fixed with an explicit route, but I could not get past 'missing template' when I tried to coerce it through the list action.

Resources