红宝石语法错误'require_relative'

时间:2018-08-08 05:58:57

标签: ruby

因此,当我运行ruby server.rb时,出现此错误:

  

server.rb:3:在`require_relative'中:/Users//Desktop/ruby/route.rb:9:语法错误,意外的')',期望keyword_then或';'或'\ n'(SyntaxError)   nv [“ REQUEST_METHOD”] ==“ GET”)

     

/Users//Desktop/ruby/route.rb:17:语法错误,意外的keyword_end,期望输入结束       来自server.rb:3:in''

不确定确切要问什么。也许你们中有些对红宝石有丰富经验的人,或者编程可能会有所启发。

server.rb

require 'rack'
require_relative 'view'
require_relative 'route'

class App

  PAGES = %w{ /home /admin}

  def call(env)
    response_headers = {}

    ### cookies
    request_cookies = Rack::Utils.parse_cookies(env)

    # set the session identifier if one doesn't already exist
    unless request_cookies["session_key"]
      Rack::Utils.set_cookie_header!(response_headers, "session_key", Time.now.to_f)
    end

    # count the number of page visits:
    # nil.to_i returns 0, so if this cookie isn't set, the count will be 0:

    count = request_cookies["session_count"].to_i
    count += 1

    Rack::Utils.set_cookie_header!(response_headers, "session_count", count)

    ### routing
    route_name = Route.new(env).name

    # get the template
    pages = Pages.new(route_name, visit_count: count)

    ### return the response object
    [status, response_headers, [pages.render]]
  end
end

Rack::Handler::WEBrick.run App.new

view.rb

class View
  def initialize(page, data = {})
    @data = data
    @page = page
    file = File.join(File.dirname(__FILE__), "./pages/#{page}.html.erb")
    @page = File.read(file)
  end

  def visit_count
    @data[:visit_count]
  end

  def render
    ERB.new(@page).result(binding)
  end
end

route.rb

class Route

  ROUTES = {
    "/home" => :home,
    "/admin" => :admin
  }

  def initialize(env)
    if env["REQUEST_METHOD"] == "GET")
      @name = ROUTES[env["PATH_INFO"]]
    end
  end

  def name
    @name || "404"
  end
end

我已经在此问题上停留了一段时间,但仍然找不到解决方案。我会很感激的。

1 个答案:

答案 0 :(得分:3)

  

server.rb:3:在'require_relative'中:/Users//Desktop/ruby/route.rb:9:语法错误,意外的')'

该错误表明,route.rb文件的第9行存在语法错误。让我们检查一下:

if env["REQUEST_METHOD"] == "GET")

这不是有效的语法,因为我们只有一个括号,但有效的括号是:

if(env["REQUEST_METHOD"] == "GET")

if env["REQUEST_METHOD"] == "GET"

因此解决方案是删除行尾的括号,或在env["REQUEST_METHOD"] == "GET")之前添加一个括号