ruby-on-rails - Ruby 尝试不处理异常

标签 ruby-on-rails ruby

我有以下示例 ruby​​ 代码:

def example_method(obj)
    ExampleClass.new(color1: @theme.try(obj['color1'].to_sym))
end

应该将 obj['color1'] 作为符号或 nil 传递给类。

但是,如果未传递 color1,我会收到错误消息:NoMethodError: undefined method 'to_sym' for nil:NilClass

try 方法不应该处理异常吗?


更新:基于评论......我通过三元解决了它:

ExampleClass.new(color1: obj['color1'].present? ? @brand_theme.try(obj['color1'].try(:to_sym)) : nil)

最佳答案

你可以写一个辅助方法:

def theme_color(name)
  return unless name
  return unless @theme.respond_to?(name)
  @theme.public_send(name)
end

def example_method(obj)
  ExampleClass.new(color1: theme_color(obj['color1']))
end
如果参数为 nil,则

theme_color 返回 nil,即 obj['color1']。如果 theme 不响应给定的方法,它也会返回 nil。否则,它会调用 name 指定的方法。

请注意,respond_to?public_send 接受字符串或符号,因此不需要 to_sym

您还可以将辅助方法定义为您的 @theme 类的实例方法:

class Theme
  def color(name)
    return unless name
    return unless respond_to?(name)
    public_send(name)
  end

  def red
    'FF0000'
  end
end

@theme = Theme.new
@theme.red            #=> "FF0000"
@theme.color(:red)    #=> "FF0000"
@theme.color('red')   #=> "FF0000"
@theme.color('green') #=> nil
@theme.color(nil)     #=> nil

并通过以下方式调用它:

def example_method(obj)
  ExampleClass.new(color1: @theme.color(obj['color1']))
end

请记住,这些方法(使用 public_sendtry)允许您在 @theme 对象上调用任意方法。将颜色保持在散列中可能更安全。

关于ruby-on-rails - Ruby 尝试不处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46561941/

相关文章:

ruby-on-rails - 在自定义位置/ View 中呈现 Rails 教程中的 'micropost feed'?

ruby-on-rails - Rails 4.2 片段缓存不起作用

ruby-on-rails - 如何搜索看起来像上传图片的图片

ruby-on-rails - rails "No route matches POST/images/1"错误

ruby-on-rails - Rspec测试加载错误: cannot load such file -- spec_helper (LoadError)

ruby-on-rails - 为什么在 ApplicationController 上定义为私有(private)的方法可以在派生类的方法内部调用,但不能在派生类本身内部调用?

ruby - URI.escape 的简单替代方案

javascript - 从先前选择的字段动态更改表单字段,迭代 javascript

ruby-on-rails - 通过保持连接打开来加速 OpenUri?

ruby-on-rails - 由于 mimemagic,Capistrano 部署失败