分段错误ruby 2.0.0p645

时间:2016-01-03 09:19:34

标签: ruby-on-rails ruby sinatra

当我在Sinatra / ruby​​应用程序中分享ALLIANCE FEED时,我得到了

  

/opt/rh/ruby200/root/usr/share/ruby/net/http/response.rb:368:[BUG]   分段故障ruby 2.0.0p645(2015-04-13)[x86_64-linux]

错误。所以我想知道这是否是ruby的错误或代码有什么问题,我可以采取哪些步骤来修复它。

Link to the error

以下是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."

1 个答案:

答案 0 :(得分:0)

在您的示例中发现了一行危险的代码:

send(hash[:action], feed)

它从外部源(hash[:action])获取一些字符串,并将其转换为方法调用。这非常危险,因为您永远不知道会得到什么字符串。那里可能有一个不能被调用为方法的字符串,所以Ruby崩溃了。

我建议检查所有受支持的操作并显式调用方法。例如,您可以使用case语句来完成此操作。

action = hash[:action]

case action
when 'action1'
  call_method1
when 'action2'
  call_method2
else
  puts "unsupported action: #{action}"
end