I’ve been spending quite a bit of time programming JavaScript lately,
not only using jQuery and writing simple jQuery
plugins but also building some ‘classes’ to organize the larger
application code. As I’ve been going I’ve been trying to learn how to
really write javascript well, following best practices and using
JavaScript programming
patterns
as much as possible. I’ve been blown away with how versatile JavaScript
really is.
You can see examples of just how powerful the language is by looking at
some of the popular JavaScript frameworks that are out there and just
how differently they do things.
Have you ever thought about how this works? The first bit,
$(’#my-div’), is selecting your element from the DOM using jQuerys
CSS selector engine Sizzle. What you
get back is a DOM element that is wrapped by a jQuery object. You can
then call any jQuery method or methods added by plugins on this object,
such as the addClass method. The method then manipulates the DOM
element or whatever the method is supposed to be doing (in this case
adding the class ‘awesome’).
Now lets contrast this with how the same thing would work with
Prototype.
This code looks very similar to how we did things with
jQuery but underneath the behaviour is very
different. Again $(’my-div’) is selecting the element from the DOM but
with Prototype you get back the actual
DOM element, not an object wrapped by something else. All the
Prototype methods have been added
directly onto the objects that they are intended for (Array methods
added to the Array object, DOM methods added to DOM objects etc). When
you call addClassName it is being called on the DOM element itself and
adding the class ‘awesome’.
I find this to be pretty amazing. The code you write is basically the
same but the underlying way the framework goes about implementing the
behaviour is so very different. jQuery is all
about augmenting the elements and adding the behaviour you when you make
the method calls. Prototype on the other
hand has extended the JavaScript language and objects as soon as you
load it into the page. Two very different approaches to solving the same
problem.
This has just been a little peak into the different approaches you can
take to solving problems with JavaScript. I highly recommend trying out
a different framework than you normally use and seeing how they do
things, it will open your eyes to solutions you might never have thought
of before.
In my last blog
post
I did a tutorial on building a SearchView using UISearchBar and
UITableView. This time around I’m going to talk about mixing together
a UINavigationController, UITabBarController and UISearchBar
together to see what we get. For this post I’m starting out with a brand
new project and doing everything from there, but it should be trivial to
do this in the same project as last time (that’s actually what I did the
first time around). As always, if all you care about is the code [be my
guest](http://jduff.github.com#/2010/03/09/throwing-a-uinavigationcontroller-uitabbarcontroller-and-uisearchbar-together.htmlfull-code, but be warned, we’re doing a lot more in Interface
Builder this time.
Background
Okay, so what exactly are we going to build this time? We’re going to
start with a Tab Bar application which is going to have a
UINavigationController as one of its View Controllers. Once we get
this all set up we’re going to add a UISearchBar as the
navigationItem of the initial view.
When we’re all done we’ll have something like this:
So we have the UISearchBar in the navigationItem and when we push
another View Controller onto the stack it slides over nicely to give you
the back button.
Setting up the Project
As I said earlier I am starting with a Tab Bar application but you
should be able to use any starting point for the application you would
like. I wont go into the details of creating the initial project but
once you’re ready to go and have a UITabBarController in there (the
Tab Bar application gives one to you) open up the Main Window Nib and
take a look at it.
This is pretty straight forward, we have the UITabBarController and it
has a couple of View Controllers that it switches between. If you run
the app right now this is what you would see:
Simple. Lets add the UINavigationController
Adding the Navigation Controller to the Mix
Okay, lets switch back to Interface Builder and drop the
UINavigationController into the Nib inside of the
UITabBarController. Here’s what we’re looking at after that:
Notice how it’s inside the UITabBarController and another button was
added to the Tab Bar? Next we want to add another View for the
UINavigationController to display. I just created a new
UITableViewController (Xcode File -> New File) from Xcode and added
it to the project.
With that added we switch back to Interface Builder and change the class
for the UIViewController that is inside the UINavigationController.
All we had to do is select the current View Controller in the Nib and
then in the Identity Inspector select our new Class in the Class drop
down.
Now when we run the project we see our Table View show up along with the
Navigation Bar.
Okay, we’re just about done. Next we’re going to add that Search Bar to
the Navigation Bar.
Pushing the Search Bar into the Navigation Bar
Alright, time to actually get in and add some code! Lets get into Xcode
and open up that Table View Controller we created and add a few lines to
the viewDidLoad method.
The main thing to take note of here is that we’re adding the Search Bar
to the navigationItem.titleView and then setting the
autoresizingMask on it to be flexible. This might seem like a bit of a
hack, and it very well might be, but it does the job. I also called
sizeToFit on my SearchBar so that it would expand to fit the whole
bar. Let’s take a look.
There we have it! Now when you select an item from the Table View and
push another View Controller onto the stack the Search Bar slides out of
the way for the back Bar Item. If you take a look at the full code below
you’ll see how to do this.
Something to note, if you want to change the color of the Navigation Bar
you will also want to set the tint on the Search Bar so it fits in.
This will set the tint to be black, very much like the ‘Black Opaque’
style that can be set on may UI elements.
Conclusion
There we go, we have a Tab Bar with a Navigation Bar for one of the
items and we’ve pushed a Search Bar into the Navigation Bar. I’ve
included the code below along with some of the generated methods for the
Table View Controller that I hooked up. If you have any suggestions or
feedback please [leave a comment](http://jduff.github.com#comments!
I’ve been working away on some iPhone programming lately and one of this
first things I wanted to add to my app was a view for searching. What I
wanted was to have a view that loads with the curser in the
UISearchBar ready to go and to only load the results when the user
presses the ‘Search’ button. The rest of this blog post will go through
putting all this together. At the end you will have a Search View very
similar to the one in the Flixster
App
and hopefully the knowhow to customize it further. If you would rather
skip the step by step and jump right to the code be my
guest.
Search View Requirements
On load have the curser in the UISearchBar ready for user input.
Search is only done once the ‘Search’ button is pressed.
When entering the query any previous results should not be
clickable.
Here’s a look at what we’re going to end up with:
As a side note, if you’re just looking for a simple type-ahead style
search (kind of like what is used in the App Store or Contacts App) you
might want to take a look at the Search Bar and Search Display
Controller that can be added from Interface Builder. I found it super
easy to use for the simple case just described, but very difficult to
customize for anything else.
Getting Started
I’ll leave it up to you to do the basic setup for your app, I started
with a Tab Bar application for mine but you can use whatever you like. I
then created a Nib for the Search View and a corresponding
SearchViewController.h/m that extends from UIViewController (more on
the code for these files later on). With that done we jump into
Interface builder to drop our UISearchBar and UITableView into our
Nib. It should look something like what I have here:
Next up we want to add some IBOutlets in our SearchViewController.h so
that we can refer to the UI elements we just added from our code. I am
going to make these properties as per the Memory Management
Guidelines
from Apple. I’m also going to define a NSMutableArray to hold the data
to display in the UITableView.
If you didn’t get XCode to generate this file for you make sure you
include the import for UIKit.h.
Now we will quickly jump back to Interface Builder and hook those
IBOutlets up before we forget. You’ll also want to make the
UISearchBar and UITableView delegate to the SearchViewController
so that we can handle the callbacks there.
With the Nib all set up lets make sure we synthesize those properties in
SearchViewController.m and release the variables in our dealloc method.
I also snuck a little bit of code into viewDidLoad and
ViewDidAppear; the former just initializing the tableData
NSMutableArray and the later making our UISearchBar first responder.
Making it the first responder causes the UISearchBar to get focus as
soon as the view loads so that the user can start entering their query
right away.
That’s a pretty good start, lets make sure it builds and see what we get
when we run our app before going on.
Implementing the Protocols
We made the SearchViewController the delegate for both the
UISearchBar and the UITableView so are going to implement the
UISearchBarDelegate and UITableViewDataSource Protocols. First we
need to add the Protocols to the SearchViewController.h header file.
Now we implement the methods in SearchViewController.m. There are a
number of callback methods defined by the UISearchBarDelegate Protocol
but we’re only interested in three: searchBarTextDidBeginEditing,
searchBarCancelButtonClicked and searchBarSearchButtonClicked.
This method is called whenever the UISearchBar gets focus. When this
happens we want to show the ‘Cancel’ button (animated:YES makes it slide
in nicely) and disable the UITableView.
When the ‘Cancel’ button is pressed we want to clear the UISearchBar
text and hide the button. We also want the UISearchBar to
resignFirstResponder status so that the keyboard hides and then enable
the UITableView.
The last UISearchBarDelegate Protocol method is the callback for the
‘Search’ button being pressed. This is where we actually perform the
search and add the results to the UITableView. The rest of this method
implementation is the same as when the ‘Cancel’ button is pressed.
Finally we need to implement the UITableViewDataSource Protocol
methods. I’m not going to go into a whole lot of detail here since
there’s lots of
infoout
there
on implementing a
UITableView.
We’ve done lots of work now and it’s probably a good idea to make sure
everything still builds. You should see something like this when you run
the app:
At this point we’ve hit all three marks in the requirements I outlined
earlier and we could call it quits. We could, but I think we could do a
little bit more to help make the UITableView actually seem like it’s
disabled when you go to search.
Fading out the UITableView
If you take another look at the Flixster
App
or even the initial screenshot I have in this post you will notice that
when you are in ‘search mode’ the background of the screen is faded
black. This effect helps to show the user that the UITableView is in
fact disabled.
To get this behaviour I add and remove another UIView and adjust the
opacity in an Animation so that in fades in smoothly. The first thing we
need to do is create an instance variable and property for this
disableViewOverlay as I called it and initialize it when the view
loads.
I’ll leave it to you to figure out what to put in
SearchViewController.m. Now that we have this UIView all set up all we
have to do is fade it in when the UISearchBar gets focus. This was
actually really easy to do, I just needed to add the
disableViewOverlay as a subview and then use
beginAnimations/commitAnimations for the fading.
At the end of searchBarTextDidBeginEditing we added the code to fade
in the disableViewOverlay, then at the end of
searchBarCancelButtonClicked and searchBarSearchButtonClicked we
remove the disableViewOverlay.
If you’ve been following along you might notice a bit of a code
smell coming from these last
three methods. There’s a lot of code duplication which I don’t really
like so I actually re-factored these three methods and created another
method that all of them can call. The resulting re-factored code looks
like this:
That cleans things up nicely. Now when you run the app you should have
the main view fade out smoothly when you enter the UISearchBar just
like mine below:
Conclusion
There we have it, a nice Search View that you have full control over.
I’ve included the full code with inline comments below, have at it! If
you have any suggestions or feedback please [leave a
comment](http://jduff.github.com#comments!
I’d like to thank everyone who came out to the latest meeting, we had
quite the turnout! A few new faces as well which is always great.
For anyone who doesn’t know “OGRE” stands for “Ottawa Group of Ruby
Enthusiasts”. We’re a local group that gets together on the fourth
Tuesday of each month to talk about Ruby, programming, cool projects and
sometimes even Python. We’re a fairly diverse group from professional
Ruby developers, to tinkerers, people just starting out and everything
in between. Check out the website and the
google group for more info.
This past Tuesday we had Don Kelly and Julie Hache giving a couple
presentations. To recap:
Don Kelly talked about TreeTop
(http://treetop.rubyforge.org/) and
LLVM (http://llvm.org/) giving us a short
example of writing a very simple language with both. He also spent a
bit of time showing us the SEXP parser and interpreter
(http://github.com/karfai/sexp)
that he was working on with both of those tools. Very cool stuff.
Julie Hache gave a presentation on some of the stuff that has
changed with Rails 3 and what the upgrade process is going to look
like. She also walked through how we can get setup and playing with
Rails 3 right now with the beta
(http://weblog.rubyonrails.org/2010/2/5/rails-3-0-beta-release/).
Julie also mentioned a book that Jeremy McAnally just released with
over 100 pages of info on the Rails 3 upgrade process
(http://www.railsupgradehandbook.com/).
Jeremy knows his stuff so I’m sure it will be $12 well spent.
In the last couple months I’ve been thinking a bit about expanding the
skills I have into some different areas. I’ve been working with Ruby on
Rails almost exclusively for over three years and have gotten to know
the ins and outs pretty well. I love Ruby and Rails, but I’m getting
that itch to play with something new. I’ve been playing around with
iPhone development a bit (though I’ve been slacking) and find that to be
really interesting, but I decided the other day to try something
different to fill this need (I will continue to play with iPhone stuff,
it’s just too cool to let go).
Javascript will be my next conquest. Writing Javascript with
jQuery to be exact. I’ve had my love for
jQuery reignited and it complements the other web
development skills I already have. I’d like to think I’m already pretty
good with jQuery, I’ve been using it for various
projects for awhile now, but my goal is to learn it in and out; all the
best practices and neat tricks as well as the limitations and how to
overcome them.
To do this I’m going to start out by trying my hand at writing a few
jQuery plugins of my own and
try to integrate jQuery into any work I might be doing. To start out
I’ve been reading a few blogs and have come across a really great
plugin
pattern
that I’m going to follow for most of my stuff.
jQuery Plugin Pattern: Giving it jQuery
First thing we want to start with is giving our plugin access to jQuery.
This sounds like a no brainer but you have to be careful since the
jQuery helper method ($) can be redefined and therefore isn’t guaranteed
to exist. To overcome this the pattern below is usually used.
This might look a little scary, but all we’re doing is defining a
function that takes a parameter. We’re then calling the function right
away passing in jQuery. Now we can use $ in our plugin without worry!
Playing Nice: Returning jQuery
When using a jQuery plugin there are a couple of things that users come
to expect. The two main things is that the plugin should be able to work
on an array of objects and at the end it should return the jQuery object
to allow chain ability. Accomplishing this is very easy with the code
below.
Giving the User Control: Plugin Options and Defaults
The next thing we’re going to want to give our plugins is a way for the
user to pass in options to override the defaults. I also like the way
the jQuery UI plugins give you public access to
the defaults so that you can set them once instead of every time the
plugin is called. Learning
jQuery
has some code to do just that and looks something like what I have
below.
This code lets our plugin users do a couple interesting things. First
thing is they can pass options to plugin like below.
What is more interesting is the fact that instead of having to pass the
same options in every time they could set the defaults at the start and
be done with it, only passing in options that differ from their own
defaults.
This gives the users a lot of flexibility and helps them to keep their
code nice and
DRY.
Giving the User Control: Exposing Public Functions
Sometimes it makes sense to expose plugin functions to the user so that
they can override the implementation with their own. This might not be
needed for all plugins, but I think it would be useful for most.
This gives the user a lot of control over how the plugin behaves. Again,
it doesn’t make sense for all plugins but when sometimes it can be a
real life saver. All the user has to do to provide their own
implementation to the helper function is to redefine it like below.
The big benefit to this that I see over having a callback is that you
could save the original function and use it in your implementation,
something like this.
This lets you build upon the original implementation if you want to,
meaning less repeated code.
Wrapping Up
Well, that pretty much does it for how I want my jQuery plugins to be
structured. I’ve left out a bunch of stuff that beginners should
probably take a look at,
theselinks should help if you’re
interested.
I’ve got the full template below and I’ve also put it up on
Github with a few more
comments, feel free to fork it and send me updates.
In the last little while I started working on a Rails project that had
been targeting an older version of mySQL. I ran into a few confusing
problems while getting started so I thought I’d bring together all the
various mySQL and Rails related info I came across to fix my problems
into one place.
Problem: ActiveRecord failing with a default field value of blank
This is a problem that a few people have posted on
ruby-forum without getting
much of a response, but what is there pointed me in the right direction.
The main problem is that older versions of mySQL (pre 5.0.45 I believe)
treat a NULL value inserted into a string column as a blank string.
Newer versions of mySQL fix this issue but this fix causes some
confusing behaviour.
What happens in the older version is maybe you forget to pass a value
for that NOT NULL string; mySQL happily treats that as a blank string
and gives you no errors. When you upgrade mySQL to a version that
‘fixes’ this you end up with all kinds of errors because the constraint
isn’t being met anymore.
Solution
Well, if you don’t actually need the constraint remove it, otherwise
explicitly send a value so the constraint is met. Update your tests and
validations so you’re passing and checking that the correct values are
being passed.
Another one that also shows up on a ruby forum
post. The root of this problem
is that on OS X the mysql gem has to be told where the installed mySQL
libraries are and which architecture your machine is.
Solution
I found the solution
here
but had to modify the gem install slightly for my 64 bit machine.
This might be slightly different depending on where mysql ended up on
your machine and your machines architecture.
Problem: mySQL can’t install because a newer version exists
Or, removing mySQL for real. While dealing with my first problem I tried
installing and uninstalling different versions of mySQL along the way
the mySQL install got angry because some files weren’t removed and
wouldn’t install the version I wanted.
Solution
I managed to get mySQL off my machine by combining the approaches from a
blog
post
and an answer found on Stack
Overflow.
Before doing this I did run the mySQL uninstaller, but it seems to leave
some goodies behind.
In the end it boiled down to running the following commands:
I know it’s a lot of mumbo jumbo, but mySQL seems to hook itself in all
over the place and this, in the end, did seem to get rid of everything.
Conclusion
Well, that’s all I’ve got for mySQL right now. It was a pretty
frustrating trip, but in the end I managed to find a solution to all the
problems and now it’s all in one place for all of time.
As a side note I’m really starting to find Stack
Overflow to be an incredibly useful resource.
Sometimes it might even save time trying a quick search there before
hitting up Google.
As I mentioned in an earlier
post I attended
this local Ottawa event called Startup Boot
Camp on the
weekend. Well, I’ve got to say, this was one of the most interesting
events I’ve ever been to. Let me break down how the weekend went a
little bit.
Day 1 (Friday 6pm - 9pm)
The first day started out with an introduction to the event, sponsors,
organizers and all that jazz. The didn’t waste any time and moved onto
the pitches. There were 8 ideas presented by some really energetic
people ranging from major hardware, software or a combination of the
two.
After voting on the pitches the bottom two were dropped and everyone
split off around whichever idea they found most interesting. The teams
ranged from 6-13 people with backgrounds in software, hardware,
marketing, sales, business development etc.
After getting to know my team a little bit we headed home to rest up a
little bit and get ready from the rest of the weekend.
Day 2 (Saturday 9am - 6pm)
Today everyone gathered together in the main room to be introduced to
some of the mentors that would be available to help us develop our
pitches. We had financial experts, accountants, lawyers, operations
experts, human resources consultants, pretty much everything you might
need to get a business started.
After the quick introduction everyone split off into their groups to
start working any of the kinks out of their startup with the help of the
mentors. I’ve got to say, the experts they brought in were just
phenomenal. This event was well worth it just to be able to spend some
time with these people and to draw from all the experiences they have
had.
By mid afternoon we had most of the details figured out so we decided to
individually take a look at the slide deck we needed to put together and
jot down some ideas. By the end of the day we had a pretty good idea of
what we needed in the deck but still stuck around after 6 to go over
things a little bit more and split up some ‘homework’.
Day 3 (Sunday 9am - 6pm)
Again, we started out with an introduction to a new set of mentors, no
messing around now though so we quickly broke off and got down to work.
Today was all about putting the slide deck together, making it look good
and making sure we had answers to all the questions the panel might ask.
Around 1pm we started practicing the presentation and tweaking anything
we still could based on the mentors comments.
At 3pm everyones back in the room for the pitches in front of the panel.
I found it really interesting how the presentations really seemed to
reflect on the team behind them. One team had an industrial designer as
the lead so their slide deck was super slick, they even had small
prototypes that they handed out to the judges. Other side decks really
showed the technical expertise of their group with detailed diagrams and
flow charts on how their products would work.
After presenting the judges asked some great questions and before
announcing the winner provided some feedback to each group on what they
really needed to look at to make their product work. All of this advice
was right on the money and, I would imagine, will help these startups
move forward in the future.
In Closing
Well, in the end my team didn’t win the final prize but I think everyone
involved did get a lot out of the event, I know I did. My teammates were
an amazing group of people that I was really glad to have met and spent
the weekend working with, the mentors and judges gave a huge amount of
advice that would be next to impossible to easily get otherwise and I
had all kinds of fun.
Big thanks goes out to Rick O’Conner and
the rest of the Ottawa Network for
putting together this event. Word is they’re already looking to do a
repeat of the Startup Boot
Camp in March so be
ready to sign up, I know I will be!
I find one of the most useful ‘tricks’ in Ruby is to use the ‘&’
character to convert Ruby Proc objects into a block. What exactly does
this mean? Well, the best way to explain it is with a couple of
examples.
This is a pretty simple block of code, all we’re doing is converting an
array of words to uppercase. Now say we’re good ruby programmers and
want to keep our code readable and concise, how does this stand up?
Well, it is a simple block so it is fairly readable, but how about we
take a look at the same piece of code using the ‘&’ method to convert a
proc into a block.
These two blocks do the exact same thing, but I find the second method
to dramatically improve the readability even in this simple example.
So, what’s really going on here? Well Ruby sees the ‘&’ so it wants to
convert the Proc to a block. Since we have a Symbol on the other side
Ruby type converts it to a proc by calling to_proc on the Symbol which
returns a Proc that takes one argument and calls the method named by the
symbol on that object. The implementation of to_proc on the Symbol
class might look something like this:
The actual implementation is a little more complicated, allowing
multiple arguments etc, but you get the idea.
You can also use this method with a normal Proc object instead of just
with a Symbol, making something like this possible:
Pretty cool isn’t it? I’ve been using the Symbol technique for awhile
now to keep my code concise and readable, I never even thought about
using a Proc until doing a little bit of research for this article. If
you want to know more about all of this check out Understanding Ruby
blocks, Procs and
methods
by Eli Bendersky, I based some of my examples off of his article.
The other day Jon Maddox sent me a message
on Github to see if I was thinking of putting my gem
tmdb_party up on
Gemcutter, the new RubyGem host on the block.
At the time I hadn’t really thought much about doing this thought what
the heck? It didn’t seem like it was too difficult so I thought I’d put
it to the test around midnight on a Saturday night.
Well, I have got to say, this was probably the easiest thing I’ve ever
done. I was going into this thinking it wouldn’t be too difficult but I
was still impressed with how it went.
The first step is to sign up for a Gemcutter account right
here which takes about 10
seconds.
The next step is to update your Jeweler Rakefile to add the
Gemcutter task. I’ve included a sample of what my Rakefile looks
like below.
!include tomd-include-0.txt
Now all you need to do is push your gem the new task and provide
your Gemcutter credentials
!include tomd-include-1.txt
That’s it, now my tmdb_party gem is up on
Gemcutter. On a side note, if
you’re not using Jeweler
to manage and release your gems you really should, it makes releasing a
gem incredibly simple.
While working on the Presence
assignments for the
Stanford iPhoneU
course I
noticed that they did something really interesting to make interacting
with the Twitter API a little bit easier.
They setup a server that responded to actions similar to Twitter with
some sample data. This really helped out so that when messing around
during development so that Twitter wasn’t annoyed with all the requests.
While working with this dummy server they set up I got thinking that
something like this might be useful when developing other API mashups. I
don’t think Stanford wants to set something like this up for all the
apis out there though, so what about a Gem that does something like
this?
What I’m thinking of is a very simple gem that basically runs a
Sinatra app which mimics a Twitter or
Google Maps or some other api. These ‘mock apis’ could be plugins that
could easily be pulled into the gem and run locally. I could see running
commands like ‘fakeserver install Twitter
git://github.com/jduff/fake-twitter.git’ and this would install a git
clone so that it can be kept up to date. Then you could run the fake
server with ‘fakeserver Twitter’ and then you’d have a local server that
mocked Twitters API.
I did a little bit of searching and still haven’t really come across
anything that does what I am thinking. There is this project,
mock-server that is kind of
like FakeWeb but you define the
mocks by writing actions like you do with
Sinatra. This is kind of what I’m thinking
of except it doesn’t run a server, but the general idea is pretty much
the same.
I’m not sure if there is another project that does what I am thinking of
but I might start working on something like this. If anyone has any
ideas or suggestions leave a comment and let me know.