Thursday, May 7, 2015

5/7/15 - File Manager UI Improvements

In order to prepare for the Career Center Tech Expo, I hammered out some improvements to our rudimentary file interface.  Before, the app would display all the files on the (emulated) SD card, which for some reason included a bunch of temp files for the emulator.  I first added logic to only show files with paths that matched the regular expression /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:
// 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'm really glad I'm reading JavaScript: the Good Parts :)

I thought that this was something unique to javascript, but it works in ruby as well! Neat!
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

1 comment:

  1. 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