/librifox\/.*/
, which only shows files that have librifox/ in the path. Next, I refactored our enumeration handler by pulling all the file traversal logic into a base method that takes functions func_each
for code to be executed for each match, func_done
for code to be executed once all the files had been traversed, and func_error
for any errors that occurred. This is a really flexible way to implement an algorithm that has slight variations in how it works, as I can display all the librifox files in a list view and delete all librifox files with the exact same call pattern, just by varying the functions passed as
func_each
and func_done
.Also, because functions keep the scope they were originally called by, I was able to do the following to check whether any librifox files were present on the device:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// adapted from displayAppFiles() in app.js | |
function checkIfAnyFiles() { | |
var items_found = 0; // variable defined in outer function | |
var each_item = function(result) { | |
items_found++; // still in scope for the callback | |
} | |
var when_done = function () { | |
// Output depends on number of items traversed by each_item | |
console.log('found ' + items_found + ' files'); | |
if (items_found == 0) { | |
// ... write 'no files found' to the listview | |
} | |
} | |
enumerateFiles({ // ... , | |
func_each: each_item, // functions are only called inside #enumerateFiles | |
func_done: when_done | |
}); | |
} |
I thought that this was something unique to javascript, but it works in ruby as well! Neat!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TestClass | |
def test_scope | |
times_called = 0 | |
other_func do # passes block into #other_func | |
times_called += 1 | |
end | |
puts "Called #{times_called} times" | |
end | |
end | |
def other_func(&callback) | |
(1..5).each do | |
callback.call | |
end | |
end | |
tc = TestClass.new | |
tc.test_scope #=> Called 5 times |
Looks like you're ahead of me in reading the book. I just finished chapter 2, but I've already encountered enough gems to make me happy.
ReplyDelete