0

I'm trying to get the following code to work, but it's giving me an undefined variable error:

class PagesController < ApplicationController
  @company = "Acme"
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end
end

How do I access @company within functions?

2 Answers 2

3

As in Ruby, every class is an object too, what you are doing here is setting an instance variable named @company on the class object PagesController, not on an instance of PagesController.

What you may want is to use a constant instead of the instance variable. Maybe like this:

class PagesController < ApplicationController
  COMPANY = "Acme"

  def home
    @title = "Welcome to #{COMPANY}"
  end

  def faq
    @title = "FAQ | #{COMPANY}"
  end
end

If you want the company to change dependent of what "page" you are displaying, you should consider adding a Page model which has an attribute which holds the company name or an association to another model named Company.

Sign up to request clarification or add additional context in comments.

Comments

0

You can access it directly like this

class PagesController < ApplicationController
  @@company = "Acme"  # class var
  def home
    @title = "Welcome to #{@@company}"
  end
  def faq
    @title = "FAQ | #{@@company}"
  end
end

Or define a custom getter method like this

class PagesController < ApplicationController
  @@company = "Acme"
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end
  private
  def company
    @@company
  end
end

Or get Company name from database

class PagesController < ApplicationController
  def home
    @title = "Welcome to #{company}"
  end
  def faq
    @title = "FAQ | #{company}"
  end

  private
  def company
    @company ||= current_user.company  # get company of logged in user (and "cache" it)
    @company.name
  end
end

4 Comments

The first example outputs nothing in #(@company), is the second one a good practice?
I think accessing the class variable with a getter is better practice than direct access.
I provided a more dynamic example that retrieves the company name from the current logged in user
Thanks macek, the dynamic example is great, but for my needs a simple constant might be better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.