我有以下示例 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_send
或 try
)允许您在 @theme
对象上调用任意方法。将颜色保持在散列中可能更安全。
关于ruby-on-rails - Ruby 尝试不处理异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46561941/