Ali
Ali

Reputation: 5476

Rails: Creating a static string class

I'm new to Rails and I'm trying to understand a basic concept.

I would like to create a class that inclues only static variables of strings, where I can call them from a controller when I want to. I wanted to achieve this by creating a strings folder under app directory. Later on I've created a class called String

class Strings
@testString="this is my test string"
end

Later on I fail when I try to call it from a controller's index (but I don't think the function or the controller would matter. Why I cannot reach it? Do I have to apply def self.testString all the time?

Upvotes: 0

Views: 1410

Answers (2)

Marlin Pierce
Marlin Pierce

Reputation: 10089

Lets say you have a strings folder under app/models. One of the classes under app/models will be ErrorMessages.

One way is to use constants. This is what constants were designed for in ruby. So file app/models/strings/error_messages.rb would be:

class Strings::ErrorMessages
  TEST_STRING = "this is my test string"
end

Alternatively, you could have an cattr_reader, where app/models/strings/error_messages.rb would be:

class Strings::ErrorMessages
  cattr_reader :test_string

  @test_string = "this is my test string"
end

Or you could just have a method return the read only string.

class Strings::ErrorMessages
  def self.test_string
    "this is my test string"
  end
end

Upvotes: 0

iouri
iouri

Reputation: 2929

I would create them as methods or constants:

class Strings

  TESTCONST = "this is my test string"

  def self.test_string
   "this is my test string"
  end

end

Using them: Strings.test_strings or Strings::TESTCONST

Upvotes: 1

Related Questions