Examples
These are som frequently used code snippets for the ruby view.
Table of Contents
Display the main table
<%= render 'table' %>
- Will write the content of variable
@docs
that come from xml
Add a new column for full name
Make a new column that combines first name and last name
@docs.each do |doc|
doc["full name"] = doc["first name"] + " " + doc["last name"]
end
@show_fields << "full name"
Provide an alternative value
Show the student grade if it exists, or show a dashed line if its missing
@docs.each do |doc|
doc["grade"] ||= "-----"
end
Use first part of the string
E.g. remove time from the string 12.02.2024 11:00
@docs.each do |doc|
doc["date"] = doc["date"][0..9]
end
Convert utc to local time
@docs.each do |doc|
doc["date"] = doc["date"].in_time_zone
end
Note
The date will be presented a little different. See next example for formatting.
Convert utc to formatted local time
If you want to format the result at the same time
@docs.each do |doc|
doc["date"] = doc["date"].in_time_zone.strftime("%d.%m.%Y %H:%M")
end
Using only the date part
Sometimes we only want the date and not the time part
@docs.each do |doc|
doc["rental_days"] = (doc["return_date"].to_date - doc["rental_date"].to_date).to_i
end
Note
If needed, use in_time_zone.to_date
Custom method
Write out numbers e.g. 3 as “3 tre”, D as “Deltatt” Returns original string if not found
def write_out_grade(str)
map = {
"1" => "1 en",
"2" => "2 to",
"3" => "3 tre",
"4" => "4 fire",
"5" => "5 fem",
"6" => "6 seks",
"D" => "Deltatt",
"G" => "God",
"NG" => "Nokså god",
"LG" => "Lite god",
"FU" => "Fullført utdanning",
"IM" => "Ikke møtt" }
map[str] || str
end
Show blank page if no data
When no data, its good to exit early to avoid errors.
return if @docs.empty?