Sinatra:为什么这是语法错误?

时间:2015-07-19 23:02:35

标签: ruby mongodb sinatra

我正在使用Ruby,Sinatra和MongoDB创建一个CRUD API。我一直收到以下错误消息,我无法弄清楚我做错了什么:

  

SyntaxError:/yasi.rb:6:语法错误,意外=>,期待'}'Yasi.connect {:server => “localhost”,:db => “yasi”} ^ /yasi.rb:6:语法错误,意外',',期待'}'Yasi.connect {:server => “localhost”,:db => “yasi”} ^

以下是我的代码:

require 'rubygems'
require 'sinatra'
require 'lib/yasi'

before do
  Yasi.connect {:server => "localhost", :db => "yasi"}
end

get "/" do
  @yasis = Yasi.find :all
  erb :index
end

get "/new" do
  erb :new
end

get "/delete/:id" do
  Yasi.delete(params[:id])
  redirect "/"
end

post "/" do
  params.reject! {|k,v| k == "submit"}
  Yasi.save(params)
  redirect "/"
end

这是lib / yasi文件:

require 'rubygems'
require 'mongo'
require 'sinatra'

module Yasi
  class << self

def connect(config)
    @db = Mongo::Connection.new(config[:server],config[:port] || 27017).db(config[:db])
end 

def find(search)
  if search == :all
    #return all
    yasi = @db.collection("yasis").find.to_a
    return nil_or_array(yasi)
  else 
    return find_with_criteria(search)
  end
end  

def save(yasi)
    stringify_keys(yasi)
    #handle author first
    if yasi["author"]
        stringify_keys(yasi["author"])
    author = @db.collection("authors").find_one(yasi["author"])
    unless author 
        author = @db.collection("authors").save(yasi["author"])
    end
    yasi["author"] = author 
  end

  @db.collection("yasis").save(yasi)    
end  

def delete(id)
  victim = @db.collection("yasis").find_one(Mongo::ObjectID.from_stringid))
  @db.collection("yasis").remove(victim) if victim
end     


private

def find_with_criteria(search)
  stringify_keys(search)
  if search["author"]
    author = @db.collection("authors").find_one stringify_keys(search["author"])
    if author
        search[:author] = author
        yasi = @db.collection("yasis").find(search).to_a
        return nil_or_array yasi
    else 
        nil
    end
  else 
    yasi = @db.collection("yasis").find(search).to_a
    return nil_or_array(yasi)
  end       
end 

def stringify_keys(hash)
  hash.each_key do |key|
    hash[key.to_s] = hash.delete(key)
  end
  hash  
end 

def nil_or_array(result)
  if result.size == 0
    return nil
  else 
    return result
  end   
  end   

end     
end 

1 个答案:

答案 0 :(得分:1)

夫妻俩。确保您以正确的路径访问yasi。另外,将引用哈希的变量作为config传递给Yasi.connect,如下所示:

require './lib/yasi'

before do
  config = { :server => "localhost", :db => "yasi" }
  Yasi.connect config
end

这应该可以处理您发布的错误,但我还会仔细检查您在yasi文件中的缩进,以便更轻松地进行故障排除。