last element of the hash - ruby-on-rails

I am sending several parameters for the printing of tickets in pdf
Parameters: {"utf8"=>"✓", "list"=>{"client_0801541"=>"0801541", "client_0801554"=>"0801554", "client_0801554"=>"0801554"}, "subaction"=>"print selected clients"}
I need to print each client on a different page, for this I use a start_new_page at the end of showing the client's code, but in that way after the last client leaves a blank page. How could I make it so that for each client it verifies if it is the last one of the array? I have tried the following:
def client
#client.each do |(c,client_id)|
draw_text "#{client_id}", :at => [0,22], :size => 5, :style => :bold
start_new_page unless client_id == #client.map{|e|[e.c, e.client_id]}.client_id.last
end
end

You can try:
#clients.each do |(c, client_id)|
draw_text "#{client_id}", :at => [0,22], :size => 5, :style => :bold
start_new_page unless client_id == #clients.values.last
end
You could also try:
#clients.each_with_index do |(c, client_id), i|
draw_text "#{client_id}", :at => [0,22], :size => 5, :style => :bold
start_new_page unless i == #clients.length - 1
end
As Tadman suggests, you could also speed this up by doing:
def client
#clients_length = #clients.length - 1
#clients.each_with_index do |(c, client_id), i|
draw_text "#{client_id}", :at => [0,22], :size => 5, :style => :bold
start_new_page unless i == #clients_length
end
end
Your original code:
def client
#client.each do |(c,client_id)|
draw_text "#{client_id}", :at => [0,22], :size => 5, :style => :bold
start_new_page unless client_id == #client.map{|e|[e.c, e.client_id]}.client_id.last
end
end
Seems banged up, minimally, because:
You're using map on every iteration, which seems wasteful.
In #client.map{|e|[e.c, e.client_id]}, .c and .client_id aren't methods on Array.
.client_id isn't a method on Array.
Probably other stuff.
BTW, last two keys and values in your list are identical. I don't know if that's an error. But, if that's what you intend, then you may have other problems.
Also BTW, the title of your question says 'last element of the array', but you're working with a hash, not an array.

Related

Ruby on Rails Roo Import Excel Return NIL

So, I am developing an Ruby on Rails website to import an Excel file into our website. I followed RailsCasts and using Roo gem. All are working, but when the import process done, all fields are nil. When I checked with raise, I found out that the data is nil.
def self.import(file)
spreadsheet = open_spreadsheet(file)
header = spreadsheet.row(1)
(2..spreadsheet.last_row).each do |i|
row = Hash[[header, spreadsheet.row(i)].transpose]
product = find_by_id(row["id"]) || new
product.attributes = row.to_hash.slice(*accessible_attributes)
product.save!
end
end
When I raised row, I got whole data from Excel. But when I raised product, I got nil. How I can put the data correctly so I can get all value correctly? Thank you.
So, after did some practices, I found out that on first test, it was a hash, so what I need to make it work is actually simple but I am not sure if this is the best practice. If someone have a better practice, it will be a good thing, but this is my solution for now.
object = Lead.new(
:first_name => row['First Name'], :last_name => row['Last Name'],
:address => row['Address'], :city => row['City'],
:state => row['State'], :county => row['County'],
:zip_code => row['Zip Code'], :bedrooms => row['Bedrooms'], :bathrooms => row['Bathrooms'],
:last_sale_date => row['Last Sale Date'], :amount_sold => row['Amount Sold'],
:tax_value => row['Tax Value'], :tax_name => row['Tax Name'], :tax_address => row['Tax Address'],
:tax_city => row['Tax City'], :tax_state => row['Tax State'], :tax_postal_code => row['Tax Postal Code'],
:listing_status => row['Listing Status'], :property_type => row['Property Type'],
:square_footage => row['Square Footage'], :days_on_market => row['Days on Market'], :list_date => row['List Date'],
:status_change_date => row['Status Change Date'], :year_built => row['Year Built'],
:mls_id => row['MLS ID'], :last_call_result => row['Last Call Result'], :last_dial_date => row['Last Dial Date'],
:last_contacted => row['Last Contacted'], :last_dial_time => row['Last Dial Time'], :create_date => row['Create Date'],
:edit_date => row['Edit Date'], :source => row['Source'], :list => row['List'],
:call_attempts => row['Call Attempts'], :family_member => row['Family Member'], :notes => row['Notes'],
:group => row['Group'], :manager => row['Manager']
)

Getting Internal Server Error when trying to create a payment through PayPal

This is a "Now it's working now it's not" situation
Everything was working just fine with PayPal sandbox and now it's giving me the following error
Internal Server Error
The server encountered an internal error or misconfiguration and was unable
to complete your request.
Please contact the server administrator, webmaster#paypal.com and inform
them of the time the error occurred, and anything you might have done that
may have caused the error.
More information about this error may be available in the server error log.
this is my cart.rb
def paypal_url(return_url,notify_url)
values = {
:business => 'seller5#myseelingwebsite.com',
:cmd => '_cart',
:upload => 1,
:return => return_url,
:invoice => id,
:notify_url => notify_url,
:cert_id => "4VA2YEE757V8A"
}
shopping_cart_items.each_with_index do |item, index|
values.merge!({
"amount_#{index+1}" => (item.price_cents/100),
"item_name_#{index+1}" => Product.find(item.item_id).name,
"item_number_#{index+1}" => item.item_id,
"quantity_#{index+1}" => item.quantity
})
end
encrypt_for_paypal(values)
end
PAYPAL_CERT_PEM = File.read("#{Rails.root}/certs/paypal_cert.pem")
APP_CERT_PEM = File.read("#{Rails.root}/certs/app_cert.pem")
APP_KEY_PEM = File.read("#{Rails.root}/certs/app_key.pem")
def encrypt_for_paypal(values)
signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM),
OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''),
values.map { |k, v| "#{k}=#{v}" }.join("\n"),
[],
OpenSSL::PKCS7::BINARY)
OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)],
signed.to_der,
OpenSSL::Cipher::Cipher::new("DES3"),
OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "")
end
my redirecting view
<%= form_tag "https://www.sandbox.paypal.com/cgi-bin/webscr", :id =>
'checkoutform' do %>
<%= hidden_field_tag :cmd, "_s-xclick" %>
<%= hidden_field_tag :encrypted,
#cart.paypal_url("http://www.mywebsite.com",
payment_notifications_url(:secret => "secretcode")) %>
<% end %>
I went through everything step by step and I got nothing
I'm getting the same error from PayPal sandbox with an encrypted button. I did not change my code either and it was working two or three weeks ago. But now I get the same error as you. It looks like PayPal doesn't really care much about fixing their Sandbox. They put a low priority on it. I suggest you open a ticket with them. The only way they will address this if enough customers complain.

Iterating through columns on active_admin model

New to Ruby and Rails, so perhaps I'm not searching/asking this the right way. I'm using the ActiveAdmin gem and want to turn this:
column :purchase_price, :sortable => :purchase_price do |piece|
div :class => "price" do
number_to_currency piece.purchase_price
end
end
column :appraised_value, :sortable => :appraised_value do |piece|
div :class => "price" do
number_to_currency piece.appraised_value
end
end
column :sale_price, :sortable => :sale_price do |piece|
div :class => "price" do
number_to_currency piece.sale_price
end
end
into this:
price_array = [:purchase_price, :appraised_value, :sale_price]
price_array.each do |p|
column p, :sortable => p do |piece|
div :class => "price" do
number_to_currency piece.p
end
end
end
...in the interest of DRY.
The longer solution works, but the shorter one gives a "NoMethodError in Admin::Pieces#index" and I'm kind of at a loss as to what's wrong. Any suggestions?
As house9 said, my problem was that I tried calling piece.p when really it should be piece.send(p). Still not exactly sure why you can't just replace all instances of p with the iterator loop like I did originally but maybe someone else can explain.
In any case, thank you!

Ruby PDF Label Printer New Line Not Working

Please be patient with me, this is the first time that I have ever messed with Ruby. Basically here is my issue. I have a huge site that is just needing a single thing modified however I'm running into issues.
I am trying to get a PDF output for a lapel printer to wrap down to the next line. Here is my code.
def print_labels
quantity = params[:quantity].to_i
hashed_label = ActiveSupport::JSON.decode(params[:label])
p = InventoryItem.labels_pdf do |pdf|
(1..quantity).each do |i|
pdf.text("#{hashed_label['inventory_item_code']} #{hashed_label['label_description']} #{hashed_label['inventory_item_size']}", :style => :bold)
pdf.text("#{hashed_label['ingredients']}", :size => 9, :font => :serif)
#pdf.text(params[:label]);
pdf.start_new_page if i < quantity
end
end
send_data(p, :type => "application/x-pdf", :filename => "labels.pdf")
end
Here is the output in the PDF.
inventory_item_code label_description inventory_item_size
I am trying to get them to break between each item.
Is this using Prawn? You should be able to put newlines in all you want:
pdf.text("Here is some\ntext with\nnewlines")
So, a newline after the ingredients would just be:
pdf.text("#{hashed_label['ingredients']}\n", :size => 9, :font => :serif)

On the fly tags generation for XML Builders

I have a hash like,
object = { :type => 'book', :name => 'RoR', :price => 33 }
OR
object = { :type => 'wig', :name => 'Elvis-Style', :price => 40, :color => 'black' }
The problem is that keys in above hash may be different all the time or even increase and decrease depending upon the object type.
What I want to do generate XML for above hashes using Xml::Builder. The XML tags are decided by the keys in the hash and text inside a tag is value corresponding that key.
I can use eval to do this like below. However, I think there must be a better way to do it.
object.each do |key, text|
eval("xml.#{key.to_s} do
#{text}
end
")
end
#object.each do |k, v|
xml.tag!(k.to_s, v)
end
Rails supports to_xml on Hash classes.
hash = { :type => 'book', :name => 'RoR', :price => 33 }
hash.to_xml
# Returns
# <?xml version=\"1.0\" encoding=\"UTF-8\"?>
# <hash>
# <type>book</type>
# <name>RoR</name>
# <price type=\"integer\">33</price>
# </hash>
If you want to skip the types then:
hash.to_xml(:skip_types => true)
If you want to give a different root then:
hash.to_xml(:root => 'options')
This one worked.
#object.each do |k, v|
xml.tag!(k.to_s, v)
end
out << "<#{key}>#{html_escape(value)}</#{key}>"

Resources