def function1
#user=User.find(params[:user_id])
#participants=Participant.find_all_by_user_id(params[:user_id])
bar_1_data = #user.get_total
bar_2_data = params[:count]
color_1 = 'c53711'
color_2 = '0000ff'
min=0
max=100
puts(bar_1_data) # prints 2 on console
puts(bar_2_data) # prints 3 on console
puts (bar_1_data).is_a? Integer # prints true
puts (bar_2_data).is_a? Integer # prints false
bc=GoogleChart::BarChart.new("300x80", " ", :horizontal, false)
bc.data " ", [100], 'ffffff'
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
bc.axis :x, :range => [min,max]
bc.show_legend = true
bc.stacked = false
bc.data_encoding = :extended
#bc= bc.to_url
end
end
I am getting the argument error "comparison of String with 100 failed" int the above controller code. Then I changed the lines
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data, color_2
to
bc.data "Bar1", bar_1_data.to_i, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
which gives me undefined method collect for 2:Fixnum at line #bc= bc.to_url.
On console it gives the following error:
NoMethodError (undefined method `collect' for 2:Fixnum):
gchartrb (0.8) lib/google_chart/base.rb:499:in `extended_encode'
gchartrb (0.8) lib/google_chart/base.rb:461:in `encode_data'
gchartrb (0.8) lib/google_chart/bar_chart.rb:69:in `process_data'
gchartrb (0.8) lib/google_chart/bar_chart.rb:68:in `collect'
gchartrb (0.8) lib/google_chart/bar_chart.rb:68:in `process_data'
gchartrb (0.8) lib/google_chart/base.rb:440:in `add_data'
gchartrb (0.8) lib/google_chart/base.rb:305:in `prepare_params'
gchartrb (0.8) lib/google_chart/base.rb:77:in `to_url'
app/controllers/assess_controller.rb:139:in `function1'
gchartrb (0.8) lib/google_chart/bar_chart.rb:22:in `initialize'
app/controllers/assess_controller.rb:131:in `new'
app/controllers/assess_controller.rb:131:in `function1'
/Library/Ruby/Gems/1.8/gems/hoptoad_notifier-2.4.11/lib/hoptoad_notifier/rack.rb:27:in `call'
/Library/Ruby/Gems/1.8/gems/hoptoad_notifier-2.4.11/lib/hoptoad_notifier/user_informer.rb:12:in `call'
Rendering rescues/layout (internal_server_error)
Tried printing bc in the view as <p><img src="<%= puts (#bc) %>" ></p>,it doesn't print anything, but when I am printing bc in the controller it prints
#<GoogleChart::BarChart:0x103be9660>.
Am I not sending it correctly to the view? I have tried both #bc=bc.to_url and puts bc.to_url as in http://gchartrb.rubyforge.org/.
What am I missing?
Without knowing the api for google charts, I see this:
bc.data " ", [100], 'ffffff'
bc.data "Bar1", bar_1_data, color_1
bc.data "Bar2", bar_2_data.to_i, color_2
The parameters of the first line are of type String, Array, String.
The parameters of the next two are String, Fixnum, String
Your error message is undefined method collect for 2:Fixnum ... so perhaps you should change the Fixnum to Array.
bc.data " ", [100], 'ffffff'
bc.data "Bar1", [bar_1_data], color_1
bc.data "Bar2", [bar_2_data.to_i], color_2
It looks like you're loading bar_1_data and bar_2_data into arrays. Thus the error undefined method to_i for Array.
Instead of:
bar_1_data = [#user.get_total]
bar_2_data = [params[:count]]
Just try
bar_1_data = #user.get_total
bar_2_data = params[:count]
Note that putting your data inside [] brackets means it's now an array of one item.
Related
I am receiving a very strange error. undefined method `delete' for 0:Fixnum when I try to style my rows. Why is this the case?
table(headers + Invoice.all.map do |invoice|
[
make_cell(content: invoice.invoice_number),
make_cell(content: format_date(invoice.invoice_date)),
make_cell(content: format_date(invoice.due_date)),
make_cell(content: format_price(invoice.total)),
make_cell(content: format_price(invoice.fees_total)),
make_cell(content: format_price(invoice.actual_total))
]
end, table_options, style(cell(0), padding: [4,2]))
Having trouble unpacking an array that is generated by rails. The array looks okay and makes sense, but unpacking it doesn't.
Here is the ruby code I have written to test it:
assets = {"0"=>{"id"=>"1", "add_asset"=>"0"},
"1"=>{"id"=>"2", "add_asset"=>"0"},
"2"=>{"id"=>"3", "add_asset"=>"1"}}
puts "assets= " + assets.to_s
puts "size = " + assets.length.to_s
assets.each_with_index do |check, i|
puts "--i = " + i.to_s
this = check[i]
puts "this = " + this.to_s
puts "id = " + this["id"].to_s
puts "add = " + this["add_asset"].to_s
end
And here is the result I am getting:
d:\Users\Michael\Documents>ruby test.rb
assets= {"0"=>{"id"=>"1", "add_asset"=>"0"}, "1"=>{"id"=>"2", "add_asset"=>"0"}, "2"=>{"id"=>"3", "add_asset"=>"1"}}
size = 3
--i = 0
this = 0
id =
add =
--i = 1
this = {"id"=>"2", "add_asset"=>"0"}
id = 2
add = 0
--i = 2
this =
test.rb:14:in `block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
from test.rb:10:in `each'
from test.rb:10:in `each_with_index'
from test.rb:10:in `<main>'
Questions:
Why is it failing to read record "0" then successfully reading record "1"?
Why is it bombing completely on record "2"?
Don't use each_with_index. You're iterating over a hash, not an array. To iterate over the keys and values of a hash, use hash.each |key,value|.
each_with_index converts your hash to an array, in the form [ [key1, value1], [key2, value2], ...]. This will give you something that looks like this:
[
["0", {"id"=>"1", "add_asset"=>"0"}],
["1", {"id"=>"2", "add_asset"=>"0"}],
["2", {"id"=>"3", "add_asset"=>"1"}]
]
So:
Why is it failing to read record "0" then successfully reading record "1"?
It isn't. It's failing all three times, it's just one failure happens to look correct.
The first iteration, i is 0 and check is equal to ["0", {"id"=>"1", "add_asset"=>"0"}], your block accesses check[0] which is "0". You then check "0"["id"] and "0"["add_asset"], which are both nil.
On the next iteration, i is 1 and check is ["1", {"id"=>"2", "add_asset"=>"0"}]. The block accesses check[1] and gets {"id"=>"2", "add_asset"=>"0"} purely by coincidence, and things seem to work.
Why is it bombing completely on record "2"?
On the third iteration, the block gets an i of 2 and check of ["2", {"id"=>"3", "add_asset"=>"1"}]. That array has no [2], so you get nil, and then your block attempts to access nil["add"] which fails.
In Ruby there is a difference between a hash and an array. Hashes can have nearly anything as a key. An array accepts only an integer. Your hashes are built with strings for keys. Decompose like this:
assets = {"0"=>{"id"=>"1", "add_asset"=>"0"},
"1"=>{"id"=>"2", "add_asset"=>"0"},
"2"=>{"id"=>"3", "add_asset"=>"1"}}
assets.each do |key, val|
puts "key = #{key}"
val.each do |inner_key, inner_val|
puts " key=#{inner_key} val=#{inner_val}"
end
end
Output:
key = 0
key=id val=1
key=add_asset val=0
key = 1
key=id val=2
key=add_asset val=0
key = 2
key=id val=3
key=add_asset val=1
I'm working on something to scrape real estate data from a certain website. It works as a standalone .rb file while saving to a JSON file. But I want this to run on Heroku and save the data to MongoDB.
Problem:
I keep getting the following errors when running:
rake aborted!
SyntaxError: /Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:35: syntax error, unexpected tLABEL
street_name: #street_name,
^
/Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:41: syntax error, unexpected tLABEL, expecting '='
bedrooms: #rooms[1],
^
/Users/user/Dropbox/Development/Rails/booyah/lib/tasks/properties_for_sale.rake:42: syntax error, unexpected tLABEL, expecting '='
number_of_floors: #number_of_floors,
^
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `load'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `block in run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `each'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:654:in `run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/application.rb:362:in `run_tasks_blocks'
/Users/user/.rvm/gems/ruby-2.1.1/gems/railties-4.1.1/lib/rails/engine.rb:449:in `load_tasks'
/Users/user/Dropbox/Development/Rails/booyah/Rakefile:6:in `<top (required)>'
/Users/user/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `eval'
/Users/user/.rvm/gems/ruby-2.1.1/bin/ruby_executable_hooks:15:in `<main>'
This is the code I'm using:
require 'mechanize'
namespace :properties_for_sale do
desc "Scrape all properties currently for sale"
task :start => :environment do
a = Mechanize.new
#a2 = Mechanize.new
#i = 1
BASE_URL = 'http://www.funda.nl'
def scrape_objects_on_page(page)
objects_on_page = page.search('//*[contains(concat( " ", #class, " " ), concat( " ", "object-street", " " ))]')
objects_on_page.each do |object|
#a2.get(BASE_URL + object[:href] + 'kenmerken/') do |page_2|
break if page_2.title == '404 - Pagina niet gevonden'
#street_name = page_2.search('//*[#id="main"]/div[1]/div/div/div/h1').text.strip
#price = page_2.search('//*[#id="main"]/div[1]/div/div/div/p[2]/span/span').text.strip.gsub("€ ", "").gsub(".", "").to_i
#url = page_2.uri.to_s
#living_area = page_2.search('//*[#id="twwo13"]/td/span[1]').text.strip.gsub(" m²", "").to_i
#content = page_2.search('//*[#id="twih12"]/td/span[1]').text.strip.gsub(" m³", "").to_i
#rooms = page_2.search('//*[#id="aaka12"]/td/span[1]').text.strip.scan(/\d/).to_i
#number_of_floors = page_2.search('//*[#id="twva12"]/td/span[1]').text.strip.to_i
#year = page_2.search('//*[#id="boja12"]/td/span[1]').text.strip.to_i
#broker = page_2.search('//*[contains(concat( " ", #class, " " ), concat( " ", "rel-info", " " ))]//h3').text.strip
#city = page_2.search('//*[#id="nav-path"]/div/p[1]/span[4]/a/span').text.strip
#district = page_2.search('//*[#id="nav-path"]/div/p[1]/span[5]/a/span').text.strip
#province = page_2.search('//*[#id="nav-path"]/div/p[1]/span[3]/a/span').text.strip
#type_of_property = page_2.search('//*[#id="soap12"]/td/span[1] | //*[#id="sowo12"]/td/span[1] | //*[#id="twsp12"]/td/span[1]').text.strip
Property.create = (
street_name: #street_name,
price: #price,
url: #url,
living_area: #living_area,
content: #content,
rooms: #rooms[0],
bedrooms: #rooms[1],
number_of_floors: #number_of_floors,
year: #year,
broker: #broker,
city: #city,
district: #district,
province: #province,
type_of_property: #type_of_property
)
puts Property.last
end
end
end
loop do
a.get("http://www.funda.nl/koop/rotterdam/sorteer-datum-af/p#{#i}/") do |page|
#end = page.search('//h3').text == 'Geen koopwoningen gevonden die voldoen aan uw zoekopdracht' ? true : false
scrape_objects_on_page(page) unless #end == true
#i = #i + 1
end
break if #end
end
puts "==================================================================================="
puts "# Done scraping #{#i - 1} pages and collected #{#all_objects_array.length} objects."
puts "==================================================================================="
end
end
This is what my Property model looks like (MongoMapper):
class Property
include MongoMapper::Document
key :street_name, String
key :price, Integer
key :url, String
key :living_area, Integer
key :content, Integer
key :rooms, Integer
key :bedrooms, Integer
key :number_of_floors, Integer
key :year, Integer
key :broker, String
key :city, String
key :district, String
key :province, String
key :type_of_property, String
end
What am I doing wrong?
You have a typo. Remove the equal sign between Property.create and the parens. Like below:
Property.create(
street_name: #street_name,
price: #price,
url: #url,
living_area: #living_area,
content: #content,
rooms: #rooms[0],
bedrooms: #rooms[1],
number_of_floors: #number_of_floors,
year: #year,
broker: #broker,
city: #city,
district: #district,
province: #province,
type_of_property: #type_of_property
)
Also, it might be better to store the #create call in a variable instead of calling Property.last. That way, you don't have to issue another query.
I'm getting a Undefined method error:
undefined method `keys' for ["71", "74", "340", "75"]:Array
I'm using Gruff with Prawn to insert an image graph, I have the bar graph displaying properly, but the undefined error is occurring on the label call.
Using prawn (0.15.0) and gruff (0.5.1)
Prawn
def initialize(result)
super()
#result = result
show_graph
end
def show_graph
lint = #result.map {|v| v.lint/227 }
g = Gruff::Bar.new('540x200')
g.data(:lint, lint, '#00463f')
#result.each_with_index do |v, i|
g.labels = {i => v.variety.variety_name}
end
g.y_axis_label = 'Yield (bales/ha)'
g.marker_font_size = 16
g.marker_count = 5
g.theme = {:marker_color => '#333333', :font_color => '#333333', :background_colors => %w(#ffffff #ffffff)}
g.minimum_value = 0
g.hide_legend = true
g.write("#{Rails.root}/app/assets/images/chart.png")
image "#{Rails.root}/app/assets/images/chart.png"
end
Controller
#result = Result.where('trial_id' => params[:trial_id]).order('lint DESC')
#result.map returns an array. A Ruby Hash indeed works like a mathematical "map", but another name for Ruby's general .map method is .collect, because that's all it does. Array in, array out.
I don't know what g.labels needs, but you can get a hash with #result.inject({}){|v, h| h.merge v.variety_id => v.variety }. Change the argument to .merge to fit your needs.
I am trying to run the following code:
dupe_groups = Activity.all.group_by { |e| e.non_id_attributes }.select{ |gr| gr.last.size > 1 }
redundant_elements = dupe_groups.map { |group| group.last - [group.last.first] }.flatten
redundant_elements.each(&:destroy)
However, I get the following error:
Activity.find(:all).group_by { |e| e.non_id_attributes }.select{ |gr| gr.last.size > 1 }
NoMethodError: undefined method `last' for #<Hash:0x00000107e505e8>
from (irb):10:in `block in irb_binding'
from (irb):10:in `select'
from (irb):10
from /usr/local/bin/irb:12:in `<main>'
How can I get this fella to work?
When you do a group_by you get a hash, the thing you group by is represented as the keys in the hash so when you select over it you should be doing .select{|key, values| ...} and you can then values.size > 1
Although, when I look at this code, it has a smell to me. What are you actually trying to do?