Skip to content

Commit 1fcbfac

Browse files
committed
method_missing
1 parent 129628a commit 1fcbfac

File tree

2 files changed

+37
-2
lines changed

2 files changed

+37
-2
lines changed

Readme.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ install ruby dengan perintah `sudo apt-get install ruby`
4444
* Advanced Blocks
4545
* Classes as Objects
4646
* Metaprogramming
47-
* IO
47+
* I/O
4848

4949
## Session 4: Testing
5050

Session3.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -182,5 +182,40 @@ end
182182
[ 1, 2, 3, 4, 5 ].foo # => Monkey patched!
183183
```
184184

185+
Kita juga bisa meng-*override* semua objek, misalnya dengan menambahkan timestamp.
185186

186-
## IO
187+
```ruby
188+
class Object
189+
attr_accessor :timestamp
190+
end
191+
192+
class Class
193+
alias_method :old_new, :new
194+
def new(*args)
195+
result = old_new(*args)
196+
result.timestamp = Time.now
197+
result
198+
end
199+
end
200+
201+
class Foo
202+
end
203+
204+
Foo.new.timestamp
205+
```
206+
207+
### method_missing
208+
209+
Ketika kita mengirimkan pesan ke objek, objek akan mengeksekusi *method* pertama yang ditemukannya pada *method lookup path* dengan nama yang sama persis dengan pesan. Jika tidak ditemukan, ia akan melemparkan *exception* NoMethodError, kecuali kalau kita sudah menyediakan sebuah *method* bernama `method_missing`.
210+
211+
```ruby
212+
class Foo
213+
def method_missing(m, *args, &block)
214+
puts "#{m} not found"
215+
end
216+
end
217+
218+
Foo.new.bar # => bar not found
219+
```
220+
221+
## I/O

0 commit comments

Comments
 (0)