I got an strange issue with my experiments with ERB. Here what code do I have:
# cat ./services_lbs2.erb
<%= def renderVip(description, template)
puts "zxc dfg"
end
%>
# locally and remote
Printing: <%= renderVip('123','456') %>
And here what I am getting in the irb:
irb(main):034:0> #template=File.read('./services_lbs2.erb')
=> "<%= def renderVip(description, template)\nputs \"zxc dfg\"\nend\n%>\n# locally and remotely monitored (all externals)\nPrinting: <%= renderVip('123','456') %>\n"
irb(main):035:0> zxc = ERB.new(#template,nil, "-")
=> #<ERB:0x00000000068d4d88 #safe_level=nil, #src="#coding:US-ASCII\n_erbout = String.new; _erbout.concat(( def renderVip(description, template)\nputs \"zxc dfg\"\nend\n).to_s); _erbout.concat \"\\n# locally and remotely monitored (all externals)\\nPrinting: \"\n\n; _erbout.concat(( renderVip('123','456') ).to_s); _erbout.concat \"\\n\"\n; _erbout.force_encoding(__ENCODING__)", #encoding=#<Encoding:US-ASCII>, #frozen_string=nil, #filename=nil, #lineno=0>
irb(main):036:0> zxc.result(binding)
zxc dfg
=> "renderVip\n# locally and remotely monitored (all externals)\nPrinting: \n"
I could not get the output like:
# locally and remotely monitored (all externals)\nPrinting: zxc dfg\n
Why is it so and how it can be fixed?
Thanks!
The return value puts function is nil so in your case, the method will return nil.
So after execution nil is being appended inside the body tag. For this to work change it to
<%
def renderVip(description, template)
"zxc dfg"
end
%>
Related
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!
i have a class to import
import_jobs.rb
require 'roo'
class ImportJob < Struct.new(:path, :name)
def perform
import(path, name)
end
#
def import(path, name)
spreadsheet = open_spreadsheet(path, name)
header = spreadsheet.row(1).map!(&:downcase)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose].to_hash
potential_user = PotentialUser.find_by_id(row[:id]) || PotentialUser.new
potential_user.attributes = row
potential_user.save!
end
end
#
def open_spreadsheet(path,extname)
case extname
when ".csv" then Roo::CSV.new(path)
when ".xls" then Roo::Excel.new(path)
when ".xlsx" then Roo::Excelx.new(path,file_warning: :ignore)
else raise "Unknown file type: extname"
end
end
end
In my View
<%= form_tag import_potential_users_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
In controller
def import
if params[:file].present?
Delayed::Job.enqueue ImportJob.new(params[:file].path, File.extname(params[:file].original_filename))
redirect_to potential_users_path, notice: "Protential Users imported."
else
redirect_to potential_users_path
end
end
When in run jobs, it display error does not exits file . Althought when i run it dont use delay_job, code ís working
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=860) RUNNING
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=860) COMPLETED after 2.0222
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=858) RUNNING
[Worker(host:ubuntu pid:14362)] Job ImportJob (id=858) FAILED (3 prior attempts) with IOError: file /tmp/RackMultipart20151211-14238-13b7xb does not exist
[Worker(host:ubuntu pid:14362)] 2 jobs processed at 0.7092 j/s, 1 failed
Looks like temporary file is removed prior to the moment when the worker starts to process the job. I'd suggest you to copy the file to another location and then try again. Here's a chunk of code that might help:
if params[:file].present?
original_filename = params[:file].original_filename
new_filename = "#{File.basename(original_filename)}_new"
new_filepath = File.join(Dir.tmpdir, new_filename)
FileUtils.cp(params[:file].path, new_filepath)
import_job = ImportJob.new(new_filepath, File.extname(original_filename))
DelayedJob.enqueue(import_job)
...
I am trying to show show this as a formatted phone number like: xxx-xxx-xxxx instead of just a number string like it currently is ..any help would be great!
<% if #post.phone.present? %>
<h4>Phone: <small> <%= #post.phone %><br></h4>
<% end %>
You can use number_to_phone helper, like this:
<% if #post.phone.present? %>
<h4>Phone: <small> <%= number_to_phone #post.phone %><br></h4>
<% end %>
By default, it formats the phone number as xxx-xxx-xxxx :
2.1.1 :009 > number_to_phone(1235551234)
=> "123-555-1234"
2.1.1 :010 > number_to_phone("1235551234")
=> "123-555-1234"
Use the phone gem. https://github.com/carr/phone
pn = Phoner::Phone.parse('+385915125486')
pn.to_s # => "+385915125486"
pn.format("%A/%f-%l") # => "091/512-5486"
pn.format("+ %c (%a) %n") # => "+ 385 (91) 5125486"
pn.format(:europe) # => "+385 (0) 91 512 5486"
pn.format(:us) # => "(234) 123-4567"
pn.format(:default_with_extension) # => "+3851234567x143"
I "inherited" a rails aplication running with ruby 1.8.7 in development.
I have a wice_grid table which I'm trying to export in CSV and in development all goes perfect.
When I push it to production, i get the following error:
uninitialized constant CSV::Writer
The production machine is running Ruby 1.9.1 and from what I read, I suppose the problem comes from there.
I've tried to put:
required 'csv'
In the controller or the model, but nothing happens, development works, production does not.
Here is the controller code:
def index
require 'csv'
#service_requests = initialize_grid(ServiceRequest,
:name => "solicitudes",
:order => "created_at" ,
:order_direction => 'desc',
:include => [:user, :service],
:enable_export_to_csv => true,
:csv_file_name => 'Listado de Solicitudes'
)
export_grid_if_requested('solicitudes' => 'service_requests') do
#Si se pulsa en exportar se exportan todos las celdas de la tabla seleccionada (con filtros aplicados)
end
end
Here is the part of the view, which calls a partial:
<%= render :partial => 'service_requests' %>
Here is the partial, cropped for making the question not too long:
<%= grid(#service_requests, :show_filters => :always) do |service_request|
[...]
service_request.column :column_name => 'Nombre' , :attribute_name => 'name', :model_class => User do |sr|
sr.user.name
end
service_request.column :column_name => 'Apellidos' , :attribute_name => 'lastName' , :model_class => User do |sr|
sr.user.lastName
end
[...]
end %>
I read this thread but didnt help me much: write csv in ruby 1.9 and CSV::Writer
Thank you all in advance!
Somewhere, that you haven't posted, you are referencing CSV::Writer. This works locally because you're using Ruby 1.8.7, but your production server is using Ruby 1.9.1. CSV::Writer was deprecated with Ruby 1.9.
From the the docs:
# * The old CSV's Reader and Writer classes have been dropped.
Step one is to upgrade your local Ruby to the same version as the server. This will give you the same error locally, which should go away once you find and remove that CSV::Writer.
The CSV docs give examples of how to use the current CSV class to accomplish what CSV::Writer used to do. Here's an example:
# == Writing
#
# === To a File
#
# CSV.open("path/to/file.csv", "wb") do |csv|
# csv << ["row", "of", "CSV", "data"]
# csv << ["another", "row"]
# # ...
# end
Upgrading Ruby will probably raise other errors. But Ruby 1.8.7 was retired in 2013 so these are problems you're going to want to fix now rather than later.
Good luck!
I have a Rails app (2.3.8) where I send emails using ActionMailer from my Controllers, with no problems.
However, I´ve created a rake task to be called from a Cronjob (in Heroku). When those emails are sent, no locale transformations in my dates are made.
I´ve googled to find any kind of solution, but couldn´t.
Anyone can help me?
Thanks.
Here is the code:
cron.rake:
desc 'This task is called by the Heroku cron add-on'
task :cron => :environment do
puts 'Sending diary...'
hollydays = [6,0] #weekend
unless hollydays.member?(Time.zone.now.wday) #if is NOT a weekend
User.all.each do |user|
user.deliver_task_diary
end
end
puts 'done.'
end
user model method:
def deliver_task_diary
TaskMailer.deliver_task_diary(self)
end
the method in TaskMailer model:
def task_diary(user)
next_five_tasks = user.next_five_tasks
last_five_tasks = user.last_five_tasks
recipients "#{user.name} <#{user.email}>"
from "My site <no_reply#mysite.com>"
subject "Your daily tasks."
sent_on Time.zone.now
body :user => user, :next_five_tasks => next_five_tasks, :last_five_tasks => last_five_tasks
end
part of my email template that doesn´t locale:
<%=l task.estimated_delivery_date, :format => :short %>
Solved.
I don´t know if it´s the best way, but I´ve just declared the locale at the very beging of the email html template:
<% I18n.locale = "pt-BR" %>