Ruby strptime method error - ruby

So I am working through a tutorial building an event manager program and I'm a bit stuck. I want to build a method that will take registration data from a .csv file and then extract the hour times when people registered. However I'm having trouble getting it to work. Here's what I have so far:
def reg_hour(regtime)
regtime = DateTime.new
DateTime.strptime(regtime, "%H")
end
When I run the code though I get this error:
`block in _strptime_i': undefined method `sub!' for #<DateTime: -4712-01-01T00:00:00+00:00 (-1/2,0,2299161)> (NoMethodError)
I am quite confused and any help would be greatly appreciated.
Here's the link to the tutorial if anyone is interested.
http://tutorials.jumpstartlab.com/projects/eventmanager.html

Not sure what you're doing with the DateTime.new and overriding the regtime variable (I'm new to ruby myself). If the regtime is coming out of a csv file, it's probably coming out as a string. Perhaps you could use a regular expression as long as the regdate format is consistent.
If regdate is: "11/12/08 10:47"
Then using:
regdate.scan(/\s\d+:/)
Would return [" 10:"]. Perhaps then you could store that in a array variable and clean it up by removing white space and the colon. There's probably a more elegant solution, but that's my newbie brute force way.

I am not quite sure I fully understand your intentions, but here it is rewritten:
require 'time'
def reg_hour(regtime)
DateTime.strptime(regtime, "%H")
end
d = reg_hour("21/03/2011 14:39:11.642")
puts d.year
Is this something you're trying to do?

Related

How do I best dump a Psych::Nodes::Document back to a YAML string?

This does what I want, but going via to_ruby seems unnecessary:
doc = Psych.parse("foo: 123")
doc.to_ruby.to_yaml
# => "---\nfoo: 123\n"
When I try to do this, I get an error:
DEV 16:49:08 >> Psych.parse("foo: 123").to_yaml
RuntimeError: expected STREAM-START
from /opt/…/lib/ruby/2.5.0/psych/visitors/emitter.rb:42:in `start_mapping'
I get the impression that the input needs to be a stream of some sort, but I don't quite get what incantation I need. Any ideas?
(The problem I'm trying to solve here, by the way (in case you know of a better way) is to fix some YAML that can't be deserialised into Ruby, because it references classes that don't exist. The YAML is quite complex, so I don't want to just search-and-replace in the YAML string. My thinking was that I could use Psych.parse to get a syntax tree, modify that tree, then dump it back into a YAML string.)
Figured out the incantation after finding the higher-level docs at https://ruby-doc.org//stdlib-2.3.0_preview1/libdoc/psych/rdoc/Psych/Nodes.html, though please let me know if there's a better way:
doc = Psych.parse("foo: 123")
stream = Psych::Nodes::Stream.new
stream.children << doc
stream.to_yaml
# => "foo: 123\n"

Is there a DB independent way to get Db2 SQL results in Ruby?

I have Rake code which I've cobbled together from some sample code in my shop, and the advice of another programmer. It looks more or less as follows:
class Ticket666StupidDb2Test < ActiveRecord::Migration
def up
lookup('WXYZ3529300')
end
def down
puts "down, boy!"
end
def lookup(xiskid)
qresult = exec_query("SELECT DISTINCT SNARK, GLOOPEE FROM VITA_XISK WHERE XISKID = '#{xiskid}'")
while row = IBM_DB.fetch_array(qresult) do
snark = row[0]
gloopee = row[1]
puts "snark = #{snark}; gloopee = #{gloopee}"
end
end
end
Is there a way to use the result set column names in getting the data, instead of integer indices? I looked at http://rubyibm.rubyforge.org/docs/adapter/2.5.9/doc/ActiveRecord/ConnectionAdapters/IBM_DBAdapter.html and found at least one method, fetch_data, which seemed as though it would allow one to reference column names, but every attempt to try to use it produced an error such as:
rake aborted!
undefined method `fetch_data' for #<ActiveRecord::ConnectionAdapters::IBM_DBAdapter:0x38c16c0>
What is wrong with this code, which was my first attempt:
x = exec_query("Select ... blah blah blah...")
x.each do |row|
puts row['SNARK']
end
This was modeled on stuff documented at http://api.rubyonrails.org/classes/ActiveRecord/Result.html, but it failed with a similar exception that x.each is undefined.
Regardless, the notion that I have to resort to anything like IBM_DB.whathaveyou strikes me as obscene. Either IBM doesn't believe in making a standards conforming driver (not my experience using the Db2 driver for Java JDBC), or I just don't know what the supported, straightforward approach to this is.
Can someone tell me?
ruby -v returns ruby 1.9.3p545 (2014-02-24) [i386-mingw32].
What is wrong with x = exec_query("Select ... blah blah blah...")? If your query is not SQL compliant then you've tied yourself to the DBM and will have a lot more work when you need to migrate to some other DBM. That's the whole point of using an ORM, to separate the code from the query. It also means you'll need to stand up an instance of DB2 for development, test and production because your code can't adjust for scenarios like using SQLite for development locally, MySQL or PostgreSQL in test and DB2 in production. That's really easy with a good ORM.
Using or renaming IBM_DB isn't a significant issue in my experience. If you don't like calling it IBM_DB, assign that constant to another that is more visually pleasing. Sequel code typically uses DB but it's up to us what we want to call it. It's just a constant holding the connection information.
Having to index into an array is the result of using fetch_array. Typically, instead of using integers to identify fields, I'd define constants that are more symbolic/mnemonic and use them in place of the numbers. But, again, a good ORM makes it easy to use classes/models based on the table schema, adding layers of convenience and readability to isolate you from the uglier lower level driver's API.
Look at using Active Record or Sequel. Sequel supports DB2 nicely and is easily as powerful as Active Record and works with Rails. Both also work well in a non-Rails script; Sequel is my favorite for that but YMMV.

Ruby RSS::Parser.to_s silently fails?

I'm using Ruby 1.8.7's RSS::Parser, part of stdlib. I'm new to Ruby.
I want to parse an RSS feed, make some changes to the data, then output it (as RSS).
The docs say I can use '#to_s', but and it seems to work with some feeds, but not others.
This works:
#!/usr/bin/ruby -w
require 'rss'
require 'net/http'
url = 'http://news.ycombinator.com/rss'
feed = Net::HTTP.get_response(URI.parse(url)).body
rss = RSS::Parser.parse(feed, false, true)
# Here I would make some changes to the RSS, but right now I'm not.
p rss.to_s
Returns expected output: XML text.
This fails:
#!/usr/bin/ruby -w
require 'rss'
require 'net/http'
url = 'http://feeds.feedburner.com/devourfeed'
feed = Net::HTTP.get_response(URI.parse(url)).body
rss = RSS::Parser.parse(feed, false, true)
# Here I would make some changes to the RSS, but right now I'm not.
p rss.to_s
Returns nothing (empty quotes).
And yet, if I change the last line to:
p rss
I can see that the object is filled with all of the feed data. It's the to_s method that fails.
Why?
How can I get some kind of error output to debug a problem like this?
From what I can tell, the problem isn't in to_s, it's in the parser itself. Stepping way into the parser.rb code showed nothing being returned, so to_s returning an empty string is valid.
I'd recommend looking at something like Feedzirra.
Also, as a FYI, take a look at Ruby's Open::URI module for easy retrieval of web assets, like feeds. Open-URI is simple but adequate for most tasks. Net::HTTP is lower level, which will require you to type a lot more code to replace the functionality of Open-URI.
I had the same problem, so I started debugging the code. I think the ruby rss has a few too many required elements. The channel need to have "title, link, description", if one is missing to_s will fail.
The second feed in the example above is missing the description, which will make the to_s fail...
I believe this is a bug, but I really don't understand the code and barely ruby so who knows. It would seem natural to me that to_s would try its best even if some elements are missing.
Either way
rss.channel.description="something"
rss.to_s
will "work"
The problem lies in def have_required_elements?
Or in the
self.class::MODELS

ruby parse HTTParty array - json

Still new to Ruby - I apologize in advance if this has been asked.
I am using HTTParty to get data from an API, and it is returning an array of JSON data that I can't quite figure out how to parse.
#<Net::HTTPOK:0x1017fb8c0>
{"ERRORARRAY":[],"DATA":[{"ALERT":1,"LABEL":"hello","WATCHDOG":1},{"LABEL":"goodbye","WATCHDOG":1}
I guess the first question is that I don't really know what I am looking at. When I do response.class I get HTTParty::Response. It appears to be a Hash inside an array? I am not sure. Anyway, I want a way to just grab the "LABEL" for every separate array, so the result would be "hello", "goodbye". How would I go about doing so?
you don't need to parse it per say. what you could do is replace ':' with '=>' and evaluate it.
example: say you have ["one":"a","two":"b"], you could set s to equal that string and do eval s.gsub(/^\[/, '{').gsub(/\]$/, '}').gsub('":', '"=>') will yield a ruby hash (with inspect showing {"one"=>"a", "two"=>"b"})
alternatively, you could do something like this
require 'json'
string_to_parse = "{\"one\":\"a\",\"two\":\"b\"}"
parsed_and_a_hash = JSON.parse(string_to_parse)
parsed_and_a_hash is a hash!
If that's JSON, then your best bet is to install a library that handles the JSON format. There's really no point in reinventing the wheel (although it is fun). Have a look at this article.
If you know that the JSON data will always, always be in exactly the same format, then you might manage something relatively simple without a JSON gem. But I'm not sure that it's worth the hassle.
If you're struggling with the json gem, consider using the Crack gem. It has the added benefit of also parsing xml.
require 'crack'
my_hash_array = Crack::JSON.parse(my_json_string)
my_hash_array = Crack::XML.parse(my_xml_string)

Need to build a url and work with the returned result

I would like to start with a little script that fetches the examination results of me and my friends from our university website.
I would like to pass it the roll number as the post parameter and work with the returned data,
I don't know how to create the post string.
It would be great if someone could tell me where to start, what are the things to learn, links to a tutorial would be most appreciated.
I don´t want someone to write code for me, just guidance on how to get started.
I've written a solution here just as a reference for whatever you might come up with. There are multiple ways of attacking this.
#fetch_scores.rb
require 'open-uri'
#define a constant named URL so if the results URL changes we don't
#need to replace a hardcoded URL everywhere.
URL = "http://www.nitt.edu/prm/ShowResult.html?&param="
#checking the count of arguments passed to the script.
#it is only taking one, so let's show the user how to use
#the script
if ARGV.length != 1
puts "Usage: fetch_scores.rb student_name"
else
name = ARGV[0] #could drop the ARGV length check and add a default using ||
# or name = ARGV[0] || nikhil
results = open(URL + name).read
end
You might examine Nokogiri or Hpricot to better parse/format your results. Ruby is an "implicit return" language so if you happened to wonder why we didn't have a return statement that's because results will be returned by the script since it was last executed.
You could have a look at the net/http library, included as part of the standard library. See http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html for details, there are some examples on that page to get you started.
A very simple way to do this is to use the open-uri library and just put the query parameters in the URL query string:
require 'open-uri'
name = 'nikhil'
results = open("http://www.nitt.edu/prm/ShowResult.html?&param=#{name}").read
results now contains the body text fetched from the URL.
If you are looking for something more ambitious, look at net/http and the httparty gem.

Resources