Adventures in code

First Ruby Motion App

I recently dived into rubymotion head first and since there is a definite lack of quality tutorials out there I decided to outline my first ruby motion project here in the hopes it will help someone. The goal of the project was simple, display hello world to the user. My first challenge was setting up the app delicate. The following code is the very generic setup the is in almost every ruby motion application.

1
2
3
4
5
6
def application(application,didFinishLaunchingWithOptions:launchOptions)
    @window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
    @window.rootViewController = HomeController.new
    @window.makeKeyAndVisible
    true
  end

This will initialize the window and set the initial controller to the homeController. Then in order for this to work I needed to define the HomeController, so in the controllers/home_controller.rb I define my controller.

1
2
3
4
5
6
7
class HomeController < UIViewController
  def loadView
    self.view = UIView.alloc.init
  end
  def viewDidLoad
  end
end

This defines the homecontroller and initializes the view local variable. This variable will be used to add UI elements to the view. So next is adding a UILabel to this view using the following code

1
2
3
label = UILabel.alloc.initWithFrame([[15,100],[140,70]])
label.text = "helloworld"
view.addSubview(label)

This code initializes a new UILabel in the given frame, adds the text, and finally adds it to the view initialized earlier. And thats it! We now have our generic helloworld application next thing to do: put it on the app store and make 1 million dollars.

5 Cool Things Ruby Does

5) collect/inject/select/each…

The easie of which ruby allow me to iterate over an collection without having to worry about the mundane details is amazing. Need to find the total of an array of prices? Here is inject to help!

1
2
3
4
 [5.32,7.65,8.94].inject do |total,price|
     total +=price
   end
 => 21.91

4) blocks / yield

The power of ruby is staggering and it starts at the block. Lets take an example I used the other day. I need to highlight certain output so in order to remain DRY I created this function.

1
2
3
4
5
6
7
8
9
10
11
12
 def display_all
   puts "================"
   yield
   puts "================"
   end
 => nil
 display_all do
     puts "hello world"
   end
================
hello world
================

3) send

Send allows you to call a method from the name of the method. This allows you to be flexible with your code and in a lot of places remain dry. Lets consider you have to initialize an object and set five fields money,age,happiness,height and weight all to 9001 we could do it like this.

1
2
3
4
  jack = Person.new
  jack.money = 0
  jack.age = 0
  ...

Or we could save ourselves some typing and use our send method

1
2
3
4
5
6
[:money=,:age=,:happiness=,:height= ,:weight=].each do |e|
      jack.send(e,9001)
   end
 => [:money=, :age=, :happiness=, :height=, :weight=]
 jack.age
 => 9001

note: This become incredibly powerful (and cool) when combined with introspection but thats another whole other post.

2) define_method

Allowing you to define instance methods of a class on the fly. This has amazing power in allowing you to refactor code and create some cool tools. For example we coulde create our own attr_accessor function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Person
   def self.our_own_attr_accessor(*method_names)
    method_names.each do |meth|
      define_method meth do
        instance_variable_get "@#{meth}"
      end
      define_method "#{meth}=" do |arg|
        instance_variable_set "@#{meth}",arg
      end
    end
  end
  our_own_attr_accessor :name, :age
end

 jack = Person.new
 jack.name = "jack"
 jack.name
 => "jack"
 jack.age = 97
 jack.age
 => 97

There is a lot going on here. The define_method method gets called twice once to create a method named name and once to create a method named name=. These then use some methods build into the Object class to act as a getter and setter.

1) method_missing

This method gets called when a method is undefined and could allow you to define it or provide a custom response. So if we wanted to we could create a very forgiving interface for an object.

1
2
3
4
5
6
7
8
9
  class Computers
  def method_missing(*args)
    puts "I can't do that jim"
    true
  end
  end
1.9.3p286 :046 > c.car
I can't do that jim
 => true

These are just 5 things that when I first ran into them I had one of those “ahh thats cool” moments which made me <3 ruby.

ActiveRecord Without Rails

TL;DR, Activerecord without rails is a headache, but it’s also a good exercise if you are struggling to find the line between activerecord and rails magic.

As developers we break down problems into smaller manageable pieces and this approach works well when learning a new framework. When first confronting rails I decided to break up the problem and first learn activerecord first. The project I embarked on was to scrape down some information that would serve as the seed data for a future rails application and I decided to do this in a non rails environment using the gem Activerecord.

The first thing I did was design some barebone structure of the classes. One of the objects I wanted to store for this scrape was a product which would represent something with a name and a price.

1
2
3
class Product < ActiveRecord::Base
  attr_accessible :name,:price
end

Next I need to set up the database for ActiveRecord to use. To do this I would need a migration. So to examine a basic migration I started by making a new rails project and generating an empty migration.

1
2
3
ralis new rails_playground
cd rails_playground
rails g migration empty
1
2
3
4
class Empty < ActiveRecord::Migration
  def change
  end
end

This is just a ruby object that inherits from ActiveRecord::Migration so in my project I created a new file and set up my first migration.

1
2
3
4
5
6
7
8
class CreateProductTable < ActiveRecord::Migration
  def change
    create_table :products do |i|
      i.string :name
      i.decimal :price
    end
  end
end

This simple migration just creates a new table products. The next step was to find out how to run a migration without the handy rake task. This turned out to be the hardest part of the project since information on ActiveRecord that is not tied to rails is scarce and in the end I decided to drop into irb…

1
2
3
4
5
6
7
8
9
10
11
require active_record
class CreateProductTable < ActiveRecord::Migration
  def change
    create_table :products do |i|
      i.string :name
      i.decimal :price
    end
  end
end
migration = CreateProductTable.new
migration.methods.sort

Here we have a large list of method this migration object defines. Looking at this list the migrate method jumps out at me for a potential way to run a migration so next I tried this method.

1
2
3
4
5
CreateProductTable.new.migrate
ArgumentError: wrong number of arguments (0 for 1)
  from /Users/jacknolan/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.8/lib/active_record/migration.rb:380:in `migrate'
  from (irb):11
  from /Users/jacknolan/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'

Lets try this with an argument, how about the method it should use?

1
2
3
4
5
6
CreateProductTable.new.migrate :change
ActiveRecord::ConnectionNotEstablished: ActiveRecord::ConnectionNotEstablished
  from /Users/jacknolan/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.8/lib/active_record/connection_adapters/abstract/connection_specification.rb:166:in `connection_pool'
  from /Users/jacknolan/.rvm/gems/ruby-1.9.3-p286/gems/activerecord-3.2.8/lib/active_record/migration.rb:389:in `migrate'
  from (irb):12
  from /Users/jacknolan/.rvm/rubies/ruby-1.9.3-p286/bin/irb:16:in `<main>'

Thats promising lets look into how to make a connection to a database! After looking around google for awhile I found this code:

1
2
3
4
ActiveRecord::Base.establish_connection(
  :adapter => "sqlite3",
  :database => development.sqlite3"
  )

Just adding this at the top of the migration file, not the best solution but this is just exploring. Then running that file…

1
2
3
ruby 001_create_Product_table.rb
-- create_table(:products)
   -> 0.0196s

Finally playing around with the Product class either in irb or just in the file…

1
2
3
4
 Product.create(:name=>"steel",:price=>7.3)
=> #<Product id: 1, name: "steal", price: 7.3> 
 Product.all
=> #[<Product id: 1, name: "steal", price: 7.3>] 

Thats it with the class made saving the information to the database was as simple as: Product.create(:name=>name, :price=>7.6)

Doing this project helped me to understand the line between active record and rails. Also was really beneficial in learning MVC architecture since I just created a rails model independent of any magic!

Classroom vs. Bedroom vs. Lecture Hall

At one time or another I have experienced all major ways of learning computer science: self study, university classes, and the group-oriented classroom. This gives me an unique ability to examine the pros and cons of each style.

Lecture Hall aka University

Lecture hall

No one is a stranger to the classic college formula these days: lecture on monday, test on friday. While University teaching works to educate a large number of students in a (relatively) short time, it does have a few drawbacks.

Cons:

  1. Large class sizes
    • hard to reach professors
    • little to no sense of ‘comradery’
    • slows down the class
    • hard for professors to give meaningful feedback
  2. Emphasis on tests
    • completely academic
      • no real world analogies
    • leads to a ‘get an A’ mentality rather than a ‘learn this shit’ mentality
  3. Bureaucracy
    • hard for professors to change class content
    • professors tend to burn out from dealing with bureaucracy
    • leads to stagnation
    • forms, hoops, and permissions for every decision
  4. Cost
    • average cost of four year degree: $21,657
    • this number increases every year
    • takes four years of your life
  5. Focused on theory
    • great foundations
    • does not really prepare you to develop

Pros:

  1. Degree
    • an accredited university provides formal proof of completion
    • required by some organisations
    • most provide an excellent foundation in theory
  2. College experience
    • a large community leads to networking opportunites
    • achieve a working knowledge in a variety of subjects

To conclude:

Overall I dislike the current way computer science is taught in universities. In the current environment it is almost impossible for professors to teach full time and keep up with the changing field of computer science. This forces a greater emphasis on theory which leads to graduates that can explain the O(n) of an algorithm they outlined, but have no idea how to launch a web server or an application.

Ruby Under the Hood

After completing the computer architecture course at the University of Minnesota I find myself wondering about how things work at a low level. Now at the flatiron school we are covering ruby, and I find myself wondering how the memory allocation works for ruby objects. After a bit of searching I found this slide deckthat contained a very clear explanation of the behind the scenes workings of ruby; While paying special attention to memory allocation and garbage collection.

These slides reminded me of my final project in the architecture class where I implemented a rudimentary malloc of my own which, it turns out, works much like the allocation of memory for classes works in ruby. I wonder how hard it would be to implement this method of garbage collection on top of it… hopefully nothing good on tv next weekend!

Job Indexing

Before I started at flatiron school this semester I worked for JobDig writing parsers and spiders to index jobs. It was good work and a great first experience in the tech industry. However, there were a few common things I ran into on a day to day bases that I thought I would share to show potential employers some good practices when listing jobs.

1) Use concise html and css. Since some poor soul out there (me) may have to wade through your html and css consider consolidating your html and css both to organize your site better but to help them index your jobs. Using constant naming schemes can save them time and get your openings out to the community.

2) Don’t hide you employment page. Seriously, I have had to hack at the url in order to get to an employment page due to broken links or hidden job listings. By keeping it visible you make it easier for potential hires to apply for the job!

3) Keep it simple. Same as number two, if you over complicate your application process the great candidates and job listings sites are going to skip your site which means less candidates. If you lack the time consider using an third party ( like Taleo!) to list your jobs in a proven organised way.

It is in a company’s interest to have as many people as possible see their job listings. More views means more applications, which means more choice in candidates which leads to better hires! By keeping these tips in mind when designing your sites employment section you can help your potential hires find you quickly and efficiently.