Rando Hinn Rando Hinn - 4 months ago 7
Ruby Question

Ruby unknown + on trying to join 2 strings

So, I'm learning Ruby and immediately, have stumbled upon something rater peculiar when trying to concatenate 2 strings to one. Here's the code, with irrevelant parts stripped, lets just say Sinatra runs it:

class CMS
# Set the site path root.
@sitePath = "./site"

get '/' do
renderCache = File.readlines(@sitePath + "index.liquid")
end
end


And on loading the page, I am greeted with

NoMethodError at /
undefined method `+' for nil:NilClass


on the
renderCache = File.readlines(@sitePath + "index.liquid")
line. Why is it refusing to concatenate the strings?

Answer

You can't set instance variables at the class level. You need to set them in an instance method.

Look's like you're using sinatra so you can do this:

See here for how to make a "before filter" like one does in Rails apps. This solution is for the modular style of Sinatra app.

To show an example:

class CMS < Sinatra::Base
  before do
    @sitePath = "./site"
  end
  get '/' do
    renderCache = File.readlines(@sitePath + "index.liquid")
  end
end
CMS.run!

You could also keep your existing code if you use a constant instead of an instance variable:

class CMS
    # Set the site path root.
    SitePath = "./site"

    get '/' do
        renderCache = File.readlines(CMS::SitePath + "index.liquid")
    end
end

To explain how I read your error and looked for the error:

undefined method '+' for nil:NilClass means you're calling + on something which is nil. Referencing the code shows that the nil variable is @sitePath. Undefined instance variables will evaluate to nil. This is different than standard variables, which will raise an undefined variable error.