开发者

Some Ruby code runs well in script/console but not with script/runner, why?

I am actually using Rails 3.0, so it is rails console vs rails runner try.rb. The following code runs well in the console but not as a script with runner. I need runner (instead of using ruby try.rb) because there are some ActiveRecord code for the project.

Update: I couldn't run it inside of myproj\lib\tasks\ (when the current directory is myproj\lib\tasks\), but can run it inside of myproj, so the question becomes, why must it be run at myproj?

http_header = {'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.53 Safari/534.3'}

url = URI.parse('http://www.google.com/')

response = Net::HTTP.start(url.host, url.port) do |http|
  http.get(url.path, http_header)
end

puts response.body

The error code is:

c:\ror\proj\lib\tasks>rails runner try.rb
c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `eval': no method name given (ArgumentError)
        from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `eval'
        from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/runner.rb:50:in `<top (required)>'
        from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:39:in `require'
        from c:/ruby192/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:39:in `<top (required)>'
        from script/rails:6:in `require'
        from script/rai开发者_如何学Gols:6:in `<main>'


Where are you running the command from?

You need to run the command from your rails root directory and give a full or relative path to the filename so rails runner lib/try.rb

The reason for this is that the command runner accepts either the name of a file containing ruby code or a string containing ruby code. When the command runner can not find the file named in argv(0) it tries to eval argv(0), so it is trying to eval the string try.rb

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜