Add thread_m/cattr_accessor/reader/writer suite of methods for declaring class and module variables that live per-thread #22630

Merged
merged 3 commits into from Dec 17, 2015

Projects

None yet

3 participants

@dhh
Member
dhh commented Dec 17, 2015

Implementation of #19693.

dhh added some commits Dec 17, 2015
@dhh dhh Add thread_m/cattr_accessor/reader/writer suite of methods for declar…
…ing class and module variables that live per-thread
748b21d
@dhh dhh Use consistent references
b708a60
@dhh dhh Use separate test class name
8a40cba
@dhh dhh merged commit bb4a9e2 into master Dec 17, 2015

2 checks passed

continuous-integration/travis-ci/pr The Travis CI build passed
Details
continuous-integration/travis-ci/push The Travis CI build passed
Details
@dhh dhh deleted the attribute-accessors-per-thread branch Dec 17, 2015
@rafaelfranca rafaelfranca commented on the diff Dec 17, 2015
...ort/core_ext/module/attribute_accessors_per_thread.rb
+ #
+ # If you want to opt out the instance writer method, pass
+ # <tt>instance_writer: false</tt> or <tt>instance_accessor: false</tt>.
+ #
+ # class Current
+ # thread_mattr_writer :user, instance_writer: false
+ # end
+ #
+ # Current.new.user = "DHH" # => NoMethodError
+ def thread_mattr_writer(*syms)
+ options = syms.extract_options!
+ syms.each do |sym|
+ raise NameError.new("invalid attribute name: #{sym}") unless sym =~ /^[_A-Za-z]\w*$/
+ class_eval(<<-EOS, __FILE__, __LINE__ + 1)
+ def self.#{sym}=(obj)
+ Thread.current[:"attr_#{name}_#{sym}"] = obj
@rafaelfranca
rafaelfranca Dec 17, 2015 Member

I think you want to use thread_variable_get here

@dhh
dhh Dec 17, 2015 Member

Nice. Didn't even see those had been added. Using those instead.

@matthewd
matthewd Dec 18, 2015 Member

I'm pretty sure we don't want those. The fiber methods got the short name because they're the ones that people actually want 99% of the time... if you're not doing something very particular, what you really want is a "current-execution-stack-local" variable, and that's what fiber-locals give you.

As I confusingly mis-stated [and then corrected] around #19693 (comment), our existing internal usage is in PerThreadRegistry, which is actually per-fiber.

So, I think 301f438 should be reverted.

@dhh
dhh Dec 18, 2015 Member

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment