Add a specific line from a document.txt to a comment field with specific id and then move to next line? - ruby-on-rails

How can I add a specific line from my document.txt to YouTube comment field with specific id and then move to next line on my document.txt. The id of YouTube comment field is 'contenteditable-root'. I have created this code but the text that is been added on the YouTube comment field show in brackets for example ["Hello"]
Or in second example it shows nothing
Example 1:
file = 'comments.txt'
File.readlines(file).each do |i|
files = [i]
files.each { |val|
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{files}';")
}
end
Example 2:
line_number = 1
loop do
comments = IO.readlines('comments.txt')[line_number-1]
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{comments}';")
line_number += 1
end
comment.txt file:
Hellooo !!
hi
Goodbye
Goodnight

Assuming a whole bunch of other things here are correct, you're doing a very weird iteration, you should just use:
file = 'comments.txt'
File.readlines(file).each do |i|
browser.execute_script("document.getElementById('contenteditable-root').innerHTML = '#{i}';")
end

Seems to me like you need to learn how to debug.
Step 1: Check in irb (about irb) if your code is printing the correct text:
File.readlines('comments.txt').each do |line|
p line
end
Expected output:
=> "Line 1"
=> "Line 2"
=> "Line 3"
If not, then look up how to read a file per line.
Step 2: Does your piece of Javascript actually work?
Go to the page you're trying to test, Open the debugger (F12) and run your Javascript directly from the console:
document.getElementById('contenteditable-root').innerHTML = 'hi';
If it doesn't work, then try learning more abut Javascript on how it works interacting with elements.
Step 3: Does my piece of code actually work from Watir?
Open up irb again and try it out
require 'watir'
b = Watir::Browser.new
b.goto 'https://youryoutubepage.com/path'
b.execute_script("document.getElementById('contenteditable-root').innerHTML = 'hi';")
If it fails, google the error, look for Watir and execute_script.
Then finally run the whole combination of your code in irb:
require 'watir'
b = Watir::Browser.new
b.goto 'https://youryoutubepage.com/path'
File.readlines('comments.txt').each do |line|
b.execute_script("document.getElementById('contenteditable-root').innerHTML = 'hi';")
sleep 5 # Give yourself some time to visually confirm the changes.
end
A quick Google about your SyntaxError: Invalid or unexpected token (Selenium::WebDriver::Error::UnknownError) I see it might be a problem with the quotations that execute_script doesn't like.
Maybe try reversing the quotes:
b.execute_script('document.getElementById("contenteditable-root").innerHTML = "hi";')
In the future, please try to pinpoint your problem and don't use StackOverflow as a place to debug your code. Get your code to work step by step and focus your question on a specific function that's not working as expected.

Related

Problem with attachments' character encoding using gmail gem in ruby/rails

What I am doing:
I am using the gmail gem in a Rails 4 app to get email attachments from a specific account at regular intervals. Here is an extract from the core part (here for simplicity only considering the first email and its first attachment):
require 'gmail'
Gmail.connect(#user_email,#user_password) do |gmail|
if gmail.logged_in?
emails = gmail.inbox.emails(:from => #sender_email)
email = emails[0]
attachment = email.message.attachments[0]
File.open("~/temp.csv", 'w') do |file|
file.write(
StringIO.new(attachment.decoded.to_s[2..-2].force_encoding("ISO-8859-15").encode!('UTF-8')).read
)
end
end
end
The encoding of the attached file can vary. The particular one that I am currently having issues with is in Finnish. It contains Finnish characters and a superscripted 3 character.
This is what I expect to get when I run the above code. (This is what I get when I download the attachment manually through gmail user interface):
What the problem is:
However, I am getting the following odd results.
From cat temp.csv (Looks good to me):
With nano temp.csv (Here I have no idea what I am looking at):
This is what temp.csv looks like opened in Sublime Text (directly via winscp). First line and small parts look ok but then Chinese/Japanese characters:
This is what temp.csv looks like in Notepad (after download via winscp). Looks ok except a blank space has been inserted between each character and the new lines seems to be missing:
What I have tried:
I have without success tried:
.force_encoding(...) with all the different "ISO-8859-x" character sets
putting the force_encoding("ISO-8859-15").encode!('UTF-8') outside the .read (works but doesn't solve the problem)
encode to UTF-8 without first forcing another encoding but this leads to Encoding::UndefinedConversionError: "\xC4" from ASCII-8BIT to UTF-8
writing as binary with 'wb' and 'w+b' in the File.open() (which oddly doesn't seem to make a difference to the outcome).
searching stackoverflow and the web for other ideas.
Any ideas would be much appreciated!
Not beautiful, but it will work for me now.
After re-encoding, I convert the string to a char array, then remove the chars I do not want and then join the remaining array elements to form a string.
decoded_att = attachment.decoded
data = decoded_att.encode("UTF-8", "ISO-8859-1", invalid: :replace, undef: :replace).gsub("\r\n", "\n")
data_as_array = data.chars
data_as_array = data_as_array.delete_if {|i| i == "\u0000" || i == "ÿ" || i == "þ"}
data = data_as_array.join('').to_s
File.write("~/temp.csv", data.to_s)
This will work for me now. However, I have no idea how these characters have ended up in the attachment ("ÿ" and "þ" in the start of the document and "\u0000" between all remaining characters).
It seems like you need to do attachment.body.decoded instead of attachment.decoded

Read next line during file IO in Ruby

I am trying to import a file using ruby and parse it. Is there a way to read the next line once inside the file import? Basically I want to see if a specific line is within x lines of another important line. Like does "x phrase" Come within 10 lines of "y phrase". I don't see a way to do this -- I know its simple with Java.
Thanks!
You can also try:
web_contents = "c:\\path\\to\\your\\file.txt"
File.open(web_contents).each_with_index do |line, i|
line.chomp!
puts "line #{line}, i #{i}" # Do whatever you want to here
end
The .each_with_index method gives you an index, i, which you can use to keep track of where on what line in your file you are. Simple maths can then yield the offset as required.
To read lines of a file
lines_array = IO.readlines('testfile')
lines_array.each { |l| #Do your stuff with your line }
Voilà
Ruby Docs on IO

Aptana Studio 3 Snippet Around Selection

So I have recently switched from Dreamweaver to Aptana Studio 3 and I have been playing around with the whole custom snippet feature. For the life of me though I cannot figure out how to take a selection/highlighted text and wrap it with my own custom code and/or text. I have looked around the internet for three days now and cannot find anything regarding snippets. I have found some things using commands and key combinations, but I am wanting to create and use a snippet and trying to modify what I have found is not producing good fruit.
I have been able to create my own category and some basic snippets that insert straight text, but nothing that uses a selection.
I have absolutely NO experience with Ruby so forgive me if what follows is completely atrocious. I have more experience with PHP, HTML, Javascript, Java, etc. Here is what I have so far.
snippet "Selection Test" do |snip|
snip.trigger = "my_code"
snip.input = :selection
selection = ENV['TM_SELECTED_TEXT'] || ''
snip.expansion = "<test>$selection</test>\n"
snip.category = "My Snippets"
end
I haven't done much with custom Snippets, but if it helps, there is an example in the HTML bundle of a snippet that surrounds the selected text with <p></p> tags when you do Ctrl + Shift + W. You can see the code for it in snippets.rb in the HTML bundle:
with_defaults :scope => 'text.html - source', :input => :none, :output => :insert_as_snippet do |bundle|
command t(:wrap_selection_in_tag_pair) do |cmd|
cmd.key_binding = "CONTROL+SHIFT+W"
cmd.input = :selection
cmd.invoke do |context|
selection = ENV['TM_SELECTED_TEXT'] || ''
if selection.length > 0
"<${1:p}>${2:#{selection.gsub('/', '\/')}}</${1:p}>"
else
"<${1:p}>$0</${1:p}>"
end
end
end
end
I fiddled around with putting it into the PHP bundle for a few minutes under CTRL + Shift + P and got it working in HTML files, which was not my goal... but was progress. I may play around with it some more later, but in the meantime, maybe you know enough after all of your research to get something put together. I would be interested to see your results if you get this figured out.

Headers on the second row in FasterCSV?

G'day guys, I'm currently using fasterCSV to parse a CSV file in ruby, and wondering how to get rid of the initial row of data on a CSV (The initial row contains the time/date information generated by another software package)
I tried using fasterCSV.table and then deleting row(0) then converting it to a CSV document then parsing it
but the row was still present in the document.
Any other ideas?
fTable = FasterCSV.table("sto.csv", :headers => true)
fTable.delete(0)
Three suggestions
Can you get FasterCSV to ignore the line?
You could use the :return_headers => true option to skip over the bad line. That'll work great if the second line isn't the real header. See here for more
:return_headers:
When false, header rows are silently
swallowed. If set to true, header rows
are returned in a FasterCSV::Row
object with identical headers and
fields (save that the fields do not go
through the converters).
Chop the line off with another tool
You don't need to use Ruby for this - how about chopping the file using one of the solutions suggested here you can call the one-liners from Ruby using the system method.
Max Flexibility - parse the file line by line with FasterCSV
Have you considered reading the file directly, skipping the first line and then accepting or rejecting lines? Deep in the heart of my code is this parse method which treats the file as a series of lines, accepting or rejecting each. You could do something similar but skip over the first row.
The neat thing is that you get to determine which rows are acceptable by defining your own acceptable? method - only valid CSV data is passed to acceptable? the rest are thrown away in response to the exception.
def parse(file)
#
# Parse data
#
row = []
file.each_line do |line|
the_line = line.chomp
begin
row = FasterCSV.parse_line(the_line)
ok, message = acceptable?(row)
if not ok
reject(file.lineno, the_line, message)
else
accept(row, the_line)
end
rescue FasterCSV::MalformedCSVError => e
reject(file.lineno, the_line, e.to_s)
end
end
hi doing just that with some data for Australian Electoral Commission. The file in question has a date string on the first line and headers on the second
require 'csv'
require 'open-uri'
filename = "http://results.aec.gov.au/15508/Website/Downloads/SenateGroupVotingTicketsDownload-15508.csv"
file = File.open(open(filename))
first_line = file.readline
CSV.parse(file, headers: true).each do |row|
puts row["State"]
end
I presume the file I quote still exists but that can be replaced by the file in question. if you need to skip more rows you have to call file.readline that number of times.
According to the docs, fTable = FasterCSV.table("sto.csv", :return_headers => false) should do what you want. .table implies :headers => true The docs have this info.

Reading the first line of a file in Ruby

I want to read only the first line of a file using Ruby in the fastest, simplest, most idiomatic way possible. What's the best approach?
(Specifically: I want to read the git commit UUID out of the REVISION file in my latest Capistrano-deployed Rails directory, and then output that to my tag. This will let me see at an http-glance what version is deployed to my server. If there's an entirely different & better way to do this, please let me know.)
This will read exactly one line and ensure that the file is properly closed immediately after.
strVar = File.open('somefile.txt') {|f| f.readline}
# or, in Ruby 1.8.7 and above: #
strVar = File.open('somefile.txt', &:readline)
puts strVar
Here's a concise idiomatic way to do it that properly opens the file for reading and closes it afterwards.
File.open('path.txt', &:gets)
If you want an empty file to cause an exception use this instead.
File.open('path.txt', &:readline)
Also, here's a quick & dirty implementation of head that would work for your purposes and in many other instances where you want to read a few more lines.
# Reads a set number of lines from the top.
# Usage: File.head('path.txt')
class File
def self.head(path, n = 1)
open(path) do |f|
lines = []
n.times do
line = f.gets || break
lines << line
end
lines
end
end
end
You can try this:
File.foreach('path_to_file').first
How to read the first line in a ruby file:
commit_hash = File.open("filename.txt").first
Alternatively you could just do a git-log from inside your application:
commit_hash = `git log -1 --pretty=format:"%H"`
The %H tells the format to print the full commit hash. There are also modules which allow you to access your local git repo from inside a Rails app in a more ruby-ish manner although I have never used them.
first_line = open("filename").gets
I think the jkupferman suggestion of investigating the git --pretty options makes the most sense, however yet another approach would be the head command e.g.
ruby -e 'puts `head -n 1 filename`' #(backtick before `head` and after `filename`)
Improving on the answer posted by #Chuck, I think it might be worthwhile to point out that if the file you are reading is empty, an EOFError exception will be thrown. Catch and ignore the exception:
def readit(filename)
text = ""
begin
text = File.open(filename, &:readline)
rescue EOFError
end
text
end
first_line = File.readlines('file_path').first.chomp

Resources