I have the following code
'Performance' => {
'Date' => performance_values.date.strftime('%m/%d/%Y'),
'Ratio' => begin sprintf("%0.02f", performance_values.ratio) rescue nil end},
'Ratings' => {
'Overall' => performance_values.overall_rating,
'3-yr' => performance_values.3yr_rating}
With 'Ratio' it can sometimes be nil, so I'm trying to begin/rescue out of the sprintf function and just let it be nil.
When this runs and performance_values.ratio is nil, i get the following error message:
TypeError: can't convert nil into Float
Being inline, you don't need to specify begin & end. Rails knows that you are rescuing the whole line.
Try this:
'Performance' => {
'Date' => performance_values.date.strftime('%m/%d/%Y'),
'Ratio' => (sprintf("%0.02f", performance_values.ratio) rescue nil)},
'Ratings' => {
'Overall' => performance_values.overall_rating,
'3-yr' => performance_values.3yr_rating}
Related
While I'm parsing alliance feed in a Sinatra/Ruby app I get the error:
/opt/rh/ruby200/root/usr/share/ruby/net/http/response.rb:368: [BUG]
Segmentation fault ruby 2.0.0p645 (2015-04-13) [x86_64-linux]
I'm wondering if this is a bug with Ruby or something wrong with the code, and if so, what could I do to fix it?
Link to the error
This is the code for the parsing alliance feed:
feeds.each { |name, hash|
puts "=== PARSING #{name.upcase} FEED ==="
start = Time.now
open(hash[:url]) { |feed|
send(hash[:action], feed)
}
duration = Time.now - start
puts "Feed syndication completed in #{duration.to_s} seconds."
puts
}
# Close DB connection
puts "Disconnecting"
#db.disconnect
end
def parseAllianceData(xml)
start = Time.now
allianceData = XMLObject.new xml
duration = Time.now - start
puts "XML parsed in #{duration.to_s} seconds."
puts "Alliances found: #{allianceData.alliances.count}"
#db[:feeds].insert(
:generated_at => allianceData.server.datagenerationdatetime,
:type => "Alliance",
:is_current => true)
start = Time.now
allianceData.alliances.each { |alliance|
capital_last_moved_at = (alliance.alliancecapitallastmoved rescue nil)
taxrate_last_changed_at = (alliance.alliancetaxratelastchanged rescue nil)
#db[:alliance].insert(
:id => alliance.alliance[:id],
:ticker => alliance.allianceticker,
:name => alliance.alliance,
:founded_at => alliance.foundeddatetime,
:founded_by_player_id => alliance.foundedbyplayerid[:id],
:capital_town_id => alliance.alliancecapitaltownid[:id],
:member_count => alliance.membercount,
:total_population => (alliance.totalpopulation rescue 0),
:tax_rate => (alliance.alliancetaxrate.to_i) / 100.0,
:tax_rate_last_changed_at => taxrate_last_changed_at,
:capital_town_last_moved_at => capital_last_moved_at)
alliance.roles.each { |role|
#db[:alliance_roles].insert(
:id => role.role[:id],
:name => role.role,
:alliance_id => alliance.alliance[:id],
:hierarchy_id => role.heirarchy[:id])
}
}
duration = Time.now - start
puts "Database populated in #{duration.to_s} seconds."
I spot one dangerous line of code in your sample:
send(hash[:action], feed)
It takes some string from external source (hash[:action]) and turns it into a method call. It is very dangerous, because you never know what string you will get. There could be a string there that cannot be made into a method call so Ruby crashes.
I would suggest checking for all supported actions and calling methods explicitly. You can do it with a case statement, for example.
action = hash[:action]
case action
when 'action1'
call_method1
when 'action2'
call_method2
else
puts "unsupported action: #{action}"
end
I am new to WSDL.
Code (I have added in the view directly - for test): (Page: http://localhost:3000/ccapis )
require 'savon'
client = Savon::Client.new(wsdl: "http://localhost:3000/ccapis/wsdl")
result = client.call(:fetch_prizes, message: { :gl_id => "123456789" })
result.to_hash
And in the controller:
soap_action "fetch_prizes",
:args => { :gl_id => :string },
:return => [:array]
def fetch_prizes
glnumber = params[:gl_id ]
prize = Prize.where(:gl_id => glnumber)
prize_to_show = []
a_hash = {}
prize.each do |p|
a_hash = { :prize => p.prize.to_s, :score => p.score.to_s, :date => p.round_date.to_s }
prize_to_show.push a_hash
a_hash = nil
end
render :soap => prize_to_show
end
When I try and run this in the Console all are good and I can see the result.to_hash but when I go to http://0.0.0.0:3000/ccapis I get the error that I mentioned above.
Explanation of what I am trying to achieve:
I need to supply a WSDL for a client which fetches all the prizes based on a score.
If My approach is wrong please direct me to a document so I can have a read and get a better understanding. Thanks again.
I am using rails 2.3. In my application it uses
val = Party.find(:all, :conditions => [" type in ('Physician') || id in (?)",PartyLabel.find(:all,:conditions=>"label_id=#{Label.find_by_label("Can Schedule").id}").collect{|p| p.party_id if Party.find(p.party_id).respond_to?("provider_organizations")}], :with_disabled => true).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
code to achieve some requirements. Now i wants to split the code in to 2 parts.
1. phys = Physician.find(:all, :include => :provider_organizations, :with_disabled => true).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
it's working fine.. and the second part will be
2. sch = Party.find(:all, :include => [:as_labels], :conditions => {:label => {:label => "Can Schedule"}}.respond_to?("provider_organizations")).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
it shows NoMethodError (undefined method 'provider_organizations' for #<ProviderOrganization:0x1ab81c20>): error message... Any comments could be appreciated..
It looks like respond_to?("provider_organizations") is called for a wrong object. Here is your code #2:
sch = Party.find(
:all,
:include => [:as_labels],
:conditions => {
:label => {
:label => "Can Schedule"
}
}.respond_to?("provider_organizations") # What's this ???
).select{ |physician|
not physician.provider_organizations.blank?
}.collect{ |enum|
[enum.display_name_schedule, enum.id]
}
If I understand it correctly, the respond_to? should be inside the select:
...
).select{ |physician|
physician.respond_to?("provider_organizations") && not physician.provider_organizations.blank?
}.collect{ ...
I have totally nine buttons in rails. I have input the data into the database by manually typing the #button_1.save function.
My question is:
How can i have the #button_i.save function in rails? I have finished the things in the for loop, what is left is the button save functions.
Many thanks!
button_number = params[:button_number]
for i in (1..button_number)
instance_variable_set("#button#{i}",
Button.new(:title => params["button_title_#{i}".to_sym],
:order => i,
:icon_url => params["button_icon_#{i}".to_sym],
:navigation_id => #navigation.id,
:next_navigation => params["selected_navigation_#{i}".to_sym].to_i,
:next_page => params["selected_page_#{i}".to_sym].to_i))
instance_variable_set("#button#{i}")
end
#button1.save
#button2.save
#button3.save
#button4.save
#button5.save
#button6.save
for i in ...
eval("#button#{i}.save")
end
The opposite of instance_variable_set is instance_variable_get, which I think will lead you to the correct answer:
1.upto(params[:button_number].to_i) do |i|
instance_variable_set("#button#{i}",
Button.new(
:title => params["button_title_#{i}".to_sym],
:order => i,
:icon_url => params["button_icon_#{i}".to_sym],
:navigation_id => #navigation.id,
:next_navigation => params["selected_navigation_#{i}".to_sym].to_i,
:next_page => params["selected_page_#{i}".to_sym].to_i
)
)
instance_variable_get("#button#{i}").save
end
Try by using constantize ruby function because I think your function call statement is in string.
button_number = params[:button_number]
for i in (1..button_number)
instance_variable_set("#button#{i}",
Button.new(:title => params["button_title_#{i}".to_sym],
:order => i,
:icon_url => params["button_icon_#{i}".to_sym],
:navigation_id => #navigation.id,
:next_navigation => params["selected_navigation_#{i}".to_sym].to_i,
:next_page => params["selected_page_#{i}".to_sym].to_i))
"#button#{i}".constantize.save();
end
May be this that you want -
button_number = params[:button_number].to_i
for i in (1..button_number)
instance_variable_set("#button#{i}",
Button.new(:title => params["button_title_#{i}".to_sym],
:order => i,
:icon_url => params["button_icon_#{i}".to_sym],
:navigation_id => #navigation.id,
:next_navigation => params["selected_navigation_#{i}".to_sym].to_i,
:next_page => params["selected_page_#{i}".to_sym].to_i))
instance_variable_set("#button#{i}")
"#button#{i}".save
end
I want to use 'tinymce_spellcheck' to use the spellcheck button in my tinymce editor.
I wrote in my controller:
def spellcheck
data = ActiveSupport::JSON.decode(request.raw_post)
args = data['params'].to_a.first
spellcheck = TinymceSpellcheck.new({}, :raspell)
result = spellcheck.send(data['method'].underscore,*args) #****---- THIS LINE****
render :json => { :id => data['id'], :result => result, :error => nil }.to_json
end
I get the following error message:
ArgumentError (wrong number of arguments (1 for 2)):
app/controllers/members_controller.rb:127:in `spellcheck'
Would you be so kind to tell me how to solve this problem? I am providing two arguments and, yet, I get the same error message again and again.
Well, the problem is probably that args is empty or nil, so when you call the splat on it, it turns into zero arguments. Thus, your only argument is the 'method', and you get an ArgumentError.
def spellcheck
`data = ActiveSupport::JSON.decode(request.raw_post)
args = data['params'].to_a.first
spellcheck = TinymceSpellcheck.new({}, :raspell)
result = spellcheck.send(data['method'].underscore,*args)
render :json => { :id => data['id'], :result => result, :error => nil }.to_json
end`
The line `args = data['params'].to_a.first` was changed to`args = data['params'].to_a`