I'm working on a PDF invoice using Prawn PDF. I am trying to use number_to_currency whilst passing the unit.
def line_item_rows
[["Description", "Qty", "Unit Price", "Price GBP"]] +
#invoice.line_items.map do |item|
[item.name, item.quantity, price(item.unit_price), price(item.full_price)]
end
end
#view.number_to_currency(num, :unit => "£")
The above results in an error:
syntax error, unexpected $end, expecting ')'
#view.number_to_currency(num, :unit => "£")
^):
If I use the HTML value instead it simply outputs the raw html:
#view.number_to_currency(num, :unit => "£")
Total £2,266.00
Is there a particular way of adding a £ when using Prawn PDF? The above attempts work fine when using html/erb but not when using Prawn PDF.
Ruby probably isn't treating your source file as utf-8:
# encoding: US-ASCII <-- it's defaulting to this
puts "£"
So when it compiles:
$ ruby foo.rb
foo.rb:2: invalid multibyte char (US-ASCII)
foo.rb:2: invalid multibyte char (US-ASCII)
foo.rb:2: syntax error, unexpected $end, expecting ')'
puts("£")
^
Add an encoding hint at the top of your file:
# encoding: utf-8
puts("£")
And it should run:
$ ruby foo.rb
£
Related
I try to do an Selenium-Acceptancetest 'Search Result List' with RSpec spec
And my Issue is
It should verify the count of a Button "Detail"
I would be happy to get help for start thinking as a coder; i am a manual tester stil.
My Problem now is:
Method Error
Failure/Error: expect(#driver.find_element(:xpath, "//a[contains(text(),'Details')]").to be > 4)
NoMethodError:
undefined method `to' for #<Selenium::WebDriver::Element:0x00000003fd4938>
Sources:
On my way to resolve the issue I tried to modify this and I found this
But its not working
thanksfully remaining!
my Test File:
# coding: utf-8
puts "this is #{File.basename(__FILE__)}"
extend RSpec::Expectations
extend RSpec::Matchers
describe 'SEL' do
before(:each) do
#driver = loadDriver()
end
after(:each) do
#driver.quit
end
it 'test_Page (SEL)' do
#get the page
...
#do input keyword 'Restaurant'
...
#click submit
...
#(Works!) temp Validation1: Is there a "Btn Details" in SearchResultList?
expect(#driver.find_element(:xpath, "//a[contains(text(),'Details')]").displayed?)
#(Works not!) Validation: Are there more than "5 Btns Detail"
expect(#driver.find_element(:xpath, "//a[contains(text(),'Details')]").to be > 5)
end
end
Update after first answer:
Given I use
expect(#driver.find_elements(:xpath, "//a[contains(text(),'Details')]")).to be > 0
it hits that error:
Failure/Error: expect(#driver.find_elements(:xpath, "//a[contains(text(),'Details')]")).to be > 0
expected: > 0
got: [#<Selenium::WebDriver::Element:0xa6219008 id="a2a2c83a-e52d-4464-81ec-4fce07ccc0b6">, #<Selenium::We...64378279">, #<Selenium::WebDriver::Element:0x..f90cc8d0e id="de990e21-eecf-48db-873b-76515dba7c3e">]
Given the error message:
undefined method `to' for #<Selenium::WebDriver::Element:0x00000003fd4938>
I suspect your issue is a missing bracket. Normal Rspec syntax is
expect(something).to eq(some value).
I would imagine you are missing the closing parenthesis
expect(#driver.find_element(:xpath, "//a[contains(text(),'Details')]").to be > 5)
and this should be something more like:
expect(#driver.find_element(:xpath, "//a[contains(text(),'Details')]")).to be > 5
Although I might guess you need to call a size function on the latter part as well as maybe use find elements. Maybe this will also be useful for you.
I want to make my yii app multilanguage. To do this I want to use gettext (because its much simpler than yii messages).
To this I used this yii extension, I configured the PO files, I made the translations, etc.
The big problem: nothing happened. Nothing was translated.
I can advice you this awesome multilanguage extension!
http://www.yiiframework.com/extension/tstranslation/
To use gettext without any extension follow those steps. In config/main.php set yout target language like this:
'language' = 'ru',
Set messages component to use CGettextMessageSource:
'messages' => array(
'class' => 'CGettextMessageSource',
),
Create messages.po file in protected/messages/ru folder (note: folder name is same as language code). If poedit is used messages.po file must have appropriate headers. Example:
msgid ""
msgstr ""
"Project-Id-Version: FOO BAR 1.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2011-11-11 11:11+0300\n"
"PO-Revision-Date: \n"
"Language: ru\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"
"X-Poedit-SourceCharset: utf-8\n"
"X-Poedit-Basepath: .\n"
"X-Poedit-KeywordsList: _ngettext:1,2;t:1c,2\n"
"X-Poedit-SearchPath-0: ../..\n"
Note t:1c,2. This means, that first parameter from function Yii::app() will be used as context (see msgctx) and second as actual string to translate. Without this your i18n will not work!
Now just open messages.po in poedit → Update → do translations → Save.
And messages.mo file will be created and used by Yii.
For you language plurals string see gettext help.
I've implemented a custom error message processor for Korean language. In Korean, postpositions take different forms depending on the sound of the preceding noun or pronoun.
For example, when marking a subject, ka (가) is used following a vowel and i (이) is used following a consonant.
Examples (hyphens are to denote morpheme boundaries):
Romanization: sakwa-ka ppalkah-ta.
Gloss: Apple-SUBJECT red-PRESENT.
Translation: Apple is red.
Romanization: phainayphul-i tal-ta.
Gloss: Pineapple-SUBJECT sweet-PRESENT.
Translation: Pineapple is sweet.
Therefore, the standard error message system implemented in ActiveModel::Errors is not adequate for Korean. You should either include the attribute in the message making a lot of duplicates ("A is blank", "B is blank", "C is blank", ...), or avoid postpositions after the attribute which is often difficult or makes awkward sentences.
I monkey patched ActiveModel::Errors and altered generate_message to solve this problem. Following is the code (Gist) which is currently in config/initializers in my Rails app.
# encoding: UTF-8
# Original article: http://dailyupgrade.me/post/6806676778/rubyonrails-full-messages-for-korean
# Modified to support more postpositions and client_side_validations gem.
#
# Add Korean translations like this:
# ko:
# errors:
# format: "%{message}"
# messages:
# blank: "%{attribute}((이)) 입력되지 않았습니다"
# taken: "이미 사용 중인 %{attribute}입니다"
# invalid: "잘못된 %{attribute}입니다"
# too_short: "%{attribute}((이)) 너무 짧습니다"
#
class Korean
POSTPOSITIONS = {"은" => "는", "이" => "가", "을" => "를", "과" => "와", "으로" => "로"}
def self.select_postposition(last_letter, postposition)
return postposition unless last_letter >= "가" && last_letter <= "힣"
final = last_letter.mb_chars.last.decompose[2]
if final.nil?
# 받침 없음
POSTPOSITIONS[postposition] || postposition
elsif final == "ㄹ" && (postposition == "으로" || postposition == "로")
# 'ㄹ 받침 + (으)로'를 위한 특별 규칙
"로"
else
# 받침 있음
POSTPOSITIONS.invert[postposition] || postposition
end
end
end
module ActiveModel
class Errors
old_generate_message = instance_method("generate_message")
define_method("generate_message") do |attribute, type = :invalid, options = {}|
msg = old_generate_message.bind(self).(attribute, type, options)
return msg unless I18n.locale == :ko
msg.gsub(/(?<=(.{1}))\(\((은|는|이|가|을|를|과|와|으로|로)\)\)/) do
Korean.select_postposition $1, $2
end
end
end
end
My first question is whether it is possible to achieve the same goal without monkey patching. I'm new to Rails (and Ruby too) so couldn't come up with a better solution.
The second question is about extracting this code from my Rails app and making it into a separate gem. I'm cutting my teeth on developing gems and recently made my first gem. In what place should I put this code in a gem? config/initializers doesn't seem right.
I'm not good at ruby but the following javascript code do the same thing. I hope it may help.
var hasJongsung = function(word) {
return !!(word && word[word.length -1].charCodeAt()>=0xAC00 && word[word.length-1].charCodeAt()<=0xD7A3 && (word[word.length -1].charCodeAt()-0xAC00)%28);
};
source:http://spectrumdig.blogspot.kr/2012/11/unicode-20.html
I'm exporting data to a CSV file in rails and in some of my fields, I'm getting character encoding issues like this when I open in Excel:
didn’t
I borrowed this code from an example and I'm assuming the encoding is off. Any idea what it should be?
send_data csv_data,
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{filename}.csv"
When Excel opens the CSV file it just assumes an "iso-8859-1" character encoding. I guess it doesn't even know about the encoding information you send along within your HTTP reply. That's why setting this to UTF-8 doesn't work.
So in order to export your CSV file for Excel in Rails you could do this:
send_data Iconv.conv('iso-8859-1//IGNORE', 'utf-8', csv_data),
:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment; filename=#{filename}.csv"
This re-encodes your UTF-8 data string (that's the Rails default) to ISO-8859 and sends it. Along goes the information that this reply is actually ISO-8859-1 encoded (which won't make a difference for Excel but is technically correct if you should open it in a browser etc.).
This worked for me, with Chinese characters!excel csv fromat (BOM + UTF8)
def export_csv_excel
....
# Add BOM to make excel using utf8 to open csv file
head = 'EF BB BF'.split(' ').map{|a|a.hex.chr}.join()
csv_str = CSV.generate(csv = head) do |csv|
csv << [ , , , ...]
#invoices.each do |invoice|
csv << [ , , , ...]
end
end
send_data csv_str, filename: "Invoices-#{Time.now.strftime("%y%m%d%H%M%S")}.csv", type: "text/csv"
end
source(Chinese): http://blog.inheart.tw/2013/09/rubyraisl-csv-excel.html
The answers above did not work for me on Mac Excel:
Using iso-8859-1 would require I replace/remove weird characters, which is not a good enough solution for me, and using BOM with UTF8 worked under Windows but not under Mac Excel.
What worked for me is the WINDOWS-1252 encoding as suggested by https://stackoverflow.com/a/20194266/226255
def self.to_csv(options = {})
(CSV.generate(options) do |csv|
csv << self.headers
all.each do |e|
csv << e.values
end
end).encode('WINDOWS-1252', :undef => :replace, :replace => '')
end
module DownloadService
def student_list
File.open("#{file_name}", "w+:UTF-16LE:UTF-8") do |f|
file = CSV.generate({:col_sep => "\t"}) do |c|
c << ['Canción ', 'años', 'etc']
end
f.write "\xEF\xBB\xBF"
f.write(file)
end
end
end
I am working with Prawn to generate a pdf, I have to insert an image in a cell of a table.
My code is like this:
image = "path to file"
subject = [["FORMATIVE I "," SUMATIVE ","GRAPH"],
[formative_1,sumative, {:image => image}]
]
table subject
But, I get an error which says:
prawn/table/cell.rb:127:in `make': Content type not recognized: nil (ArgumentError)
How can I resolve this? Any help is greatly appreciated.
Cheers!
In the current version of Prawn 0.12.0 it is not possible to embed images in a Prawn::Table, but this feature seems to be under way, see here. At the moment you have to write your own table, something like
data = [[{:image => "red.png"},{:text => "Red"}],
[{:image => "blue.png"},{:text => "Blue"}]]
data.each_with_index do |row,i|
row.each_with_index do |cell,j|
bounding_box [x_pos,y_pos], :width => cell_width, :height => cell_height do
image(cell[:image], ...) if cell[:image].present?
text_box(cell[:text], ...) if cell[:text].present?
end
x_pos = (x_pos + cell_width)
end
y_pos = (y_pos - cell_height)
end
Prawn in version 0.12.0 doesn't give the possibility to insert image in a cell. Look at this for further information. It works on the next version 1.0.0.rc1. Just change your version. You can also use the tricky way, but I advise you not to do so.
The manual is available here.
The commit and explanation for that feature from the author. Here