Project

General

Profile

Feature #13009

Implement fetch for Thread.current

Added by dwbutler (David Butler) over 2 years ago. Updated about 2 years ago.

Status:
Closed
Priority:
Normal
Target version:
-
[ruby-core:78500]

Description

It's a common idiom to use a fiber-local variable, but return a default value if it hasn't been assigned. Here's an example of Ruby code I would expect to be able to write:

def feature_enabled?
  Thread.current.fetch(:feature_enabled, true)
end

Unfortunately, Thread.current does not implement fetch, like Hash does. So I have to write the more verbose:

def feature_enabled?
  Thread.current.key?(:feature_enabled) ? Thread.current[:feature_enabled] : true
end

Thanks for your consideration!

Associated revisions

Revision 7d54b4ea
Added by nobu (Nobuyoshi Nakada) about 2 years ago

Thread#fetch

  • thread.c (rb_thread_fetch): add new method Thread#fetch. [Feature #13009]

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@57683 b2dd03c8-39d4-4d8f-98ff-823fe69b080e

Revision 57683
Added by nobu (Nobuyoshi Nakada) about 2 years ago

Thread#fetch

  • thread.c (rb_thread_fetch): add new method Thread#fetch. [Feature #13009]

Revision 57683
Added by nobu (Nobuyoshi Nakada) about 2 years ago

Thread#fetch

  • thread.c (rb_thread_fetch): add new method Thread#fetch. [Feature #13009]

Revision 57683
Added by nobu (Nobuyoshi Nakada) about 2 years ago

Thread#fetch

  • thread.c (rb_thread_fetch): add new method Thread#fetch. [Feature #13009]

History

Updated by shevegen (Robert A. Heiler) over 2 years ago

I can not say whether this feature is important or not, but on the syntax suggestion - I like the above (on the premise that it behaves as .fetch on Hash does; I have not checked this either).

Updated by nobu (Nobuyoshi Nakada) over 2 years ago

Thread.current just returns a Thread instance, so it should be Thread#fetch method.

https://github.com/ruby/ruby/compare/trunk...nobu:feature/Thread%23fetch

Updated by ko1 (Koichi Sasada) over 2 years ago

  • Assignee set to nobu (Nobuyoshi Nakada)

2.4? 2.5?

#5

Updated by nobu (Nobuyoshi Nakada) about 2 years ago

  • Status changed from Open to Closed

Applied in changeset r57683.


Thread#fetch

  • thread.c (rb_thread_fetch): add new method Thread#fetch. [Feature #13009]

Also available in: Atom PDF