1

我们的应用程序使用了许多环境,因此我们可以在不破坏任何东西的情况下试验设置。在一个典型的控制器动作中,我有这样的事情:

def some_action    
  ...
  if @foo.development_mode == 'Production'           
    @settings = SomeHelper::Production.lan(bar)
  elsif @foo.development_mode == 'Beta'
    @settings = SomeHelper::Beta.lan(nas)
  elsif @foo.development_mode == 'Experimental'
    @settings = SomeHelper::Experimental.lan(nas)
  end
  ...
 end

由于我们有几十个这样的,我想我可以尝试用这样的东西来干掉事情:

 @settings = "SomeHelper::#{@foo.development_mode}.lan(bar)"

这显然不起作用 - 我只是得到:

 "NasHelper::Production.lan(bar)"

我怎样才能减少这种情况,还是我必须坚持我所拥有的?

4

2 回答 2

1

如果您担心最终得到的是字符串而不是对象,则可以使用String.constantize(仅限 Rails,使用标准 Ruby,您必须实现它;它使用 Object.const_get(String))

另一种选择是.const_get(例如Object.const_get(x),其中 x 是您的字符串),它本身不能正确嵌套,因此您必须在“::”处拆分,等等。

此外,还有eval用于评估字符串的选项。但请注意:eval应该非常小心地使用(它很强大),或者根本不使用。

编辑:

这意味着,而不是:

 @settings = "SomeHelper::#{@foo.development_mode}.lan(bar)"

你可以运行:

 @settings = "SomeHelper::#{@foo.development_mode}".constantize.lan(bar)

有用的资源:

http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-constantize

http://www.ruby-forum.com/topic/183112

http://blog.grayproductions.net/articles/eval_isnt_quite_pure_evil

于 2012-11-15T21:06:08.647 回答
0

在第一种情况下,@settings接收方法的结果SomeHelper::Production.lan(bar);在第二个,@settings只是得到一个字符串。您可以使用这里链接的send方法Object来触发该方法,或者eval,但这不是我的首选。

It looks like you might be reinventing a wheel -- Rails already has the concept of "environments" pretty well wired into everything -- they are defined in app/config/environments. You set the environment when you launch the server, and can test like Rails.env.production?. To create new environments, just copy the existing environment file of the one closest to the new one, e.g. copy production.rb to beta.rb and edit as necessary, then test Rails.env.beta?, for example.

But this still leaves you testing which one all over the place. You can add to the config hash (e.g. config.some_helper.lan = 'bar'), which value you can assign to @settings directly. You have to make sure there's either a default or it's defined in all environments, but I think this is probably the right approach ... not knowing exactly what you aim to accomplish.

于 2012-11-15T21:20:16.730 回答