0

I come from Java background. I was wondering if there was a way to have a class that stored constant values.

Specific to my problem, I was wondering if I could have something like:

@user.authentications.create(:uid => "12345", :provider => Provider::FACEBOOK)

where the Provider class stored all the static constants. Also, is this the right way to do it in Ruby on Rails?

Extra Info: I tried the above by having

class Provider
  FACEBOOK = "facebook"
  TWITTER = "twitter"
end

but it gave the error:

NameError:
       uninitialized constant Provider
Karan
  • 14,824
  • 24
  • 91
  • 157
  • Very similar questions already answered: http://stackoverflow.com/questions/10607063/where-would-i-store-static-constant-values-in-a-rails-application/ – jstim May 22 '12 at 22:13
  • the gist though is to put constants in the context that they are needed. In the specific class they are needed or inside of environment.rb if you need them everywhere. – jstim May 22 '12 at 22:14
  • http://stackoverflow.com/questions/10438647/declaring-static-properties-of-rails-model-subclasses/ – jstim May 22 '12 at 22:15

3 Answers3

1

Option 1 (class variables):

class Provider
  @@FACEBOOK = "facebook"
  @@TWITTER = "twitter"
end

@user.authentications.create(:uid => "12345", :provider => Provider.FACEBOOK)

Using class variables is strongly discouraged though in some cases. A better way to go would be to use meta voodoo:

class Provider
  @FACEBOOK = "facebook"
  @TWITTER = "twitter"

  class << self
    attr_reader :FACEBOOK, :TWITTER
  end
end

@user.authentications.create(:uid => "12345", :provider => Provider.FACEBOOK)
forker
  • 2,609
  • 4
  • 23
  • 24
0

If you would like to keep the implementation above

Try prefixing the Provider::FACEBOOK with a double colon

::Provider::FACEBOOK

This sets an absolute path so Ruby doesn't try to look for the constant inside of the current context/class/Controller. (My assumption is that right now it thinks the constant is defined in UserController::Provider::FACEBOOK)

More Rails-esque

There have been a number of other posts on where to put constants, so please check out:

Basically, put constants where you actually need them. Either in the Controller/Model or in environment.rb if you want to access them everywhere.

Community
  • 1
  • 1
jstim
  • 2,432
  • 1
  • 21
  • 28
0

If you declare that class in your model file then it will be accessible. If you are declare in lib file then you have add one line in your application.rb file

config.autoload_paths += %W(#{config.root}/lib)
Sandip Mondal
  • 921
  • 7
  • 12