This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am trying to read Sonar report in XML format using ruby. I have written the following code:
class Resource
attr_accessor :file_name, :lines, :generated_lines, :ncloc, :generated_ncloc, :statements, :comment_lines, :commented_out_code_lines, :lines_to_cover, :uncovered_lines, :conditions_to_cover, :uncovered_conditions, :line_coverage, :branch_coverage, :coverage, :test_success_density, :test_failures, :skipped_tests, :test_errors, :num_of_tests, :lang, :qualifier
def to_s
"#{#name} #{#lines} #{#generated_lines} #{#ncloc} #{#generated_ncloc} #{#statements} #{#comment_lines} #{#commented_out_code_lines} #{#lines_to_cover} #{#uncovered_lines} #{#conditions_to_cover} #{#uncovered_conditions} #{#line_coverage} #{#branch_coverage} #{#coverage} #{#test_success_density} #{#test_failures} #{#skipped_tests} #{#test_errors}#{#num_of_tests} #{#lang} #{#qualifier}"
end
end
sonar.root.each_element do |node1| # resources
next if node1.name != "resources"
node1.each_element do |node2| #resource
resource = Resource.new
resource.lang = node2.text if node2.name == "lang"
resource.qualifier = node2.text if node2.name == "qualifier"
resource.name = node.text if node2.name == "name"
end
end
As you can see this takes up too many statements whether I use if conditionals or case statements. Is there a more succinct way of doing this in ruby?
Filter the nodes first instead of switching while iterating. And since you’re doing the same thing for each possible value of the name attribute, DRY that up with a loop too.
sonar.root.each_element_with_attribute 'name', 'resources' do |node1|
%w[lang qualifier name].each do |name_val|
node1.each_element_with_attribute 'name', name_val do |node2|
resource = Resource.new
resource.public_send :"#{name_val}=", node2.text
end
end
end
Note: I’m assuming you’re using REXML from your code and your lack of answer to my comment as of this writing. I would, however, suggest you use the friendlier Nokogiri instead.
Related
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm writing a little script with Ruby that takes twitter posts and breaks them up even further. When I send a normal string (non-twitter) against it, it works fine and split strings that are bigger than 32 characters. But for some reason I get an error like this when using the twitter data:
in chunk': private methodscan' called for ["twituser: foo. #yolo"]:Array (NoMethodError)
require 'rubygems'
require 'twitter'
Twitter.configure do |config|
config.consumer_key = ''
config.consumer_secret = ''
config.oauth_token = ''
config.oauth_token_secret = ''
#config.auth_method = :oauth
end
def chunk(string,size)
string.scan(/.{1,#{size}}/)
end
twitterfeed = Twitter.search("#yolo", :count => 1, :result_type => "recent").results.map do |status|
"#{status.from_user}: #{status.text}"
end
twitterfeed.join
puts "#{twitterfeed}\n"
sendchunks = chunk(twitterfeed,32)
sendchunks.each do |string|
puts "\x52\x31\x10\xAC\x4E\x31\x31\x32\x33\x34\x35\x36\x35\x41\x0E" + string + "\x0D\x0A"
puts "#{string}\n"
sleep(10)
end
puts "done\n"
So why the difference? I'm new to ruby so I'm trying to get my head around the difference in how variable types work. A normal string works but even after array to string conversion it horks.
Thanks!
[Edited with the full code of script as the answers are getting off track causing things to burst]
Solution was to do the following:
twitterfeed_string = twitterfeed.join
puts "#{twitterfeed_string}\n"
sendchunks = chunk(twitterfeed_string,32)
The error says private methodscan' called for #Array. This is because you are not storing the result of twitterfeed.join('').to_s anywhere. You are then passing twitterfeed as an array to your chunk method.
You are not overriding twitterfeed.
You probably want to do
twitterfeed_as_string = twitterfeed.join
sendchunks = chunk(twitterfeed_as_string , 32)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to read an XML file and store the structure into an array of objects. Here is my code:
class Bike
attr_accessor :id, :color, :name
def initialize(id, color, name)
#id = id
#color = color
#name = name
end
end
---x---snip---x---
rules.root.each_element do |node1|
case node1.name
when "Bike"
bike = Bike.new(node1.attributes['id'], node1.attributes['color'], { |bike_elem| bike_elem.text.chomp if bike_elem.name == "name"})
bikes.push bike
end
end
However, the last element is not fetching the value alone. It is fetching the whole tag. Is there a better way to do it?
Your code block { |bike_elem| bike_elem.text.chomp if bike_elem.name == "name" }
doesn't seem to make sense inside the new parameter list.
Where does bike_elem come from? This is not valid Ruby in this context.
It's hard to give an answer here without knowing what your XML looks like.
But I would recommend using a XML library like Nokogiri, libxml, and then parse out
the name before you do the new. Try using XPath.
rules.root.each_element do |node1|
case node1.name
when "Bike"
name = node1.attributes[....]
bike = Bike.new(node1.attributes['id'], node1.attributes['color'],name )
bikes.push bike
end
end
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have an array that looks like
["", "Fitness", "Stationary", "Looks", "Access", "Food",
"---\n- Stationary\n- Access\n- ''\n"] ["", "Fitness",
"Stationary", "Looks", "Access", "Food", "---\n- Stationary\n- Access\n- ''\n"]
I use the following code to go through them...
<h3>Categories</h3>
<% for product in Product.select(:category)%>
<% a = [""].concat(Product.select(:category).map(&:category).uniq) %>
<% end %>
<% a.each do |c| %>
<p class="text-error"><%= link_to(c.delete("-"), ) %></p>
<% end %>
I get something like this...
Fitness
Stationary
Looks
Access
Food
Stationary Access ''
The full code is available at:
https://github.com/abhishekdagarit/sample-app.git
How to solve this?
If there is dirty data in the database, How can I clean that?
What is the problem here? And How to fix it?
It looks like you have YAML in your array:
jruby-1.7.0.preview2 :001 > require 'yaml'
=> true
jruby-1.7.0.preview2 :002 > a = ["", "Fitness", "Stationary", "Looks", "Access", "Food", "---\n- Stationary\n- Access\n- ''\n"]
=> ["", "Fitness", "Stationary", "Looks", "Access", "Food", "---\n- Stationary\n- Access\n- ''\n"]
jruby-1.7.0.preview2 :003 > YAML.load(a.last)
=> ["Stationary", "Access", ""]
which means you have probably have junk in your category column of the products table. How it got there, not sure; maybe some strange stuff happened when seeding data from a yml file?
The best way to avoid this kind of situations is to make a reference table named for example categories and reference this table with a category_id foreign key in the products table. That way, when creating a product, you can display a dropdown with only the valid categories in it – and prevent invalid categories from being added to the db.
I'm learning about Qt Model/View with Ruby and I'm trying run the following code
require 'Qt4'
class MyModel < Qt::AbstractListModel
def initialize(data = [])
super()
#data = data
end
def rowCount idx
#data.size
end
def data idx, role = Qt::DisplayRole
if role == Qt::DisplayRole then
Qt::Variant.new #data
else Qt::Variant.new
end
end
end
if $0 == __FILE__
app = Qt::Application.new ARGV
v = Qt::ListView.new
m = MyModel.new(['1', '2', '3'])
v.model = m
v.show
app.exec
end
When I run the script what it shows is a list window with three rows empty. What am I doing wrong?
On the other hands, I find it hard to learn to model/view programming with ruby due to the poor documentation (All is C++) anyone know if there are tutorials or something?
Are you familiar with Qt, Ruby and/or C++ already? If so that'll help hugely on your journey as there isn't unfortunately that much documentation for Qt with Ruby available.
Anyway, the problem is that you're returning an Array instead of the element for the wanted index, see QAbstractItemModel::data. The idx argument in there is a QModelIndex, so just look up the wanted row and return it like this:
Qt::Variant.new #data[idx.row]
Also, checkout http://techbase.kde.org/Development/Languages/Ruby for information regarding to Ruby & Qt in general.
n the .net world, my specs would follow the Arrange, Act, Assert pattern. I'm having trouble replicating that in rspec, because there doesn't appear to be an ability to selectively verify your mocks after the SUT has taken it's action. That, coupled with the fact that EVERY expectation is evaluated at the end of each 'It' block, is causing me to repeat myself in a lot of my specs.
Here's an example of what I'm talking about:
describe 'AmazonImporter' do
before(:each) do
Kernel.**stubs**(:sleep).with(1)
end
# iterates through the amazon categories, and for each one, loads ideas with
# the right response group, upserting ideas as it goes
# then goes through, and fleshes out all of the ideas that only have asins.
describe "find_new_ideas" do
before(:all) do
#xml = File.open(File.expand_path('../amazon_ideas_in_category.xml', __FILE__), 'r') {|f| f.read }
end
before(:each) do
#category = AmazonCategory.new(:name => "name", :amazon_id => 1036682)
#response = Amazon::Ecs::Response.new(#xml)
#response_group = "MostGifted"
#asin = 'B002EL2WQI'
#request_hash = {:operation => "BrowseNodeLookup", :browse_node_id => #category.amazon_id,
:response_group => #response_group}
Amazon::Ecs.**expects**(:send_request).with(has_entries(#request_hash)).returns(#response)
GiftIdea.expects(:first).with(has_entries({:site_key => #asin})).returns(nil)
GiftIdea.any_instance.expects(:save)
end
it "sleeps for 1 second after each amazon request" do
Kernel.**expects**(:sleep).with(1)
AmazonImporter.new.find_new_ideas(#category, #response_group)
end
it "loads the ideas for the given response group from amazon" do
Amazon::Ecs.**expects**(:send_request).
with(has_entries(#request_hash)).
returns(#response)
**AmazonImporter.new.find_new_ideas(#category, #response_group)**
end
it "tries to load those ideas from repository" do
GiftIdea.expects(:first).with(has_entries({:site_key => #asin}))
**AmazonImporter.new.find_new_ideas(#category, #response_group)**
end
In this partial example, I'm testing the find_new_ideas method. But I have to call it for each spec (the full spec has 9 assertion blocks). I further have to duplicate the mock setup so that it's stubbed in the before block, but individually expected in the it/assertion block. I'm duplicating or nearly duplicating a ton of code here. I think it's even worse than the highlighting indicates, because a lot of those globals are only defined separately so that they can be consumed by an 'expects' test later on. Is there a better way I'm not seeing yet?
(SUT = System Under Test. Not sure if that's what everyone calls it, or just alt.net folks)
You can use shared example groups to reduce duplication:
shared_examples_for "any pizza" do
it "tastes really good" do
#pizza.should taste_really_good
end
it "is available by the slice" do
#pizza.should be_available_by_the_slice
end
end
describe "New York style thin crust pizza" do
before(:each) do
#pizza = Pizza.new(:region => 'New York' , :style => 'thin crust' )
end
it_behaves_like "any pizza"
it "has a really great sauce" do
#pizza.should have_a_really_great_sauce
end
end
Another technique is to use macros, which is handy if you need similar specs in different classes.
Note: the example above is borrowed from The RSpec Book, Chapter 12.
you can separate them using "context" if that helps...
https://github.com/dchelimsky/rspec/wiki/faq