Replace transpose method? - ruby-on-rails

I have the following code:
table([
["UnitID", "First Name", "NPS Score", "Comments"],
*[invite_unitid_arr, invite_name_arr, nps_score_integers_final, comment_arr]
.transpose.reject{ |x| x[3].empty? }
], :position => :center, :column_widths => {0 => 50, 1 => 60, 2 => 60, 3 => 40, 4 => 150}) do
row(0).style :background_color => 'C0C0C0'
end
I am calling transpose on an array of arrays. I am refactoring this code and I now have an array of model objects:
array = Model.all
How can I rewrite the above, saying "Loop through each model (Model1, Model2, etc.) and create a row with the attributes unit_id,first_name,nps_score,comment like so: Model1[:unit_id],Model1[:first_name],Model1[:nps_score],Model1[:comment]"

If I understand correctly, you have an array of objects like this:
my_models = [ <MyModel id: 1, unit_id: 123, first_name: "Xxx", nps_score: 100, ...>,
<MyModel id: 2, unit_id: 456, first_name: "Yyy", nps_score: 200, ...>,
...
]
And you want an array like this:
[ [ "UnitID", "First Name", "NPS Score", "Comments" ],
[ 123, "Xxx", 100, "..." ],
[ 456, "Yyy", 200, "..." ],
...
]
All you really need to do is this:
headers = [ "UnitID", "First Name", "NPS Score", "Comments" ]
data = my_models.map do |model|
[ model.unit_id, model.first_name, model.nps_score, model.comments ]
end
rows = [ headers, *data ]
Or...
data = my_models.map do |model|
model.attributes.values_at(:unit_id, :first_name, :nps_score, :comments)
end
(Either way you could make this a one-liner, but mind your code's readability.)
Of course, it's always best to select only the columns you're going to use, so you could just do this (adding whatever where, order etc. calls you need):
my_models = MyModel.select([ :unit_id, :first_name, :nps_score, :comments ]).where(...)
data = my_models.map(&:attributes)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]
In Rails 4 the pluck method takes multiple arguments, making this even easier:
data = MyModel.where(...).pluck(:unit_id, :first_name, :nps_score, :comments)
# => [ [ 123, "Xxx", 100, "..." ],
# [ 456, "Yyy", 200, "..." ],
# ...
# ]

I am not entirely sure what are you trying to achieve here, but it seems that you are looking for pluck method. Since rails 4 it allows you to pluck multiple columns at once (and by default will pluck all columns). So it seems that:
Model.pluck(:unit_id, :first_name, :nps_score, :comment)
Is what you are looking for - and is actually much better as it is not instantiating new objects and makes just one call to db. . It will return 2d array, one row for each model. If you rather prefer have different values of same column, add transpose on the above.

Related

split multi-dimensional array in ruby

I am trying to parse json data in ruby my desired output is:
var events = { '01-01-2018' :
[ {content: 'Psalm 2', allDay: true},
{content: 'by ToddWagner', allDay: true}
],
'01-02-2018' :
[ {content: 'Psalm 2', allDay: true},
{content: 'by ToddWagner', allDay: true}
]
}
what I get is
var events = [
{"2017-11-03":
[ {"content":"Romans 14:5-12","allDay":true},
{"content":"by Micah Leiss","allDay":true}
]
},
{"2017-11-06":
[{"content":"Romans 14:13","allDay":true},
{"content":"by Sarah Thomas","allDay":true}
]
}
]
I tried something like
data = []
raw_data['entries'].each do |entry|
data << {entry_date => [
{
"content" => entry.title,
"allDay" => true,
},
{
"content" => entry.writer,
"allDay" => true,
},
]
}
end
data.to_json
but I didn't get desired results, I have also tried data.pop data.shift.
Ruby implementation would look like:
data = raw_data['entries'].map do |entry|
[entry.date, [entry.title, entry.writer].map do |content|
{content: content, allDay: true}
end]
end.to_h
First of all, are adding fields to your array data, as I can see from your desired output, you need a hash.
You have to create the hash, not the array:
data = {}
and then in your loop
raw_data['entries'].each do |entry|
add it like that
data[entry_date] = [
{
"content" => entry.title,
"allDay" => true,
},
{
"content" => entry.writer,
"allDay" => true,
},
]
(I am not where do you declare entry_date in your example so it might be entry.date)
I can't tell from your example if entry date is unique or not(and I think it's not) make sure you add to hash, because you might overwrite it.
You can do something like this if entry date isn't unique
data[entry.date] ||= []
data[entry.date] << {hash_you_need}

Rails merge multiple json response

Can anyone help me with this problem?
So, here is the problem, I want to merge this query response:
#energy = Alert.where(["alert_type = ?", "Energy"]).last.as_json
#cost = Alert.where(["alert_type = ?", "Cost"]).last.as_json
Then I merge those object with:
#current_notif = #energy.merge(#cost)
But those just give me #cost object like this:
{
"alert_type": "Cost",
"value": 30000000,
"status": "Cost exceeds limit",
"created_at": "2017-06-03T15:31:21.156+07:00",
"updated_at": "2017-06-03T15:31:21.156+07:00",
"home_id": 2
}
Rather than a merged #energy + #cost like this:
{ {"alert_type": "Energy",
"value": 384455.813978742,
"status": "Energy too high",
"created_at": "2017-05-31T11:31:12.907+07:00",
"updated_at": "2017-05-31T11:31:12.907+07:00",
"home_id": 2 },
{
"alert_type": "Cost",
"value": 30000000,
"status": "Cost exceeds limit",
"created_at": "2017-06-03T15:31:21.156+07:00",
"updated_at": "2017-06-03T15:31:21.156+07:00",
"home_id": 2
}
}
If you want you could "join" both values, and then over that use as_json:
[#energy, #cost].as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]
Or if you want you could use the IN expression, in order to deal with ActiveRecord instead having to customize the result this gives you:
Alert.where(alert_type: ['Energy', 'Cost']).as_json
# [{"alert_type": "Energy", ... }, {"alert_type": "Cost", ... }]
This is happening because that's how merge works.
hash = {:name => "Ade", :gender => "Male"}.merge(:name => "Bob")
puts hash # {:name=>"Bob", :gender=>"Male"}
Solution:
results = [ #energy, #cost ]
results.each do |result|
puts result['alert_type'] # Energy, Cost
end

Can you change Multiple Properties with select helper?

I'm using the following select helper:
f.select(:page_color, Orders::PAYMENT_TYPES ,:prompt => "Select a Box")
is it possible to change multiple columns with one selection? Say I want to change :page_color and :pay_method with the selection of "Check". Is this possible?
PAYMENT_TYPES = [
# Displayed stored in db
[ "Check", "check" ],
[ "Credit card", "cc" ],
[ "Purchase order", "po" ]
]
I think the cleanest thing would be to write a virtual attribute:
def paymethod=(value)
mapping = {
'check' => 'red',
'cc' => 'green',
...
}
self.page_color = mapping(value)
super
end

Hash remove all except specific keys

I would like to remove every key from a hash except a given key.
For example:
{
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address":
{
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumber":
[
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
I want to remove everything except "firstName" and/or "address".
What about slice?
hash.slice('firstName', 'lastName')
# => { 'firstName' => 'John', 'lastName' => 'Smith' }
Available in Ruby since 2.5
Some other options:
h.select {|k,v| ["age", "address"].include?(k) }
Or you could do this:
class Hash
def select_keys(*args)
select {|k,v| args.include?(k) }
end
end
So you can now just say:
h.select_keys("age", "address")
If you use Rails, please consider ActiveSupport except() method: http://apidock.com/rails/Hash/except
hash = { a: true, b: false, c: nil}
hash.except!(:c) # => { a: true, b: false}
hash # => { a: true, b: false }
Hash#select does what you want:
h = { "a" => 100, "b" => 200, "c" => 300 }
h.select {|k,v| k > "a"} #=> {"b" => 200, "c" => 300}
h.select {|k,v| v < 200} #=> {"a" => 100}
Edit (for comment):
assuming h is your hash above:
h.select {|k,v| k == "age" || k == "address" }
hash = { a: true, b: false, c: nil }
hash.extract!(:c) # => { c: nil }
hash # => { a: true, b: false }
Inspired by Jake Dempsey's answer, this one should be faster for large hashes, as it only peaks explicit keys rather than iterating through the whole hash:
class Hash
def select_keys(*args)
filtered_hash = {}
args.each do |arg|
filtered_hash[arg] = self[arg] if self.has_key?(arg)
end
return filtered_hash
end
end
No Rails needed to get a very concise code:
keys = [ "firstName" , "address" ]
# keys = hash.keys - (hash.keys - keys) # uncomment if needed to preserve hash order
keys.zip(hash.values_at *keys).to_h

header and footer in Prawn PDF

I have read through all relevant posts on Prawn but found no mentioning (even in Prawn's own documentation) of headers and footers.
However, I did see a demo on Prawnto's own website about headers and footers. I copied the entire source of that demo just to see if it works but an error of undefined method "header" is complained about. Am I to understand that Prawn took out header and footer recently in the gem or is there something else I need to do first to use header and footer?
The demo page:
http://cracklabs.com/prawnto/code/prawn_demos/source/text/flowing_text_with_header_and_footer
the part of code of concern:
Prawn::Document.generate("flow_with_headers_and_footers.pdf") do
header margin_box.top_left do
text "Here's My Fancy Header", :size => 25, :align => :center
end
text "hello world!"
end
And by header, just in case, I mean the snippets of words that appear usually at a corner of every page of a document. Like your account number in your bills pages.
thanks!
The sample you are refering to, from the prawnto plugin, is using an older version of prawn.
Since i also needed header and footer i looked a bit more into this. It seems that that version of prawn had header and footer methods, which were implemented using lazy bounding box. (found by checking the code on github)
In the new prawn version you can do the same thing using repeaters.
Here is the full sample rewritten using the new version:
require "#{File.dirname(__FILE__)}/../example_helper.rb"
Prawn::Document.generate("test.pdf") do
repeat :all do
# header
bounding_box [bounds.left, bounds.top], :width => bounds.width do
font "Helvetica"
text "Here's My Fancy Header", :align => :center, :size => 25
stroke_horizontal_rule
end
# footer
bounding_box [bounds.left, bounds.bottom + 25], :width => bounds.width do
font "Helvetica"
stroke_horizontal_rule
move_down(5)
text "And here's a sexy footer", :size => 16
end
end
bounding_box([bounds.left, bounds.top - 50], :width => bounds.width, :height => bounds.height - 100) do
text "this is some flowing text " * 200
move_down(20)
font "#{Prawn::BASEDIR}/data/fonts/DejaVuSans.ttf"
table [["ὕαλον ϕαγεῖν", "baaar", "1" ],
["This is","a sample", "2" ],
["Table", "dont\ncha\nknow?", "3" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules\nwith an iron fist", "x" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ],
[ "It", "Rules", "4" ]],
:font_size => 24,
:horizontal_padding => 10,
:vertical_padding => 3,
:border_width => 2,
:position => :center,
:headers => ["Column A","Column B","#"]
end
end
you can check the documentation page of repeat for other options which allow you to exactly specify where you want the repeaters.
#GrantSayer thx for the example, but this will only let you show the current page number, not the total number of pages.
You can also use the number_pages function for the footer:
Prawn::Document.generate("page_with_numbering.pdf") do
text "Hai"
start_new_page
text "bai"
start_new_page
text "-- Hai again"
number_pages "<page> in a total of <total>", [bounds.right - 50, 0]
end
However, in my case I also need to format/style and right align the page numbers to match company style guides. I used go_to_page(k) to create my own header and footer functions, which add the header and footer to each page after all the pages are created. This gives me both styling options and the total number of pages:
Prawn::Document.generate("footer_example.pdf", :skip_page_creation => true) do
10.times do
start_new_page
text "Some filler text for the page"
end
# footer
page_count.times do |i|
go_to_page(i+1)
lazy_bounding_box([bounds.right-50, bounds.bottom + 25], :width => 50) {
text "#{i+1} / #{page_count}"
}.draw
end
end
It's little bit different with latest version of Prawn you must passe an hash
Prawn::Document.generate("page_with_numbering.pdf") do
text "Hai"
start_new_page
text "bai"
start_new_page
text "-- Hai again"
number_pages "<page> in a total of <total>", { :start_count_at => 0, :page_filter => :all, :at => [bounds.right - 50, 0], :align => :right, :size => 14 }
end
If you want a footer that do not write stuff over your text, you have to create the bounding_box below the margin of the document using bounds.bottom.
require 'prawn'
file_name = 'hello.pdf'
random_table = (0..50).map{|i|[*('a'..'z')]} # generate a 2D array for example (~2 pages)
Prawn::Document::generate(file_name) do |pdf|
pdf.table random_table
pdf.page_count.times do |i|
pdf.bounding_box([pdf.bounds.left, pdf.bounds.bottom], :width => pdf.bounds.width, :height => 30) {
# for each page, count the page number and write it
pdf.go_to_page i+1
pdf.move_down 5 # move below the document margin
pdf.text "#{i+1}/#{pdf.page_count}", :align => :center # write the page number and the total page count
}
end
end
It should look like that, you can see that the footer is outside the margin bottom :
Hope it help someone
START EDIT
This works in prawn >= 0.12
END EDIT
Here is my solution using repeat, canvas and cell. Essentially I'm drawing my bounding boxes at the absolute top and bottom of every page. I'm using cell to have better styling control over it. Hope this is going to be helpful to someone. ( I used slightly annoying colors to better illustrate how you can control styling of header and footer)
Prawn::Document.generate("headers_and_footers_with_background.pdf") do
repeat :all do
# header
canvas do
bounding_box([bounds.left, bounds.top], :width => bounds.width) do
cell :content => 'Header',
:background_color => 'EEEEEE',
:width => bounds.width,
:height => 50,
:align => :center,
:text_color => "001B76",
:borders => [:bottom],
:border_width => 2,
:border_color => '00FF00',
:padding => 12
end
end
# footer
canvas do
bounding_box [bounds.left, bounds.bottom + 50], :width => bounds.width do
cell :content => 'Footer',
:background_color => '333333',
:width => bounds.width,
:height => 50,
:align => :center,
:text_color => "FFFFFF",
:borders => [:top],
:border_width => 2,
:border_color => 'FF0000',
:padding => 12
end
end
end
# body
bounding_box([bounds.left, bounds.top - 25], :width => bounds.width, :height => bounds.height - 50) do
100.times do
text "Some filler text for the page"
end
end
end
here's the problem when using the bounding_box for creating the custom footer contents... it is still rendering within the bounds of a margin.
I was looking for something that will write the contents in the margin area together with number_pages.(because a footer usually is set in the bottom margin area)... and it seems that there were none.
so instead, I used text_box and place the coordinates outside my main bounding box like so:
repeat :all do
text_box "My custom footer", size: 7, align: :center, :at => [bounds.left, bounds.bottom], :height => 100, :width => bounds.width
end
take note that the repeat :all , will render this footer text to every page.
The only way I've found to get a repeating item on a page is to use the Prawn::Document::LazyBoundingBox method. Basically this allows you to define a bounding box that is only rendered once you call it. So the usual pseudo-code steps are
Define lazy bounding box element assign to somevar
On each new page call the element.
The example from the source shows how
file = "lazy_bounding_boxes.pdf"
Prawn::Document.generate(file, :skip_page_creation => true) do
point = [bounds.right-50, bounds.bottom + 25]
page_counter = lazy_bounding_box(point, :width => 50) do
text "Page: #{page_count}"
end
10.times do
start_new_page
text "Some filler text for the page"
page_counter.draw
end
end
This gives you a Page-count text output on each new page. What would be ideal is if this could be applied in the setup of a page template that is reused without the manual call to render the element. Combined with text flow this would give the traditional solution of headers and footers.

Resources