NameError: uninitialized constant Roar::JSON in Sinatra

2.3k views Asked by At

I'm building an app in Ruby/Sinatra where I want to use Roar for JSON (and Hal) output. At the moment I'm having problems with Roar.

These gems are installed:

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

and this is in my 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

But when I start my app I get the following:

app.rb:11:in `': uninitialized constant Roar::JSON (NameError)

I can't find out how to fix this.

This is my class where I use it:

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

    todo.extend(TodoRepresenter)
    todo.to_json 
end
1

There are 1 answers

0
LiveNL On

I found an answer. In first place, use single, or double quotes, not both.

I require:

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

Create a module (title of Class + Representer):

module TodoRepresenter
   include Roar::Representer::JSON

   property :title
end

And use it in a route:

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

In my console, I do get my @title now.