2014-11-03 100 views
0

我在Ruby/Sinatra中构建了一个应用程序,我想使用Roar for JSON(和Hal)输出。目前我遇到了Roar的问题。NameError:未初始化的常量在Sinatra中的Roar :: JSON

这些宝石安装:

Using i18n 0.6.11 
Using json 1.8.1 
Using minitest 5.4.2 
Using thread_safe 0.3.4 
Using tzinfo 1.2.2 
Using activesupport 4.1.7 
Using builder 3.2.2 
Using activemodel 4.1.7 
Using arel 5.0.1.20140414130214 
Using activerecord 4.1.7 
Using backports 3.6.3 
Using bond 0.5.1 
Using mini_portile 0.6.0 
Using multi_json 1.10.1 
Using nokogiri 1.6.3.1 
Using rack 1.5.2 
Using rack-protection 1.5.3 
Using rack-test 0.6.2 
Using uber 0.0.10 
Using representable 1.8.5 
Using ripl 0.7.1 
Using ripl-multi_line 0.3.1 
Using ripl-rack 0.2.1 
Using roar 0.12.9 
Using tilt 1.4.1 
Using sinatra 1.4.5 
Using sinatra-contrib 1.4.2 
Using roar-sinatra 0.0.1 
Using shotgun 0.9 
Using sinatra-activerecord 2.0.3 
Using sqlite3 1.3.10 
Using tux 0.3.0 
Using bundler 1.7.4 

,这是我app.rb

require "sinatra" 
require "sinatra/activerecord" 
require "roar-sinatra" 
require 'roar/representer/json' 
require 'roar/representer/json/hal' 

set :database, "sqlite3:todolist.db" 

module TodoRepresenter 
    include Roar::JSON 

    property :title 
end 

但是,当我开始我的应用程序,我得到以下几点:

app.rb: 11:在`:未初始化的常量Roar :: JSON(NameError)

我找不出如何解决这个问题。

这是我的课,我使用它:

class Todo < ActiveRecord::Base 
    validates :title, presence: true, length: { minimum: 3 } 
    validates :body, presence: true 

    todo.extend(TodoRepresenter) 
    todo.to_json 
end 
+0

你可能应该使用助手Roar :: Sinatra而不是'include Roar :: JSON' – 2014-11-03 09:19:56

+0

你是否尝试添加'require'roar/json''? – 2014-11-03 09:26:08

+0

@UriAgassi当我这样做时,我得到:/Users/JW/.rbenv/versions/2.1.3/lib/ruby/2.1.0/rubygems/core_ext/kernel_require.rb:126:in'require':无法加载这样的文件 - 咆哮/ json(LoadError) – LiveNL 2014-11-03 09:28:11

回答

0

我找到了答案。首先,使用单引号或双引号,而不是两者。

我要求:

require 'sinatra' 
require 'sinatra/activerecord' 
require 'sinatra/base' 
require 'roar-sinatra' 
require 'roar/representer/json' 
require 'roar/representer/json/hal' 

创建一个模块(类+申述的标题):

module TodoRepresenter 
    include Roar::Representer::JSON 

    property :title 
end 

而且在路由使用它:

get '/todos/:id' do 
    Todo.find(params[:id]).extend(TodoRepresenter) 
    @todo = Todo.find(params[:id]) 
    @title = @todo.title.to_json 
    puts @title 
    erb :'todos/show' 
end 

在我的控制台,我现在得到了我的@title。

相关问题