I am using axlsx gem to generate Excel sheets in Ruby on Rails.
wb = xlsx_package.workbook
wb.styles do |s|
title = s.add_style :b => true, :sz => 10,
:border => { :style => :thin, :color => "00" },
:alignment => {
:horizontal => :center,
:vertical => :center
}
row = s.add_style :b => false,
:sz => 10,
:border => { :style => :thin, :color => "00" },
:alignment => {
:horizontal => :left,
:vertical => :center
}
wb.add_worksheet(name: "Customer") do |sheet|
sheet.add_row ['Customer Name', 'Status'] :style => title
#customers.each do |customer|
sheet.add_row [customer.name, customer.status] :style => row
end
end
how can I conditionally change the row background color if the customer status let say = "Late Payment"
I haven't tested it but this should do the job.
wb = xlsx_package.workbook
wb.styles do |s|
title = s.add_style :b => true, :sz => 10,
:border => { :style => :thin, :color => "00" },
:alignment => {
:horizontal => :center,
:vertical => :center
}
row = s.add_style :b => false,
:sz => 10,
:border => { :style => :thin, :color => "00" },
:alignment => {
:horizontal => :left,
:vertical => :center
}
red_cell_row = s.add_style :b => false,
:sz => 10,
:border => { :style => :thin, :color => "00" },
:alignment => {
:horizontal => :left,
:vertical => :center
},
:bg_color => "FF0000",
:fg_color => "000000"
wb.add_worksheet(name: "Customer") do |sheet|
sheet.add_row ['Customer Name', 'Status'] :style => title
#customers.each do |customer|
if customer.status == "Late Payment"
sheet.add_row [customer.name, customer.status] :style => red_cell_row
else
sheet.add_row [customer.name, customer.status] :style => row
end
end
end
Related
I am using Ruby on Rails application. I want to combine 2 array of hashes with hash and to result in array of hashes.
Inputs:
first_array_of_hash = [{:name => "John", :age => 34, :mode => "nullable"},{:name => "Rose", :age => 30, :mode => "nullable"}]
second_hash = {:field_name => "", :field_age => nil, :field_nullable => false, :field_default => ""}
I want my result to be like below
result = [{:field_name => "John", :field_age => 34, :field_nullable => true, :field_default => ""},{:field_name => "Rose", :field_age => 30, :field_nullable => true, :field_default => ""}]
You can use a regular Array#map for this:
first_array_of_hash = [{:name => "John", :age => 34, :nullable => 'yes'},{:name => "Rose", :age => 30, :nullable => 'no'}]
second_hash = {:field_name => "", :field_age => nil, :field_nullable => false, :field_default => ""}
def transform(object)
{
field_name: object[:name],
field_age: object[:age],
field_nullable: object[:mode] == 'nullable'
}
end
result = first_array_of_hash.map do |object|
second_hash.merge(transform(object))
end
puts result
I'm attempting to create a new AWS Cloudfront Distribution with v2 of the ruby AWS SDK and cannot figure out what is causing this error.
Aws::CloudFront::Errors::MalformedInput: Unexpected list element termination
client = Aws::CloudFront::Client.new
resp = client.create_distribution({
distribution_config: {
caller_reference: Time.now.to_i.to_s,
:aliases => {
:quantity => 1,
:items => [Name.generate_name]
},
:origins => {
:quantity => 1,
:items => [
{
:id => "#{self.id}-distribution",
:domain_name => "example-static.s3-website-us-east-1.amazonaws.com",
:origin_path => "/#{self.id}",
:custom_headers => {
:quantity => 0,
:items => []
},
:custom_origin_config => {
:http_port => 80,
:https_port => 443,
:origin_protocol_policy => "http-only",
:origin_ssl_protocols => {
:quantity => 3,
:items => ["TLSv1","TLSv1.1","TLSv1.2"]
}
}
}
]
},
:default_cache_behavior => {
:target_origin_id => "Custom-example-static.s3-website-us-east-1.amazonaws.com/#{self.id}",
:forwarded_values => {
:query_string => true,
:cookies => {
:forward => "none"
},
:headers => {
:quantity => 1,
:items => ["Origin"]
}
},
:trusted_signers => {
:enabled => false,
:quantity => 0
},
:viewer_protocol_policy => "allow-all",
:min_ttl => 0,
:allowed_methods => {
:quantity => 3,
:items => ["HEAD","GET","OPTIONS"],
:cached_methods => {
:quantity => 3,
:items => ["HEAD","GET","OPTIONS"]
}
},
:smooth_streaming => false,
:default_ttl => 86400,
:max_ttl => 31536000,
:compress => true
},
:cache_behaviors => {
:quantity => 0
},
:custom_error_responses => {
:quantity => 0
},
:comment => "",
logging: {
enabled: true, # required
include_cookies: false, # required
bucket: "example-logs", # required
prefix: "#{self.id}", # required
},
:price_class => "PriceClass_100",
:enabled => true,
:restrictions => {
:geo_restriction => {
:restriction_type => "none",
:quantity => 0
}
}
}
})
I compared the results I got back from an existing instance with
client = Aws::CloudFront::Client.new(:http_wire_trace => true)
resp = client.get_distribution_config({
:id => '<ID>'
})
Changing the payload from
:custom_headers => {
:quantity => 0,
:items => []
},
to
:custom_headers => {
:quantity => 0
},
seemed to fix the same error message for me.
I'm trying to calculate the shipping cost depending of the total quantity of the product purchased with the Fedex gemhttps://github.com/jazminschroeder/fedex. I'm getting the rates but I have different packages options, 3 actually.
the first one when the quantity is 1 (small), the second one when the quantity is 2 (medium) and the third one when the quantity is 3 or 4 (larger).
def packages_types
packages = []
if #order.quantity >= 4
packages << { :weight => {:units => "LB", :value => #order.case_weight},
:dimensions => {:length => 8, :width => 1, :height => 7, :units => "IN" } }
elsif #order.quantity == 2
packages << { :weight => {:units => "LB", :value => 21},
:dimensions => {:length => 1, :width => 2, :height => 7, :units => "IN" } }
elsif #order.quantity == 1
packages << { :weight => {:units => "LB", :value => 10},
:dimensions => {:length => 1, :width => 2, :height => 2, :units => "IN" } }
end
end
So if the client orders 5 on quantity. It's going to be the package of 4(large) and 1 of the small package. I was thinking using the mod...
def packages_types
packages = []
extra_items_count = #order.quantity % 4
large_packages_needed = (#order.quantity - extra_items_count) / 4
# point A
large_packages_needed.times do
packages << { :weight => { :units => "LB", :value => #order.case_weight },
:dimensions => { :length => 8, :width => 1, :height => 7, :units => "IN" } }
end
# point B
case extra_items_count
when 1
packages << { :weight => { :units => "LB", :value => 10 },
:dimensions => { :length => 1, :width => 2, :height => 2, :units => "IN" } }
when 2
packages << { :weight => { :units => "LB", :value => 21 },
:dimensions => { :length => 1, :width => 2, :height => 7, :units => "IN" } }
when 3, 4
packages << { :weight => { :units => "LB", :value => #order.case_weight },
:dimensions => { :length => 8, :width => 1, :height => 7, :units => "IN" } }
end
return packages
end
Point A: For each group of 4 items, a large package is needed (and added to the packages array).
Point B: For the remaining items (example: you ordered 5 items -> 1 large package of 4 items + 1 small for 1 remaining item), we add the corresponding conditions in the package array.
I have a issue with Locales. In rails app /config/locales/ I have two files: cs.rb & en.yml. At the end, the output of price is in $. Why is this?
my index.html.erb looks
<% if notice %>
<p id="notice" ><%= notice %></p>
<% end %>
<h1>Zoznam produktov</h1>
<% #products.each do |product| %>
<div class="entry" >
<%= image_tag(product.image_url) %>
<h3><%= product.title %></h3>
<%= sanitize(product.description) %>
<div class="price_line" >
<span class="price">
<%= number_to_currency(product.price, :locale => :cs) %>
%>
</span>
</div>
</div>
<% end %>
#Зелёный
First is cs.rb and second is en.yml
# Czech translations for Ruby on Rails
# by Karel Minařík (karmi#karmi.cz)
# contributors:
# - Vít Krchov - http://github.com/vita - Rails 3 update
unless defined?(CzechLocaleI18n::ERROR_MESSAGES)
module CzechLocaleI18n
ERROR_MESSAGES = {
:inclusion => "není v seznamu povolených hodnot",
:exclusion => "je vyhrazeno pro jiný účel",
:invalid => "není platná hodnota",
:confirmation => "nebylo potvrzeno",
:accepted => "musí být potvrzeno",
:empty => "nesmí být prázdný/á/é",
:blank => "je povinná položka", # alternate formulation: "is required"
:too_long => "je příliš dlouhý/á/é (max. %{count} znaků)",
:too_short => "je příliš krátký/á/é (min. %{count} znaků)",
:wrong_length => "nemá správnou délku (očekáváno %{count} znaků)",
:not_a_number => "není číslo",
:greater_than => "musí být větší než %{count}",
:greater_than_or_equal_to => "musí být větší nebo rovno %{count}",
:equal_to => "musí být rovno %{count}",
:less_than => "musí být méně než %{count}",
:less_than_or_equal_to => "musí být méně nebo rovno %{count}",
:odd => "musí být liché číslo",
:even => "musí být sudé číslo",
:not_an_integer => "musí být celé číslo"
}
end
end
{ :'cs' => {
# ActiveSupport
:support => {
:array => {
:two_words_connector => ' a ',
:last_word_connector => ' a ',
:words_connector => ', '
},
:select => {
:prompt => 'Prosím vyberte si',
}
},
# Date
:date => {
:formats => {
:default => "%d. %m. %Y",
:short => "%d %b",
:long => "%d. %B %Y",
},
:day_names => %w{Neděle Pondělí Úterý Středa Čtvrtek Pátek Sobota},
:abbr_day_names => %w{Ne Po Út St Čt Pá So},
:month_names => %w{~ Leden Únor Březen Duben Květen Červen Červenec Srpen Září Říjen Listopad Prosinec},
:abbr_month_names => %w{~ Led Úno Bře Dub Kvě Čvn Čvc Srp Zář Říj Lis Pro},
:order => [:day, :month, :year]
},
# Time
:time => {
:formats => {
:default => "%a %d. %B %Y %H:%M %z",
:short => "%d. %m. %H:%M",
:long => "%A %d. %B %Y %H:%M",
},
:am => 'am',
:pm => 'pm'
},
# Numbers
:number => {
:format => {
:precision => 3,
:separator => '.',
:delimiter => ',',
:significant => false,
:strip_insignificant_zeros => false
},
:currency => {
:format => {
:unit => 'Kč',
:precision => 2,
:format => '%n %u',
:separator => ",",
:delimiter => " ",
:significant => false,
:strip_insignificant_zeros => false
}
},
:human => {
:format => {
:precision => 1,
:delimiter => '',
:significant => false,
:strip_insignificant_zeros => false
},
:storage_units => {
:format => "%n %u",
:units => {
:byte => "B",
:kb => "KB",
:mb => "MB",
:gb => "GB",
:tb => "TB",
}
},
:decimal_units => {
:format => "%n %u",
:units => {
:unit => "",
:thousand => "Tisíc",
:million => "Milion",
:billion => "Miliarda",
:trillion => "Bilion",
:quadrillion => "Kvadrilion"
}
}
},
:percentage => {
:format => {
:delimiter => ''
}
},
:precision => {
:format => {
:delimiter => ''
}
}
},
# Distance of time ... helper
# NOTE: In Czech language, these values are different for the past and for the future. Preference has been given to past here.
:datetime => {
:prompts => {
:second => "Sekunda",
:minute => "Minuta",
:hour => "Hodina",
:day => "Den",
:month => "Měsíc",
:year => "Rok"
},
:distance_in_words => {
:half_a_minute => 'půl minutou',
:less_than_x_seconds => {
:one => 'necelou sekundou',
:other => 'ani ne %{count} sekundami'
},
:x_seconds => {
:one => 'sekundou',
:other => '%{count} sekundami'
},
:less_than_x_minutes => {
:one => 'necelou minutou',
:other => 'ani ne %{count} minutami'
},
:x_minutes => {
:one => 'minutou',
:other => '%{count} minutami'
},
:about_x_hours => {
:one => 'asi hodinou',
:other => 'asi %{count} hodinami'
},
:x_days => {
:one => '24 hodinami',
:other => '%{count} dny'
},
:about_x_months => {
:one => 'asi měsícem',
:other => 'asi %{count} měsíci'
},
:x_months => {
:one => 'měsícem',
:other => '%{count} měsíci'
},
:about_x_years => {
:one => 'asi rokem',
:other => 'asi %{count} roky'
},
:over_x_years => {
:one => 'více než rokem',
:other => 'více než %{count} roky'
},
:almost_x_years => {
:one => 'téměř rokem',
:other => 'téměř %{count} roky'
}
}
},
:helpers => {
:select => {
:prompt => "Prosím vyberte si"
},
:submit => {
:create => "Vytvořit %{model}",
:update => "Aktualizovat %{model}",
:submit => "Uložit %{model}"
}
},
:errors => {
:format => "%{attribute} %{message}",
:messages => CzechLocaleI18n::ERROR_MESSAGES
},
# ActiveRecord validation messages
:activerecord => {
:errors => {
:messages => {
:taken => "již databáze obsahuje",
:record_invalid => "Validace je neúspešná: %{errors}"
}.merge(CzechLocaleI18n::ERROR_MESSAGES),
:template => {
:header => {
:one => "Při ukládání objektu %{model} došlo k chybám a nebylo jej možné uložit",
:other => "Při ukládání objektu %{model} došlo ke %{count} chybám a nebylo možné jej uložit"
},
:body => "Následující pole obsahují chybně vyplněné údaje:"
},
:full_messages => {
:format => "%{attribute} %{message}"
}
}
}
}
}
#
# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
en:
hello: "Hello world"
I think, you have not defined cs.yml in locale directory that's why, it is taking default as en locale.
please define cs.yml instead of cs.rb
For this to work you need to have a locale file at config/locales/fr.yml for this to work.
The :locale option only declares to Rails what locale you want it to be. Rails does not have all the translations for every language in the project, and so you must include these translation files yourself.
I'm using jqgrid with ruby on rails and as per my requiremnet in jqgrid listing page i need background color as dynamic for a particular column values.
Here is my code for helper,
include JqgridsHelper
def colors_jqgrid
options = {:on_document_ready => true, :html_tags => false}
grid = [{
:sortable => true,
:url => '/colors',
:datatype => 'json',
:mtype => 'GET',
:colNames => ['colors_id','ID','External ID','name','Color Swatch','Actions'],
:colModel => [
{ :name => 'colors_id', :index => 'colors_id',:hidden => true},
{ :name => 'ID', :index => 'ID', :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
}},
{ :name => 'External ID', :index => 'color_id',:search=>false, :width => 180 ,:searchoptions => {
:sopt => ['eq','ne','bw','ew','cn'],
} },
{ :name => 'name', :index => 'name', :width => 180 ,:searchoptions => {
:sopt => ['eq','in'],
} },
{ :name => 'color_id', :index => 'Color Swatch',:search=>false, :width => 180},
{name:'Actions',index:'action',align:'center',sortable:false,formatter: 'function(cellvalue, options, rowObject) {
edit = "<span class=\"ui-icon ui-icon-pencil\" title=\"Edit\" style= \"cursor:pointer;float:left;\" onclick=\"window.location.href = '"'colors/edit?id="'"+options.rowId+"'"'"';\"></span>";
edit += "<span class=\"ui-icon ui-icon-trash\" title=\"Delete\" style= \"cursor:pointer;\" onclick=\"jQuery.fn.fmatter.rowactions.call(this,'"'del'"');\"></span>";
return edit;
}'.to_json_var },
],
:editurl => '/colors/grid_update',
:pager => '#colors_pager',
:rowNum => 10,
:rowList => [10, 20, 30],
:caption => 'Colors',
:autowidth => true,
:navigator=>true,
:excel=>true,
:viewrecords=>true,
:ondblClickRow => "function(rowId, iRow, iCol, e) { window.location = 'colors/edit?id='+ rowId; }".to_json_var
}]
pager = [:navGrid, "#colors_pager", { :del => false,:search=>true,:edit => false,:add => false},
{:closeAfterEdit => true, :closeOnEscape => true}, {}, {}, {:multipleSearch => true}, {}]
options = [:navButtonAdd, "#colors_pager", {caption: "Columns", title: "Reorder Columns", onClickButton: "function() { jQuery('#colors_list').jqGrid('columnChooser'); }".to_json_var }]
jqgrid_api 'colors_list', grid, pager, options
end
Add following line anywhere in grid variable section.
:afterInsertRow => "function(rowId, data) { $(\"#colors_list\").setCell(rowId, 'color_id', '', {'background-color':'#'+data.color_id }); }".to_json_var
it requires 2 parameters. First is rowId which is identifier of row. second is data which is content of that row with all fields. so i used data.color_id for fetching color code which u want to use to set background color.