Skip to content

Make Mutex_m work with Module#prepend #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,10 +34,12 @@ obj.extend Mutex_m
```

Or mixin Mutex_m into your module to your class inherit Mutex instance methods.
You should probably use `prepend` to mixin (if you use `include`, you need to
make sure that you call `super` inside `initialize`).

```ruby
class Foo
include Mutex_m
prepend Mutex_m
# ...
end

Expand Down
5 changes: 5 additions & 0 deletions lib/mutex_m.rb
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ def Mutex_m.define_aliases(cl) # :nodoc:
cl.alias_method(:synchronize, :mu_synchronize)
end

def Mutex_m.prepend_features(cl) # :nodoc:
super
define_aliases(cl) unless cl.instance_of?(Module)
end

def Mutex_m.append_features(cl) # :nodoc:
super
define_aliases(cl) unless cl.instance_of?(Module)
Expand Down
43 changes: 43 additions & 0 deletions test/test_mutex_m.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,49 @@ def test_initialize_no_args
assert NoArgInitializeChild.new
end

class PositionalArgInitializeParent
attr_reader :x

def initialize(x)
@x = x
end
end

def test_include
c = PositionalArgInitializeParent.dup
c.class_eval do
alias initialize initialize
def initialize(x)
@x = x
super()
end
include Mutex_m
end
o = c.new(1)
assert_equal(1, o.synchronize{o.x})
end

def test_prepend
c = PositionalArgInitializeParent.dup
c.prepend Mutex_m
o = c.new(1)
assert_equal(1, o.synchronize{o.x})
end

def test_include_sub
c = Class.new(PositionalArgInitializeParent)
c.include Mutex_m
o = c.new(1)
assert_equal(1, o.synchronize{o.x})
end

def test_prepend_sub
c = Class.new(PositionalArgInitializeParent)
c.prepend Mutex_m
o = c.new(1)
assert_equal(1, o.synchronize{o.x})
end

def test_alias_extended_object
object = Object.new
object.extend(Mutex_m)
Expand Down