Ruby on Rails - string to array weird formatting in email parsing - ruby-on-rails-3

I can get the body of an email in String format like so
body = params[:plain]
And when I output it, it looks like:
Hi there.
--
John B.
Sent from my iPhone.
Now, when I try and split by newline body.split("\n") I get:
---
- ! 'Hi there.'
- ''
- ! '-- '
- John B.
- ''
- Sent from my iPhone.
I don't really understand the extra hyphens and bangs. Any thoughts?
Also if I do body[2] I get --, but body.index("--") returns me nothing.
UPDATE
In my ReceivingMails controller:
...
def create
body = params[:plain]
parsed_body = parse_body(body)
Comment.new(:content => parsed_body)
end
private
def parse_body(body)
split = body.split("\n")
sig_index = split.index("-- ")
return split[0, sig_index].join("\n")
end
In my view, comments are shown as: <%= simple_format(comment.content)%>
UPDATE 2
When I do something like, body.split("\n").to_s I get what the expected array should look like (as String): ["Hi there. ", "", "-- ", "John B.", "", "Sent from my iPhone."]

I don't think params[:plain] is actually a string - I think you should test it to find out what it actually is. For example try:
puts params[:plain].class

Related

Karate framework variable usage

I have this steps:
...
Then status 200
And match response.requests[0].request.url == "/endpoint"
And json body = response.requests[0].request.body
And match body == { "something": "something"}
To simplify, I tried to put response.requests[0].request in a variable called request:
...
Then status 200
And def request = response.requests[0].request
And match request.url == "/endpoint"
And json body = request.body
And match body == { "something": "something"}
I'm having the following error:
'request' is not a variable, use the form '* request <expression>' instead
I read the documentation and the use of request seems to be fine:
Given def color = 'red '
And def num = 5
Then assert color + num == 'red 5'
What am I doing wrong?
Thanks in advance.
Just make this change:
* def req = response.requests[0].request
# other steps
* request req
We simply disallow def request (using request as a variable name) because a lot of newbie users get confused. The error message has worked 99.9% of the time for users to understand what the problem is, but I guess you fall in the 0.1% :)

How to send a variable to a text file that calling to karate feature file...?

Step 01#: I am calling 'Request Date' from json file and saving as "RequestDate"
Background:
json req = read('classpath:XXX/XXX/API/02_Dataset/DataSet.json')
* def RequestDate = get req.GameEnq.RequestDate
Step 02#: I am also calling 'GameDetailsRequest' from json file which has the field called "RequestDate", I would like pass "RequestDate" into "GameDetailsRequest".
Scenario: GameEnq
Given request
"""
GameDetailsRequest
"""
* def GameDetailsRequest = read('classpath:XXX/XXX/API/02_Dataset/ServiceRequestData_GameEnq');
Note: I can able to print the "RequestDate" value correctly ,however i don't know how to call into "GameDetailsRequest"... Please assist me. Your suggestion highly appreciated
Kind Regards
Sudheer Bonam
I think you need to try replace for a text place holder replacement
Add a placeholder <PLACEHOLDER_NAME> in your text data in GameDetailsRequest where you want to insert RequestDate
eg:
* string GameDetailsRequest = "Game release data : <RequestDate>"
* replace GameDetailsRequest.RequestDate = "12-12-2020"
Now GameDetailsRequest will be "Game release data : 12-12-2020"
refer: karate doc for replace

How can I signal parsing errors with LPeg?

I'm writing an LPeg-based parser. How can I make it so a parsing error returns nil, errmsg?
I know I can use error(), but as far as I know that creates a normal error, not nil, errmsg.
The code is pretty long, but the relevant part is this:
local eof = lpeg.P(-1)
local nl = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n" + eof -- \r for winblows compat
local nlnoeof = (lpeg.P "\r")^-1 * lpeg.P "\n" + lpeg.P "\\n"
local ws = lpeg.S(" \t")
local inlineComment = lpeg.P("`") * (1 - (lpeg.S("`") + nl * nl)) ^ 0 * lpeg.P("`")
local wsc = ws + inlineComment -- comments count as whitespace
local backslashEscaped
= lpeg.P("\\ ") / " " -- escaped spaces
+ lpeg.P("\\\\") / "\\" -- escaped escape character
+ lpeg.P("\\#") / "#"
+ lpeg.P("\\>") / ">"
+ lpeg.P("\\`") / "`"
+ lpeg.P("\\n") -- \\n newlines count as backslash escaped
+ lpeg.P("\\") * lpeg.P(function(_, i)
error("Unknown backslash escape at position " .. i) -- this error() is what I wanna get rid of.
end)
local Line = lpeg.C((wsc + (backslashEscaped + 1 - nl))^0) / function(x) return x end * nl * lpeg.Cp()
I want Line:match(...) to return nil, errmsg when there's an invalid escape.
LPeg itself doesn't provide specific functions to help you with error reporting. A quick fix to your problem would be to make a protected call (pcall) to match like this:
local function parse(text)
local ok, result = pcall(function () return Line:match(text) end)
if ok then
return result
else
-- `result` will contain the error thrown. If it is a string
-- Lua will add additional information to it (filename and line number).
-- If you do not want this, throw a table instead like `{ msg = "error" }`
-- and access the message using `result.msg`
return nil, result
end
end
However, this will also catch any other error, which you probably don't want. A better solution would be to use LPegLabel instead. LPegLabel is an extension of LPeg that adds support for labeled failures. Just replace require"lpeg" with require"lpeglabel" and then use lpeg.T(L) to throw labels where L is an integer from 1-255 (0 is used for regular PEG failures).
local unknown_escape = 1
local backslashEscaped = ... + lpeg.P("\\") * lpeg.T(unknown_escape)
Now Line:match(...) will return nil, label, suffix if there is a label thrown (suffix is the remaining unprocessed input, which you can use to compute for the error position via its length). With this, you can print out the appropriate error message based on the label. For more complex grammars, you would probably want a more systematic way of mapping the error labels and messages. Please check the documentation found in the readme of the LPegLabel repository to see examples of how one may do so.
LPegLabel also allows you to catch the labels in the grammar by the way (via labeled choice); this is useful for implementing things like error recovery. For more information on labeled failures and examples, please check the documentation.

Rails - How to test that ActionMailer sent a specific attachment?

In my ActionMailer::TestCase test, I'm expecting:
#expected.to = BuyadsproMailer.group_to(campaign.agency.users)
#expected.subject = "You submitted #{offer_log.total} worth of offers for #{offer_log.campaign.name} "
#expected.from = "BuyAds Pro <feedback#buyads.com>"
#expected.body = read_fixture('deliver_to_agency')
#expected.content_type = "multipart/mixed;\r\n boundary=\"something\""
#expected.attachments["#{offer_log.aws_key}.pdf"] = {
:mime_type => 'application/pdf',
:content => fake_pdf.body
}
and stub my mailer to get fake_pdf instead of a real PDF normally fetched from S3 so that I'm sure the bodies of the PDFs match.
However, I get this long error telling me that one email was expected but got a slightly different email:
<...Mime-Version: 1.0\r\nContent-Type: multipart/mixed\r\nContent-Transfer-Encoding: 7bit...> expected but was
<...Mime-Version: 1.0\r\nContent-Type: multipart/mixed;\r\n boundary=\"--==_mimepart_50f06fa9c06e1_118dd3fd552035ae03352b\";\r\n charset=UTF-8\r\nContent-Transfer-Encoding: 7bit...>
I'm not matching the charset or part-boundary of the generated email.
How do I define or stub this aspect of my expected emails?
Here's an example that I copied from my rspec test of a specific attachment, hope that it helps (mail can be creating by calling your mailer method or peeking at the deliveries array after calling .deliver):
mail.attachments.should have(1).attachment
attachment = mail.attachments[0]
attachment.should be_a_kind_of(Mail::Part)
attachment.content_type.should be_start_with('application/ics;')
attachment.filename.should == 'event.ics'
I had something similar where I wanted to check an attached csv's content. I needed something like this because it looks like \r got inserted for newlines:
expect(mail.attachments.first.body.encoded.gsub(/\r/, '')).to(
eq(
<<~CSV
"Foo","Bar"
"1","2"
CSV
)
)

grails internationalization (i18n)

i work on grails project
def result = "customer"
//(this value is according to returned method parameter,
//it may be customer, company,... & so on)
def messages = "${message(code: 'default.result.${result}', default:'${result}')}"
i need to send a variable inside message code as i mention above
problem: this code appears as
default.result.${result}
that there is no code in message.properties refer to these code
there is default.result.customer ....$ so on
Question: how can i send variable inside message Code?
Try omitting the double quotes (GString) and it should work like the following:
def xxx = "bar"
def m = message(code: "foo.${xxx}", args: ['hello world'])
Results in following message-code
foo.bar
Try:
def messages = message(code: 'default.result.' + result, default: result)
If you want to pass in some values, e.g. a string, you can define your message like this:
default.result.success = Action {0} was successfull.
And resolve your code like this:
def m = message(code: 'default.result.' + result, args: ['delete User'])