开发者

Stating constant values using '||'

开发者 https://www.devze.com 2023-03-26 03:39 出处:网络
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 ||):

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消