0

I am using Ruby on Rails 3.0.9 and I am developing a plugin. I would like to know if it "right" to state a constant value like this (note the ||):

CONSTANT_NAME ||= "Constant_value"

Is it a proper\ensured approach the above?

P.S.: I would like to make that in order to avoid to log warning messages like the following in the Apache error_log file:

/<RAILS_ROOT>/vendor/plugins/sample_plugin/lib/sample.rb:52: warning: already initialized constant CONSTANT_NAME
Backo
  • 18,291
  • 27
  • 103
  • 170
  • have a look at ruby memoization or check http://stackoverflow.com/questions/696338/when-to-use-memoization-in-ruby-on-rails – cristian Aug 06 '11 at 14:47
  • @Octopus-Paul - I read this article http://ryandaigle.com/articles/2008/7/16/what-s-new-in-edge-rails-memoization where the author write memoization about methods... is it possible to use memoization with constant values? – Backo Aug 06 '11 at 15:00
  • Where do you assign that constant? Why is that code executing more than once? – Mladen Jablanović Aug 06 '11 at 15:03
  • @Mladen Jablanović It is because I am implementing an "acts_as_something" plugin and many my models are assigned to "acts_as_something". – Backo Aug 06 '11 at 15:09

1 Answers1

0

It seems clumsy to define constants in several places. I even don't see why you need this. A better solution could be provided if you give more context.

Anyway, a trick could be to create a constant as a Hash. Then anywhere in you app you can define/redefine the it's content. Something like:

CONFIG = { :foo => "bar" } 

Then anywhere else:

CONFIG[:foo] ||= baz

Edit:

With your gem context provided, I'd say you'd better avoid to include the constant at the model level: you won't have to worry if many models use it.

Define it at the application level inside your main acts_as_something.rb file for instance.

apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • I need that because I am implementing an "acts_as_something" plugin and many my models are assigned to "acts_as_something". – Backo Aug 06 '11 at 15:05
  • why don't you define your constant at the app level instead of model level? – apneadiving Aug 06 '11 at 15:15
  • It is because those constants are related specifically to the plugin. – Backo Aug 06 '11 at 15:16
  • I know that, but you can define your constant at a higher level in your gem. – apneadiving Aug 06 '11 at 15:18
  • No, I can not state those constant values at the higher level since my plugin include a lot of modules... however, going back to the original question, is it save to use '||' to state constant values? – Backo Aug 06 '11 at 15:31
  • @Backo let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/2191/discussion-between-apneadiving-and-backo) – apneadiving Aug 06 '11 at 15:32