Monday, 29 October 2012

Rails App from Scratch (On fresh Lion installation)

I'm setting up a new Mac Mini for Ruby on Rails development. It was pretty much headache free. I knew I needed my app to use MySQL so I wanted to set things up to incorporate this. Here's the list of components that need to be installed in the order shown.
  1. Xcode (with Command Line Tools)
  2. Homebrew
  3. MySQL & MySQL Workbench
  4. RVM (installing lastest Ruby 1.9.3)
  5. Install gems to against 1.9.3 gemset: rails, bundler, mysql2, activerecord-mysql2-adapter
  6. Rubymine (My editor/IDE of choice for RoR development)
Once all of these are installed, you can use Rubymine to create a new rails project, configure your database.yml file, generate a model (with a migration), and run rake db:migrate to confirm that all connections are up and running. We'll step through this at the end.

Install Xcode


Best done through the Mac App Store. Launch the App Store and search for xcode. Follow directions to install it.

Once Xcode is installed you need to install the Command Line Tools. This gets you lots of command line goodies we'll need for ruby and rails development. (One main one being the gcc compiler, integral for running Ruby.)

Within Xcode, go to Preferences > Downloads > Componenents. From here, you can install the 'Command Line Tools'.

Install Homebrew


Homebrew is a package manager for Mac OSX. It's currently quite popular and I like it as it seems to work the most smoothly with the latest components new in Lion. Here's a comparison between the different options in this area.

Lion ships with Ruby installed, so we can use this default version to install Homebrew. Run this in your terminal: 

$ ruby -e "$(curl -fsSkL raw.github.com/mxcl/homebrew/go)"

Install MySQL


Super easy now that we have Homebrew.

$ brew install mysql

When this finishes it gives you some instructions of a few things to do to set up the root account and different configuration options for startup, etc... read these and do what you think you need to do. I'm going to configure it to start when the system starts

$ mysql_install_db --verbose --basedir="$(brew --prefix mysql)" --datadir=/usr/local/var/mysql --tmpdir=/tmp
mkdir -p ~/Library/LaunchAgents
cp /usr/local/Cellar/mysql/5.5.15/com.mysql.mysqld.plist ~/Library/LaunchAgents/
launchctl load -w ~/Library/LaunchAgents/com.mysql.mysqld.plist

You may still need to manually start it at this point before you can log in.

$ cd /usr/local/opt/mysql ; /usr/local/opt/mysql/bin/mysqld_safe &

Now, login.

$ mysql -uroot

If this is successful, you're almost there, the only thing left is to install the MySQL WorkBench!

Create a connection using the default configurations: user: root, host: 127.0.0.1, port: 3306. Now you can create databases against this connection through this interface. We'll do this later though!

Install RVM


I used this as a step-by-step installation guideline.

But, basically... for installation. You just need to run this from your terminal:

$ curl -L get.rvm.io | bash -s stable

Now we can install the latest Ruby (or which any you need) First, list all the ruby versions available for installation:

$ rvm list known

I'm going to install the latest version, 1.9.3.

$ rvm install 1.9.3

Before we start installing gems, lets tell RVM the version of ruby we want to install gems against.

rvm use 1.9.3

Installing Gems for Rails Development using MySQL


$ gem install rails
$ gem install bundler 
$ gem install mysql2
$ gem install activerecord-mysql2-adapter

Install RubyMine create a new Rails project


Once RubyMine is installed, launch it and create a new project. 
  • Make sure to specify the project type as 'Rails Application'.
  • Select the ruby version you want to use. 
  • If RubyMine doesn't know the Rails version it should use, you will need to click the '...' box next to the Rails Version dropdown. RubyMine will go and get it!
  • Click 'ok' and we're ready to go!

Configure your database.yml File


It should look something like this:

Test that everything is up and running.


$ rails g model user
      invoke  active_record
      create    db/migrate/20121029132052_create_users.rb
      create    app/models/user.rb
      invoke    test_unit
      create      test/unit/user_test.rb
      create      test/fixtures/users.yml

Edit your migration file to reflect the columns you'll need in your table. If all this doesn't make sense, spend some time researching ActiveRecord and Rails database migrations.

If you need a cheat sheet to help with defining your columns, check this out.

Now you should be able to run this:

$ rake db:migrate


BOOM. Easy Peasy.


Friday, 26 October 2012

Post 4.3 Xcode & Command line tools

I'm currently getting new mac mini ready for Ruby on Rails, iOS and Android development. I had Xcode 4.3 installed by default but I didn't have the standard /Developer directory where you get all the lovely command line tools used for Ruby development. Some of my gem installs were working, but some were not. Was seeing stuff like this from the terminal:

$ make
-bash: make: command not found

Weird, right? Where are my command line tools?

Turns out, in Xcode 4.3 and later, you have to specifically install these and they aren't in the /Developer  directory.

Once Xcode is installed. Go into Preferences > Downloads Tab > Components Pane

From there install Command Line Tools.

Boom. Terminal works.

Tuesday, 11 September 2012

Guava's EventBus and Android's async tasks

Android requires that you do all network processing on non-UI threads. This is good business as it means unexpected exceptions aren't going to crash your app. It can be a little problematic when you need to be notified of the different outcomes of your various network activity. You need to notify an activity, it needs to notify one of it's components.

The Callback Approach

This is essentially like handing a reference to the caller of the process. The process then calls an appropriate method on the caller, depending on the outcome.


The Guava EventBus Approach

This approach decouples the caller from the process. The caller can register for different events on the event bus after which, any process can put that event on the event bus. The registered processes with get notified.

You have to define those events but they can be empty or you can wrap anything you need in them.
Then all you have to do is subscribe for the event from the activity. It doesn't matter what you call the method... what matters is the parameter must match an event that will be put on the message bus.

Why is the event bus better? 

Well it decouples the method responding to the outcome of the network activity or whatever from the task doing this. You don't have to pass a reference of the thing doing the responding to the task. Another benefit here is that anything can register to respond to this event. Be it the activity, or one of it's fragments, it's action bar, or whatever. Nice!

Thursday, 6 September 2012

iOS development - Writing an app - Pt 2 - Choosing data storage

This is the 2nd in a series of posts concerning iOS development. I want to begin my app by choosing a data storage technique. I'm leaning towards Core Data because I want to hook it up with my models using xCode's for iOS 5 storyboards... but I realize I need to do my due diligence and research all the options. So, here they are with an outline of my needs.

The vision for my app will definitely involve some robust storage capability. Without saying too much, the foundation for my app will be a users ability to build, track, and share recipes. I'd like to investigate my options for this. My research has concluded that in iOS development you have a number of on-device data storage techniques as your disposal.

Property Lists - These are sort of key-value pair storage techniques. You define them programmatically and they're loaded when the app starts. I suppose this is the simplest, most basic option. It's limitation would be you don't get any relational capabilities.

SQLite - With this option you get the relational thing at least in your database because it's SQL. It's my understanding that the support for this comes from some C libraries included into the iOS framework. Since SQLite works off a single file, you can seed this with your data and load it into your application. I plan to investigate this further in another post. It appears this option involves the requirement of writing your own sql queries. Boo.

Core Data - This is sort of the Maserati option. Core Data is provided and customized to work with xcode development. You get your relational structure. You hook it to your data models via xcode. You don't have to deal with database connections or schemas. It's basically the only option where you get an ORM feeling.

My decision is to move forward with Core Data. Not only will it satisfy the curiosity of how storyboards work with it, but it's the ORM option. And I love ORMs. Don't get me wrong, I can write my fair share of SQL, but if there's something out there that does all this for you... why not use it?

Sunday, 2 September 2012

iOS development - Let's write an App - Pt 1

This will be the first in a series of posts where I document the process of writing an iOS 5 app using Xcode. I've been playing around here and there for about a year. I want to take it to the next level though. I'm going to write an app around storing, tracking and sharing home-brewing recipes.

As I write my app, I'm going to move through the decision-making process, high-lighting what I'm thinking about and why I'm making the decisions I'm making.

I've obviously already made a couple decisions so I'll go ahead and document those here.
  1. Why a home-brewing app? Because I love home-brewing. :-) (Even though I don't do it anymore.... see: the size of my NYC apartment.) I also think there's a gap in the market here... be it a somewhat niche market.
  2. Why native iOS? Well, my current 9-6 job is native Android development. I want to explore something outside of this. I thought about doing an HTML5 or jquery-based mobile website. And, I appreciate the fact that you reach more users this way. It's just that I'm less interested in exploring these right now. I want to play around with Xcode, especially some of the latest features.  
So, off we go! 



Sunday, 19 August 2012

Avoid ABSTRACT Classes!!!

Ahem... In business enterprise software. I will put forward the case that 95% of the time there is an alternative to a design involving abstract classes that will leave you with DRY, well-tested code and without the inherent risk that comes with inheritance. (That risk being a big jumbled spider web of parent-classes and subclasses that inevitable happens after x number of developers touch it.)

Back when I learned how to do OO in large codes bases.... Oh those 6 long years ago... I worked in London and was influenced by a few very awesome developers. We were doing C# and I remember this team where the leaders said 'No abstract classes.' And the code was beautiful. It might be said that we all just really cared. But, I have worked on very few teams where the majority of coders didn't care. We always care and strive for beautiful code. Anyway, today I find myself back in the US and working in the Java world, doing android development. And I find abstract class use everywhere. Everyone embracing it. And honestly, I see it lead to a tangled mess 95% of the time.

I see the appeal. You reduce duplication. If you were to use an interface instead of an abstract class, you would have several classes implementing the same interface but what about the common functionality. That's what an abstract class gets you. You can pop the common stuff in the abstract base class.

I rarely see a problematic situation at the time of initialing setting this up. It's normally beautiful. You say 'Yeah! Look at that beautiful inheritance. This is great. No duplication.' DRY, right?

The problem comes when you have to come along later and add a little functionality here or there. Often additional layers get added into the hierarchy and you sprinkle the common functionality where they belong. So maybe you started with 1 abstract class and 4 classes extending. You come along a month or 2 later and there's 1 base abstract class, two other abstract classes extending this and a slew of concrete classes extending any of these 3 abstract classes.

If this doesn't sound scary, maybe it's never happened to you. Let me just overview the pain I feel when working with this sort of thing is.

1. It's nightmare for a developer who's unfamiliar with the codebase. Who's overriding what? Who's implementing what? Who's responsibility is what?
2. It's hard to unit test. Who do you test? Really, you have to test all the concrete classes completely. This includes the functionality they implement themselves and the functionality they get from any of their parents. You could say.. well, write unit tests for the parents and then don't retest in the subclasses. The issue here is that you can't test that the subclass is specifically using the functionality from the parent through interaction based testing (mocking and stubbing). To be sure it's using the right code, you have to unit test the specific functionality for that code.. wherever it is. So, you either have duplicate tests or incomplete test coverage.
3. It's often highly brittle to change. This is because it's inevitable under tested and often not completed understood by those augmenting functionality.

I can't say that inheritance is never right. In fact it often feels right. And if you're working in a small team where you can discuss design frequently catch these things turning into issues... maybe it's worthwhile embracing it more. My feeling is that if you aren't working on a small team.. and/or you have even a minimal level of turnover among you're developers. This problem will almost certainly rear it's head.

What is the answer?? Let's turn back to the things taught by the gang of 4 and that super genius, Martin Fowler.  There must be some wisdom there! I'll dive into this next. I just want to reread a few chapters and articles first.


Thursday, 9 August 2012

Android Fragments

I've been developing in Android for the last 5 months. Aside from the normal learning curve when learning a new technology, my team and I have found Android's fragments a bit of a headache. The android documentation is great. But there are a few things they don't explicitly mention that I really would have found useful to know or think about up front.

There are two options for using fragments, really. At least when looking at it from a high level. And I didn't realize the benefits or drawbacks of either of these... or the implications.

Option 1- Implement it and manage it yourself. 

This is what I did first. In this sense it's still a sort of miniature activity. 
There are a few ways you can do this.

  1. Define it as a fragment in the layout that your activity inflates.
  2. In doing this, you can inject it into your activity (if you're using roboguice) or pull it out into your activity as you would any other layout component to operate on it or delegate to it.
  3. Use the fragment manager to load the fragment in a FragmentTransaction and then load it into your layout based on some id (within a LinearLayout or something).
This would allow you to toggle the fragment for a given section of your activities layout.

The first way I went was a little of both of these. As it seemed to fit the bill and I didn't know any betting. I have since found that managing many fragments within an activity in the above fashion does not scale well. Also, the thing mentioned in the first option... where you can grab your fragment from the activity and delegate to it. That turns out to also be a mess. Ideally, you want your fragment to live in it's own little world. Without having to talk to it's activity or whoever is holding it.

Option 2 - Use Android components 

(i.e. ActionBar, Menus, etc..) 

What happened in my situation was that the number of fragments I needed on my screen was growing. There was more and more stuff going on and now I needed to manage the interactions myself. There was realization at some point that... 'Hey, those Android docs going on and on about the Android way of doing things... maybe they can help here!' So enter a few useful components.


Action bars and menus manage Fragments for you! You just hook into the behavior they provide and tell them which Fragment and when. It also allows for an experience your user is used to from other Android apps.

This is pretty much the code used in the Android API demos code. But you get the idea...

ActionBar

It's much easier to keep the Fragment separated from the Activity. Thus decoupling and simplifying. For more code I suggest to see the API demos. They're very useful.

Conclusion


As normal, it really depends on what you want to do. If you have a complex interaction between many different components on your screen, I really feel now that using the suggested Android approaches is easiest. If you just need one little fragment... going with the hook it up yourself approach may be best. But knowing that these are the two option paths may help in making the decision.