Kerrick
Kerrick

Reputation: 7478

Sinatra: NoMethodError at [...] undefined method `body=' for #<String:[...]>

I got a NoMethodError when trying to return a response in Sinatra. This is the error:

NoMethodError at /contact/book-me.php

undefined method `body=' for #<String:0x00000001911418>

/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in body
        response.body = value
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in invoke
        body res
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in call!
      invoke { dispatch! }
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/sinatra-1.3.2/lib/sinatra/base.rb in call
      dup.call!(env)
/home/kerrick/.rvm/gems/ruby-1.9.3-p194/gems/rack-protection-1.2.0/lib/rack/protection/xss_header.rb in call
        status, headers, body = @app.call(env)
[...]

This is the relevant code:

# Snipped, but basically populate the @error hash if the form wasn't filled out right
if @error.length == 0
  #Snipped, but basically handle the success case
else
  @response = ''
  @error.each do |x, y|
    @response << "<li>#{y}</li> \n"
  end
  return [400, @response]
end

Why is this happening?

Upvotes: 1

Views: 1635

Answers (1)

Kerrick
Kerrick

Reputation: 7478

Using @response as your return value in Sinatra is what's causing your problem. The same problem is documented on the Ruby on Rails OldWiki, so it's not just Sinatra specific. You should change your code to look something like this and it'll work:

else
  @send_errors = ''
  @error.each do |x, y|
    @send_errors << "<li>#{y}</li> \n"
  end
  return [400, @send_errors]
end

Upvotes: 1

Related Questions