rails how can you convert / to \ in a file name - ruby-on-rails

I am working on selecting files to email and then passing them to the user's notes email client.
The string I want to send to the system command should be in the format of:
"C:\Program Files (x86)\IBM\Lotus\Notes\notes.exe"
Mailto:chris#mydomain.com?Subject=MailSubject?Attach=C:\test.bat
However, the code
$attached_files = $attached_files + "?Attach="+ Rails.root.to_s + "/public/images/" + document.id.to_s + "/" + document.doc_file_file_name
gives me forward slashes instead:
C:/Users/cmendla/RubymineProjects/technical_library/public/images/2/High_Durability.pdf
When that is passed to system() it won't launch the notes email. I think that the problem is that the server looks for / and the windows pc looks for \
Is there any way to easily change / to \ at least for the time being for testing?

Have you tried
Rails.root.join("public","images", document.id, document.doc_file_file_name)
?

Related

Need to collect only emails using Ruby code

I've received a list of emails that I'd like to run an email campaign on, however, in the list there are some URL's... and it complicates things.
Here's the standard formatting of the email address, for example:
news#ydr.com
I'd like to paste the list in terminal and run a command to ONLY capture all of the email addresses and save them to a file and remove any URLS.
Please advise! It is much appreciated :)
If you are just looking to catch most emails this regex might work.
I got this regex from here How to validate an email address using a regular expression?
They talk about the much more complicated RFC822 email regex
#!/usr/bin/env ruby
input = $stdin.readlines # ctrl + D after paste
input.each do |f|
puts f if f[/^[a-zA-Z0-9_.+\-]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/]
end
# test input
# foo#bar.com
# www.cnn.com
# test.email#go.com
# turdburgler#mcdo.net
# http://www.google.com
To write emails to a file:
#!/usr/bin/env ruby
file = File.open("emails.txt", "w")
input = $stdin.readlines # ctrl + D after paste
input.each do |f|
file.write(f) if f[/^[a-zA-Z0-9_.+\-]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-.]+$/]
end
file.close
Just to be clear, this is a ruby script which should be ran like this.
Save the script as a file, ie email_parser.rb.
chmod +x email_parser.rb
./email_parser.rb # this will wait for stdin, here you paste the list in to the terminal
When the terminal is hanging waiting, paste the list of emails in, then press ctrl + D to tell the program that this is the EOF. The program will then run through the list of emails/urls and parse. The output of this will be a file if using the updated script. The file will be in the same folder you ran the script and be called emails.txt

Mixing Ruby and bash commands -- mv returns "x and y are the same file"

So I have a Ruby script (using Ruby because we have a library of pre-existing code that I need to use). From within Ruby I am using backticks to call Linux commands, specifically in this case the "mv" command. I am trying to move one file to another location but I keep getting the error message that x and y are "the same file" even though they are very clearly NOT the same file.
Here is the code in Ruby:
#!/usr/local/rvm/rubies/ruby-2.1.1/bin/ruby
masterFiles=[]
masterFiles << "/mnt/datadrive/Data Capture/QualityControl/UH_HRA_SVY/Scans and DataOutput/Data/UH_HRA_SVY_DATA.txt"
masterFiles << "/mnt/datadrive/Data Capture/QualityControl/UH_HRA_SVY_SPAN/Scans and DataOutput/Data/UH_HRA_SVY_SPAN_DATA.txt"
tm=Time.new.strftime("%Y%m%d")
masterFiles.each do |mf|
if File.exist?(mf)
qmf=39.chr + mf + 39.chr
`cat #{qmf} >> /tmp/QM`
savename=39.chr + \
"/mnt/datadrive/Data Capture/QualityControl/UH_HRA_SVY/Scans and DataOutput/Data/DailyFiles/" + \
File.basename(mf).gsub(".txt","_"+tm) + ".txt" + 39.chr
`mv #{qmf} #{savename}`
end
end
The error that I get is this:
mv: `/mnt/datadrive/Data Capture/QualityControl/UH_HRA_SVY_SPAN/Scans
and DataOutput/Data/UH_HRA_SVY_SPAN_DATA.txt' and `/mnt/datadrive/Data
Capture/QualityControl/UH_HRA_SVY/Scans and
DataOutput/Data/DailyFiles/UH_HRA_SVY_SPAN_DATA_20140530.txt' are the
same file
If I change this line:
`mv #{qmf} #{savename}`
To this:
puts "mv #{qmf} #{savename}"
And then run the output, it works as expected.
I am pretty sure that this has to do with spaces in the path. I have tried every combination of double-quoting, triple-quoting, quadruple-quoting, and back-slashing I can think of to resolve this but no go. I have also tried using FileUtils.mv but get what is basically the same error worded differently.
Can anybody help ? Thanks a lot.
p.s. I realize it's entirely possible that I could be going about this in an entirely wrong-headed way, so feel free to point that out if so. However, I am trying to use the tools which I already have some knowledge of (cat, mv, etc) instead of re-inventing the wheel.
You could use FileUtils.mv
I often do aliases like so:
require 'fileutils'
def mv(from, to)
FileUtils.mv(from, to)
end
And inside the mv() method I do additional safeguards, i.e. if the file does not exist, if there is a lack of permissions and so forth.
If you then still have problems with filenames that have ' ' blank characters, try to put the file into a "" quote like:
your_target_location = "foo/bar bla"

phantomjs: How to run phantomjs command when Url with queryparams

I am using Phantomjs to generate pdf from web page.
Using following command to generate pdf:
`phantomjs rasterize.js http://www.myurl.com?q=123&&selected_opts%5B%5D=fs&selected_opts%5B%5D=disc form1.pdf`
where, selected_opts is array type
It is giving me error - form1.pdf: not found or selected_opts%5B%5D=fs: not found
If I remove querystring from url then it generate pdf, any idea how to run phantomjs having url with querystring.
You need to protect all & chars with a backslash :
phantomjs rasterize.js http://www.myurl.com?q=123\&s=foo form1.pdf
Ampersand is annoying in console so you need to protect it like above. In a ruby script you need to protect backslash that protect & :
`phantomjs rasterize.js http://www.myurl.com?q=123\\&s=foo form1.pdf`
example :
`phantomjs rasterize.js https://www.google.fr/search?q=rasterize.js+special+char\\&oq=rasterize.js google1.pdf`

iOS UI Automation- performtaskwithpatharguments- curl

Please help!!! I am trying to add some performtaskwithpathargumentstimeout functions to my ios UI automation javascript. Specifically I am submitting a form within the app and subsequently want to check that it has been submitted successfully. However I am having problems.
I want to do several things. The ideal was to do a curl request to a url, and then search the stdout body that comes back to ensure that several keywords were there. However, instruments keeps crashing when I try and use any indexOf or .search functions on the result.stdout...
I thought another option would be to output the html to a file, and then search that file by writing a command line application which will search for the keyword passed as an argument. However, when I try and output the file to a directory using the following-
var target = UIATarget.localTarget();
var host = target.host();
result = target.host().performTaskWithPathArgumentsTimeout("usr/bin/curl", ["-o /Users/andrewweaver/Documents/output.html", "http://www.google.co.uk"], 30);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
UIALogger.logDebug("stderr: " + result.stderr);
I get the following error-
Warning: Failed to create the file /Users/me/Documents/output.html:
\nWarning: No such file or directory
This directory DOES exist, and has permissions for anyone to read & write to it.... also, if I create the .html file in that directory the same thing happens. If I run the same command from terminal it works fine...
I also wanted to do a write out of the http code...
result = target.host().performTaskWithPathArgumentsTimeout("usr/bin/curl", ["--write-out %{http_code}", "http://www.google.co.uk"], 30);
But again, that is failing....
curl: option --write-out %{http_code}: is unknown
I'm not sure what I'm doing wrong....
Any help would be much appreciated : - )
Fixed it. Each of the args passed into performTaskWithPathArgumentsTimeout needs to be separated by "" and a ,
So, for example to query a website and write the output to a file...
var host = target.host();
var result = target.host().performTaskWithPathArgumentsTimeout("usr/bin/curl", ["-o", "/Users/me/Documents/football.html", "http://www.bbc.co.uk/"], 30);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
And then to search the outputted file for a particular element I use grep...
var str = "BBC Sport - Football";
var result = target.host().performTaskWithPathArgumentsTimeout("usr/bin/grep", ["-w", (str), "/Users/me/Documents/football.html"], 15);
UIALogger.logDebug("exitCode: " + result.exitCode);
UIALogger.logDebug("stdout: " + result.stdout);
This will return a 0 if the regex is found, and BBC Sport - Football as the stdout.
I can then use an if statement to pass or fail (or use a tuneup js assert) based on whether the expected expression is present...
Useful for sending requests to webservices and then verifying the content...

Converting pdf's to images with Imagemagick + RMagic

I'm using paperclip at the moment to convert pdf files to images.
My code looks something like this
def convert_keynote_to_slides
system('convert -size 640x300 ' + keynote.queued_for_write[:original].path + ' ' + KEYNOTE_PATH + '/' + File.basename( self.keynote_file_name )+"%02d.png")
slide_basename = File.basename( self.keynote_file_name )
files = Dir.entries(KEYNOTE_PATH).sort
for file in files
#puts file if file.include?(slide_basename +'-')
self.slides.build("slide" => "#{file}") if file.include?(slide_basename)
end
end
I'm sure this can be re-factored to work better.
My questions are:
Is there a way to figure out the progress of ImageMagick if not how would I put this into a delayed job as im worried this wont scale very well.
Can anyone point me in the direction as to how to make this code better / more efficient. The KEYNOTE_PATH points to a directory in public where all of the images are held in a single folder im not sure if I like this or not. What would probably be better is to assign a random name to each file.
I hope you're doing extensive filtering of keynote.queued_for_write[:original].path and File.basename( self.keynote_file_name ) input variables, so you're not susceptible to shell meta-character injection attacks.

Resources