Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2a5e60d

Browse files
author
Tim Perkins
committedMay 16, 2016
Add private_alias_method
1 parent 8f1e2db commit 2a5e60d

File tree

3 files changed

+58
-0
lines changed

3 files changed

+58
-0
lines changed
 

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ class Bar
5757
private_attr_accessor :foo
5858
private_attr_reader :baz
5959
private_attr_writer :bat
60+
private_alias_method :bar, :foo
6061

6162
def initialize foo
6263
self.foo = foo

‎lib/private_attr.rb

+5
Original file line numberDiff line numberDiff line change
@@ -32,4 +32,9 @@ def protected_attr_writer *attr
3232
attr_writer(*attr)
3333
protected(*attr.map { |a| "#{a}=" })
3434
end
35+
36+
def private_alias_method(new_name, old_name)
37+
alias_method(new_name, old_name)
38+
private(new_name)
39+
end
3540
end

‎spec/private_attr_spec.rb

+52
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,24 @@ def write_writer value
3333
def write_writer_other other, value
3434
other.writer = value
3535
end
36+
37+
attr_reader :original
38+
39+
def call_aliased
40+
aliased
41+
end
42+
43+
def call_aliased_other other
44+
other.aliased
45+
end
3646
end
3747

3848
class PrivateDummy < Dummy
3949
extend PrivateAttr
4050
private_attr_accessor :accessor
4151
private_attr_reader :reader
4252
private_attr_writer :writer
53+
private_alias_method :aliased, :original
4354
end
4455

4556
class ProtectedDummy < Dummy
@@ -147,6 +158,47 @@ class ProtectedDummy < Dummy
147158
end
148159
end
149160

161+
describe 'private_alias_method' do
162+
let(:dummy_class) { PrivateDummy }
163+
164+
before { dummy.instance_variable_set '@original', old_value }
165+
166+
it 'allows alias to be called internally' do
167+
dummy.call_aliased.must_equal old_value
168+
end
169+
170+
it 'raises Error when alias is called externally' do
171+
-> { dummy.call_aliased_other other }.must_raise NoMethodError
172+
end
173+
174+
it 'allows the original method to be called externally' do
175+
dummy.original.must_equal old_value
176+
end
177+
178+
describe 'when the original method is overridden' do
179+
let(:dummy_class) do
180+
mod = Module.new do
181+
def original
182+
super.upcase
183+
end
184+
end
185+
Class.new(PrivateDummy).include(mod)
186+
end
187+
188+
it 'allows alias to be called internally' do
189+
dummy.call_aliased.must_equal old_value
190+
end
191+
192+
it 'raises Error when alias is called externally' do
193+
-> { dummy.call_aliased_other other }.must_raise NoMethodError
194+
end
195+
196+
it 'allows the overridden method to be called externally' do
197+
dummy.original.must_equal old_value.upcase
198+
end
199+
end
200+
end
201+
150202
describe 'protected_attr_accessor' do
151203
let(:dummy_class) { ProtectedDummy }
152204

0 commit comments

Comments
 (0)
Please sign in to comment.