How to add multiple spaces between two strings in ruby .rb file method for pdf generation? - ruby-on-rails

I want to have more spaces between two strings in my rails pdf file.I tried adding more spaces like " " but it is assuming to have a single space.And also, I am not able to use "\n" for my pdf file. The "\n" is not working for pdf generation.
Give a quick solution for it.
Eg:
self.details.map{|i|text = i.name + " " + dob + "\n"}
which gives the output :
ndev 12/12/2020
dev 12/12/2020

Use the constant Prawn::Text::NBSP instead of plain spaces, i.e.
self.details.map {|i| text = i.name + (Prawn::Text::NBSP * 4) + i.dob + "\n" }
The constant contains the Unicode symbol for a non-breaking space and Prawn knows how to correctly handle this for AFM and TTF/OTF fonts.

Related

How to Add Linebreak to Postgres Text Field

I am trying to add a linebreak to a text object in rails.
Using rails 5.0 and postgres 9.4
some_text = "string sentence one"
some_text += #how do i add line break here
some_text = "string sentence two"
I've tried chr(10), '\n', \n, '/\n/' and /\n/
How would I add a line break to some_text?
tl;dr
Below is a loop that I am using in a controller to loop through attributes of an object and try to add a line break to it
#some_text ||= ""
object.attributes.each do |attr_name, attr_value|
#some_text << attr_value.to_s + "\n"
end
When I display the #some_text object in a view, it has no line breaks. If I save the #some_text object into postgres, it still has no line breaks.
It's "\n" (with double quotes):
some_text = "string sentence one"
some_text << "\n"
some_text << "string sentence two"
If you want to output multiline string in irb or der Rails console use puts. Whereas p doesn't work, because it shows control characters instead.
It is worth noting that line break in HTML are usually not displayed in the rendered document. To translate new line characters in strings (\n) into visible HTML line breaks (<br>) there a several options:
Translating the string (string_with_linebreaks.gsub("\n", '<br>')),
use Rails' simple_format text helper or a markdown parser,
place the string into a <pre> block that usually (unless the default css is changed) will preserves both spaces and line breaks or
declare a css rule like white-space: pre-line on the surrounding HTML tag.

Leading and trailing spaces for each line from textarea

ruby 2.1.3
rails 4.1.7
I want to generate a unordered list from textarea. So I have to preserve all line breaks for each item and remove leading and trailing spaces.
Well, I'm trying to remove all leading and trailing spaces from each line of textarea with no success.
I'm using a regex:
string_from_textarea.gsub(/^[ \t]+|[ \t]+$/, '')
I've tried strip and rstrip rails methods with no luck too (they are working with the same result as regex):
Leading spaces for each line are removed perfectly.
But with trailing spaces only the last space from string is removed. But I wanna for each line.
What am I missing here? What is the deal with textarea and trailing spaces for each line?
UPDATE
Some code example:
I'm using a callback to save formated data.
after_validation: format_ingredients
def format_ingredients
self.ingredients = #ingredients.gsub(/^[ \t]+|[ \t]+$/, "")
end
Form view:
= f.text_area :ingredients, class: 'fieldW-600 striped', rows: '10'
You can use String#strip
' test text with multiple spaces '.strip
#=> "test text with multiple spaces"
To apply this to each line:
str = " test \ntext with multiple \nspaces "
str = str.lines.map(&:strip).join("\n")
"test\ntext with multiple\nspaces"
This isn't a good use for a regexp. Instead use standard String processing methods.
If you have text that contains embedded LF ("\n") line-ends and spaces at the beginning and ends of the lines, then try this:
foo = "
line 1
line 2
line 3
"
foo # => "\n line 1 \n line 2\nline 3\n"
Here's how to clean the lines of leading/trailing white-space and re-add the line-ends:
bar = foo.each_line.map(&:strip).join("\n")
bar # => "\nline 1\nline 2\nline 3"
If you're dealing with CRLF line-ends, as a Windows system would generate text:
foo = "\r\n line 1 \r\n line 2\r\nline 3\r\n"
bar = foo.each_line.map(&:strip).join("\r\n")
bar # => "\r\nline 1\r\nline 2\r\nline 3"
If you're dealing with the potential of having white-space that contains other forms of white-space like non-breaking spaces, then switching to a regexp that uses the POSIX [[:space:]] character set, that contains white-space used in all character sets. I'd do something like:
s.sub(/^[[:space:]]+/, '').sub(/[[:space:]]+$/, '')
I think #sin probably intimated the problem in his/her first comment. Your file was probably produced on a Windows machine that puts a carriage return/life feed pair ("\r\n") at the end of each line other than (presumably) the last, where it just writes \n. (Check line[-2] on any line other than the last.) That would account for the result you are getting:
r = /^[ \t]+|[ \t]+$/
str = " testing 123 \r\n testing again \n"
str.gsub(r, '')
#=> "testing 123 \r\ntesting again\n"
If this theory is correct the fix should be just a slight tweak to your regex:
r = /^[ \t]+|[ \t\r]+$/
str.gsub(r, '')
#=> "testing 123\ntesting again\n"
You might be able to do this with your regex by changing the value of the global variable $/, which is the input record separator, a newline by default. That could be a problem for the end of the last line, however, if that only has a newline.
I think you might be looking for String#lstrip and String#rstrip methods:
str = %Q^this is a line
and so is this
all of the lines have two spaces at the beginning
and also at the end ^`
`> new_string = ""
> ""
str.each_line do |line|
new_string += line.rstrip.lstrip + "\n"
end
> "this is a line\n and so is this \n all of the lines have two spaces at the beginning \n and also at the end "
2.1.2 :034 > puts new_string
this is a line
and so is this
all of the lines have two spaces at the beginning
and also at the end
> new_string
`> "this is a line\nand so is this\nall of the lines have two spaces at the beginning\nand also at the end\n"`

Classic ASP, VBScript Concatenation issue,

Below is some Classic Asp VB Script that i am trying to alter so i can get it to run on my windows 2012 server. (I know its old don't ask :( ). This worked on our old 2003 box but the library it use to use is not supported in 2012. I am now using a stored procedure to send out this e-mail. The problem i am facing is that when i concatenate the sMailBody string i must have some ' or " syntax that is not allowing it to concatenate. When I Response.Write(strRSs) I get the string but all of the HTML renders.
EXEC [dbo].[MailPackage] 'test#test.com', 'tteesstt#ttessttt.com', 'tset' {visible HTML}
for x = 0 to uBound(aRecipientID)
'-- Plugin real content
sMailBody = Replace(sMailBody,"{*~BACKGROUND~*}","'"Session("LiveURL")&"")
sMailBody = Replace(sMailBody,"{*~HEADER~*}",Session("LiveURL")&"images/testing.jpg")
sMailBody = Replace(sMailBody,"{*~BODY~*}",sBody)
sMailBody = Replace(sMailBody,"{*~URL~*}",Session("LiveURL") & "/viewpackage.asp?p=" & sPackageKey & "&u=" & aRecipientID(x) & "&s=" & nSendID&"'")
Dim strRS
strRS = "EXEC [dbo].[MailPackage] " + "'" + aRecipientEmail(x) + "', '" + Session("FromAddress") + "', '" + sSubject + "', '" + sMailBody + "'"
Response.Write(sMailBody)
Response.Write(strRS)
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.Open Session("ConnectionString")
Conn.Execute strRS
How can i correct my syntax so i can pass sMailBody as my message body into my stored procedure.
Assuming you want to replace the placeholder {*~BACKGROUND~*} in sMailBody with the content of Session("LiveURL"):
change
sMailBody = Replace(sMailBody,"{*~BACKGROUND~*}","'"Session("LiveURL")&"")
to
sMailBody = Replace(sMailBody, "{*~BACKGROUND~*}", Session("LiveURL"))
Basic rules:
Replace need 3 string parameters
A double quote in a string literal must be escaped by ""
VBScript does not interpolate/splice in variable content into string literals
concatenating the empty string - & "" - is a waste of time
The other Replace lines compile, but isn't there a Next missing?
Update thanks to #Lankymart's comment:
... Assuming you want to replace the placeholder {*~BACKGROUND~*} in sMailBody with the single-quoted content of Session("LiveURL") ...
The error in the original code and my probably wrong interpretation of jackncode's intention shows that building strings by concatenation adds so much noise to the expression that it gets messed up easily. See the millions of questions wrt putting quoted pathes and other parameters into command lines for .Run or .Exec.
For such cases it pays to write functions that do the 'embracing' so that you DRY the tangle of funny letters:
>> Function q(s) : q = "'" & s & "'" : End Function
>> Function qq(s) : qq = """" & s & """" : End Function
>> s = "x"
>> t = "<tag attr=#>"
>> WScript.Echo Replace(t, "#", q(s))
>> WScript.Echo Replace(t, "#", qq(s))
>>
<tag attr='x'>
<tag attr="x">
(cf. here)

ASP MVC 3 - Export to CSV method including junk characters not in database

Below is the (crude) method I'm using to export the contents of a table into a CSV. I came up with this on the fly, however the data in the table has been loaded from an Excel spreadsheet created by a Sharepoint site. I do not know if that conversion process or my method is the cause, but a large number of these characters: Â are being imported into the cells.
Also, a large number of records are having their fields split up into two rows as opposed to just one. This is my first attempt at exporting to a CSV programatically (as opposed to using excel) so any help would be greatly apprecitated.
Controller Method
public ActionResult ExportToCsv()
{
using (StringWriter writer = new StringWriter())
{
var banks = db.BankListMaster.Include(b => b.BankListAgentId).ToList();
writer.WriteLine("Bank Name, EPURL, AssociatedTPMBD, Tier, FixedLifeMasterSAF, VariableLifeMasterSAF, FixedLifeSNY, VariableLifeMasterSNY, SpecialNotes, WelcomeLetterReq, " +
"BackOfficeNotification, LinkRepsToDynamics, RelationshipCode, INDSGC, PENSGC, LicensingContract, MiscellaneousNotes, ContentTypeID1, CreatedBy, MANonresBizNY, Attachment");
foreach (var item in banks)
{
writer.Write(item.BankName + ",");
if(String.IsNullOrWhiteSpace(item.EPURL))
{
writer.Write(item.EPURL + ",");
}
else
{
writer.Write(item.EPURL.Trim() + ",");
}
writer.Write(item.AssociatedTPMBD + ",");
writer.Write(item.Tier + ",");
writer.Write(item.LicensingContract + ",");
writer.Write(item.MiscellaneousNotes + ",");
writer.Write(item.ContentTypeID1 + ",");
writer.Write(item.CreatedBy + ",");
writer.Write(item.MANonresBizNY + ",");
writer.Write(item.Attachment);
writer.Write(writer.NewLine);
}
return File(new System.Text.UTF8Encoding().GetBytes(writer.ToString().Replace("Â", "")), "text/csv", "BankList.csv");
}
}
CSV is a file format that's poorly specified. Several important things aren't specified:
The field separator. Even though it's called "comma separated", Excel will use the semicolon sometimes (depending on your locale!).
The encoding (UTF-8, ISO-8859-1, ANSI/Windows-1252 etc.)
The kind of newlines (CR, NL or CR NL).
Whether all fields have to be quoted with double quotes or just the ones containing the field separator, the line separator, blanks etc.
Whether white space is trimmed from unquoted fields.
Whether newlines are allowed within quoted fields (Excel allows them).
How double quotes are escaped if they are part of the field content (normally they are doubled)
Excel is usually the reference for a valid CSV format. But even Excel chooses the field separator and the encoding depending on your locale.
In your case, the encoding is most likely the main problem. You use UTF-8 but the consumer treats it as ISO-8859-1 or ANSI. For that reason, the character  often appears whose binary code is used in UTF-8 to introduce a two byte sequence. Change the encoding to fix the Â.
As the next step, properly quote the text fields, i.e. add double quotes at the start and at the end and double all double quotes within the field.

Ruby on Rails: How can i take/cut first 300 words or characters from a string?

I need to take/cut first 300 words or characters from a string.
That means, I need a limited number of characters from a string, from the beginning.
Something like truncating.
Is there a function to do this?
str = "many words here words words words ..."
first_500_words = str.split(" ").first(500).join(" ")
first_500_chars = str[0..500]
Depending on the size of your text and performance needs, one option is #text.split(/\s+/).slice(0,300).join(' ')
If you actually want to truncate on character level, which is advisable because different words differ in display length quite a bit, use:
def truncate_words(text, length = 300, end_string = ' …')
words = text.split()
words[0..(length-1)].join(' ') + (words.length > length ? end_string : '')
end
which I found here: http://snippets.dzone.com/posts/show/804
If you're using Rails, you can also use string.truncate but it does not take into account word boundries.
str = "this is really long string which I want to truncate..."
str.truncate 300, separator: " "
or if you prefer to youse brackets
str.truncate(300, separator: " ")
It's the most elegant solution of all above. As you mentioned in the topic, you use Rails so it will work. If you code in raw Ruby, you should write something like this:
str.split.first(300).join " "
The split method no need to take argument if you need to split the text by spaces.

Resources