With Ruby 1.8, FeedTools is able to get and parse rss/atom feed links given a non-feed link. For eg:
ruby-1.8.7-p174 > f = FeedTools::Feed.open("http://techcrunch.com/")
=> #<FeedTools::Feed:0xc99cf8 URL:http://feeds.feedburner.com/TechCrunch>
ruby-1.8.7-p174 > f.title
=> "TechCrunch"
Whereas, with JRuby 1.5.2, FeedTools is unable to get and parse rss/atom feed links given a non-feed link. For eg:
jruby-1.5.2 > f = FeedTools::Feed.open("http://techcrunch.com/")
=> #<FeedTools::Feed:0x1206 URL:http://techcrunch.com/>
jruby-1.5.2 > f.title
=> nil
At times, it also gives the following error:
FeedTools::FeedAccessError: [URL] does
not appear to be a feed.
Any ideas on how I can get FeedTools to work with JRuby?
There seems to be a bug in the feedtools gem. In the method to locate feed links with a given mime type, replace 'lambda' with 'Proc.new' to return from the method from inside the proc when the feed link is found.
--- a/feedtools-0.2.29/lib/feed_tools/helpers/html_helper.rb
+++ b/feedtools-0.2.29/lib/feed_tools/helpers/html_helper.rb
## -620,7 +620,7 ##
end
end
get_link_nodes.call(document.root)
- process_link_nodes = lambda do |links|
+ process_link_nodes = Proc.new do |links|
for link in links
next unless link.kind_of?(REXML::Element)
if link.attributes['type'].to_s.strip.downcase ==
Related
Trying to display second level information about characters from this Futurama API.
Currently using this code to get information:
def self.character
uri = URI.parse(URL)
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data.each do |c|
Character.new(c["name"], c["gender"], c["species"], c["homePlanet"], c["occupation"], c["info"], c["sayings"])
end
end
I'm then stuck either returning (gender and species) from the nested hash (if character id > 8) or the original hash (character id < 8) when using this code:
def character_details(character)
puts "Name: #{character.name["first"]} #{character.name["middle"]} #{character.name["last"]}"
puts "Species: #{character.info["species"]}"
puts "Occupation: #{character.homePlanet}"
puts "Gender: #{character.info["gender"]}"
puts "Quotes:"
character.sayings.each_with_index do |s, i|
iplusone = i + 1
puts "#{iplusone}. #{s} "
end
end
Not sure where or what logic to use to get the correct information to display.
Maybe you have a problem when save c['info] in Character.new(c["name"], c["gender"], c["species"], c["homePlanet"], c["occupation"], c["info"], c["sayings"])
I'm running your code and I see info does not exist in the response of API, the gender should be accessed in character.gender
irb(main):037:0> character.gender
=> "Male"
irb(main):039:0> character.species
=> "Human"
I don't understand this comment: (if character id > 8) or the original hash (character id < 8) Can you explain us what u need do?
I am trying to save data from a Hash to a file. I convert it to JSON and dump it into the file.
When I try to parse back from file to hash I get JSON::ParserError
Code to convert Hash to JSON file: (works fine)
user = {:email => "cumber#cc.cc", :passwrd => "hardPASSw0r|)"}
student_file = File.open("students.txt", "a+") do |f|
f.write JSON.dump(user)
end
After adding a few values one by one to the file it looks something like this:
{"email":"test1#gmail.com","passwrd":"qwert123"}{"email":"test3#gmail.com","passwrd":"qwert12345"}{"email":"cumber#cc.cc","passwrd":"hardPASSw0r|)"}
I tried the following code to convert back to Hash but it doesn't work:
file = File.read('students.txt')
data_hash = JSON.parse(file)
I get
System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/json/common.rb:155:in `parse': 757: unexpected token at '{"email":"test3#gmail.com","passwrd":"qwert12345"}{"email":"cumber#cc.cc","passwrd":"hardPASSw0r|)"}' (JSON::ParserError)
from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/json/common.rb:155:in `parse'
from hash_json.rb:25:in `<main>'
My goal is to be able to add and remove values from the file.
How do I fix this, where was my mistake? Thank you.
This should work:
https://repl.it/EXGl/0
# as adviced by #EricDuminil, on some envs you need to include 'json' too
require 'json'
user = {:email => "cumber#cc.cc", :passwrd => "hardPASSw0r|)"}
student_file = File.open("students.txt", "w") do |f|
f.write(user.to_json)
end
file = File.read('students.txt')
puts "saved content is: #{JSON.parse(file)}"
p.s. hope that this is only an example, never store passwords in plain-text! NEVER ;-)
So here is what i'm trying to do. I'm building a simply Ruby file that will as the user for input, a city, and then return weather results for that city. I've never written in Ruby nor have I ever used API's. But here is my attempt.
The API response below:
> {"coord"=>{"lon"=>-85.68, "lat"=>40.11}, "weather"=>[{"id"=>501,
> "main"=>"Rain", "description"=>"moderate rain", "icon"=>"10d"}],
> "base"=>"stations", "main"=>{"temp"=>57.78, "pressure"=>1009,
> "humidity"=>100, "temp_min"=>57, "temp_max"=>60.01},
> "wind"=>{"speed"=>5.17, "deg"=>116.005}, "rain"=>{"1h"=>1.02},
> "clouds"=>{"all"=>92}, "dt"=>1475075671, "sys"=>{"type"=>3,
> "id"=>187822, "message"=>0.1645, "country"=>"US",
> "sunrise"=>1475062634, "sunset"=>1475105280}, "id"=>4917592,
> "name"=>"Anderson", "cod"=>200} [Finished in 2.0s]
The Ruby file below:
require 'net/http'
require 'json'
url = 'http://api.openweathermap.org/data/2.5/weather?q=anderson&APPID=5c89010425b4d730b7558f57234ea3c8&units=imperial'
uri = URI(url)
response = Net::HTTP.get(uri)
parsed = JSON.parse(response)
puts parsed #Print this so I can see results
inputs temp = JSON.parse(response)['main']['temp']
puts desc = JSON.parse(response)['weather']['description']
puts humid = JSON.parse(response)['main']['humidity']
puts wind = JSON.parse(response)['wind']['speed']
What I was trying to do was only pull out a few items like temperature,description, humidity, and wind. But I can't seem to get it right. I keep getting undefined errors with each attempt.
(Wanting to complete this without using gems or anything that isn't already built into Ruby) (I have not written the parts for user input yet)
Your problem is that response['weather'] is an array, so you won't be able to access ['weather']['description'], instead you will have to do something like ['weather'][0]['description'].
2.3.0 :020 > puts parsed['weather'][0]['description']
moderate rain
2.3.0 :021 > puts parsed['main']['humidity']
100
2.3.0 :022 > puts parsed['wind']['speed']
5.17
2.3.0 :025 > puts parsed['main']['temp']
58.8
ok I am trying to create a definition which will read a list of IDS from an external Json file, Which it is doing. Its even putting the data into the database on load of the program, my issue is this. I cant seem to match the list IDs to a comparison. Here is my current code:
def check(account):
global ID_account
import json, httplib
if not hasattr(BigWorld, 'iddata'):
UID_DB = account['databaseID']
UID = ID_account
try:
conn = httplib.HTTPConnection('URL')
conn.request('GET', '/ids.json')
conn.sock.settimeout(2)
resp = conn.getresponse()
qresp = resp.read()
BigWorld.iddata = json.loads(qresp)
LOG_NOTE('[ABRO] Request of URL data successful.')
conn.close()
except:
LOG_NOTE('[ABRO] Http request to URL problem. Loading local data.')
if UID_DB is not None:
list = BigWorld.iddata["ids"]
#print (len(list) - 1)
for n in range(0, (len(list) - 1)):
#print UID_DB
#print list[n]
if UID_DB == list[n]:
#print '[ABRO] userid located:'
#print UID_DB
UID = UID_DB
else:
LOG_NOTE('[ABRO] userid not set.')
if 'databaseID' in account and account['databaseID'] != UID:
print '[ABRO] Account not active in database, game closing...... '
BigWorld.quit()
now my json file looks like this:
{
"ids":[
"1001583757",
"500687699",
"000000000"
]
}
now when I run this with all the commented out prints it seems to execute perfectly fine up till it tries to do the match inside the for loop. Even when the print shows UID_DB and list[n] being the same values, it does not set my variable, it doesn't post any errors, its just simply acting as if there was no match. am I possibly missing a loop break? here is the python log starting with the print of the length of the table print:
INFO: 2
INFO: 1001583757
INFO: 1001583757
INFO: 1001583757
INFO: 500687699
INFO: [ABRO] Account not active, game closing......
as you can see from the log, its never printing the User located print, so it is not matching them. its just continuing with the loop and using the default ID I defined above the definition. Anyone with an idea would definitely help me out as ive been poking and prodding this thing for 3 days now.
the answer to this was found by #VikasNehaOjha it was missing simply a conversion to match types before the match comparison I did this by adding in
list[n] = int(list[n])
that resolved my issue and it finally matched comparisons.
I am using h helper method in Rails to encode/escape a string that has an apostrophe (') In my view I am using it like this
<%=h "Mike's computer" %>
My understanding is that the html when viewing the source should be Mike%27s computer but the html produced has an apostrophe in it, Mike's computer
Am I missing something obvious?
How do I get my desired result of Mike%27s computer?
Help is always appreciated.
An apostrophe is a valid character in HTML. It is not encoded because it is not needed to be encoded.
If you want to encode a URL, use u helper:
>> fer#:~/$ script/console
Loading development environment (Rails 2.3.8)
>> include ERB::Util
=> Object
>> h "Mike's computer"
=> "Mike's computer"
>> u "Mike's computer"
=> "Mike%27s%20computer"
>>
If we look at the source code of the h method (it is an alias for html_escape), it is not that hard to just open the file and add the single quote (') to the HTML_ESCAPE constant in the file.
Below is the source code of the method with the location of the method in the file. Find the constant and and the quote in. You can even add more things inside as you want it.
HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"' }
File actionpack/lib/action_view/template_handlers/erb.rb, line 17
17: def html_escape(s)
18: s.to_s.gsub(/[&"><]/) { |special| HTML_ESCAPE[special] }
19: end
CAVEAT: This modification will affect all projects that uses the library.
OR an alternative will be to create a view helper method say in ApplicationHelper
def h_with_quote(s)
HTML_ESCAPE = { "'" => "%27"}
h(s).gsub(/[']/) {|special| HTML_ESCAPE[special]}
end
That approach should be safer.