3 ms·
How prevalent is `try` in rails/activesupport? My benchmarks show that the lonely operator is ~2x faster than `try`. I'd expect someone to create a gem that mon
by anonova 11y ago
How prevalent is `try` in rails/activesupport? My benchmarks show that the lonely operator is ~2x faster than `try`. I'd expect someone to create a gem that monkey patches `try` for those running 2.3.0.
- hueho 11y agoThere isn't really anyway to monkeypatch `try` to use the operator. `try` API is inherently based on metaprogramming (passing a symbol to call), and have different semantics than the operator (by default it won't throw if a non-existent method is called in a non-nil object, while the operator will thrown a NoMethodError) https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/core_ext/object/try.rb#L62 https://github.com/rails/rails/blob/4-2-stable/activesupport...
- simplyluke 11y ago`try` is pretty prevalent in rails dev from what I've seen in the field.
- allworknoplay 11y ago`try` is different from `try!`. the new lonely operator is like `try!`, which asks only if the object is nil and then calls the method on it if it's not (and will blow up if the object doesn't have the method publically defined). `try`, in contrast, asks if the object is nil or responds to the method and returns nil if it doesn't.
- matthewrudy 11y ago`try` is bad for a number of reasons. Because itll never throw an error, you see it hiding issues. And I keep seeing colleagues writing `hash.try(:[], :some_key)` `try!` is better. But I'll stick to `&.` from now on.
- kelseydh 11y agoUsing `try` is definitely a code smell, but unfortunately it's often a necessary one in production environments that have seen some wear and tear in the integrity of their database structures.