Archive Page 2

19
Mar

JazzToolbox REST API Deployed

Today I deployed a major update to my Jazz object model which implements a full REST web interface that is currently accessible through a web browser. Visit http://www.jazztoolbox.com/ for the RDocs – there are plenty of examples at the bottom of the index file, or you can try this immediately:

http://www.jazztoolbox.com/chords.xml

Some fairly complex relationships can be explored in this manner just using your web browser (displaying XML). Note that I still do not have a whole lot of data in here; all the data is just my personal knowledge of Jazz theory. Eventually I will consult a theory reference and develop the database of jazz more thoroughly.

11
Mar

Object-Oriented Approach to Blank Checking/Defaulting

Something I constantly find myself doing is checking to see if a value is blank, and returning something else if it is, otherwise the object itself:

birthday.blank? ? '0000-00-00' : birthday

I started thinking about how I could possibly eliminate the need for all these ternary operators, and came up with this:

class Object
  def or_if_blank(value)
    self.respond_to?(:blank) && self.blank? ? value : self
  end
end

Now we can do something like this:

birthday.or_if_blank('0000-00-00')

You could do something similar for nil, though a more general Ruby idiom is to just use the || operator, which does not work for blank.

On another note, if any of you are used to appending a “if object.respond_to?(:method)” predicate, check out this technique using try.

25
Feb

Introducing JazzToolbox: A computational model of Jazz Theory…

As a (wannabe) Jazz pianist, I’ve always had a strong interest in Jazz theory not only from a practical you-need-this-to-play standpoint but also a theoretical standpoint. At it’s core, music theory is all about a 0 – 11 number system where each number represents a pitch, with the added complication of letters (which makes Eb theoretically different from D#). Everything in music is based on this basic number system: scales and chords are simply sequences of these numbers. Changing key in a scale or chord mathematically is adding some integer to all of the index values and doing modulo 12. Changing modes within a scale simple involves a position shift of the sequence.

Last week I began exploring the idea of developing some sort of computerized object model to capture these musical theory concepts. As a pianist, knowing theory is extremely important and voicing chords can become quite complex, yet there is sanity in the complexity – a harmony of mathematical precision. Today I introduce “Jazz Toolbox”, the future front-end for which will be located at JazzToolbox.com. Right now I have only developed the back-end object model and calculation engine, which is definitely the foundation of the project. I’ve also written up extensive documentation. Here’s an introduction to the project straight out of my README file:

Jazz Toolbox

Jazz Toolbox is an online Jazz utility driven by a full object-relational and REST model of
concepts in Jazz theory, establishing relationships between chords and scales, and much more.
The web interface is a fully Ajaxified Web 2.0 interface towards exploring these relationships and
answering questions about the jazz science. The REST interface exposes the underlying data model
and relationships to other developers wishing to use Jazz Toolbox as a source for their own web
applications.

Architecture Overview

The core of Jazz Toolbox is a full Ruby object model representing concepts of Jazz theory,
distilled to their most basic concepts and architected in a very abstract manner. The system
is data-centric and all “rules” (for example, the tones in a C7 chord) in theory are
self-contained in the database.

All chord/scale/mode/etc. definitions are stored as a mathematical system (sequences of numbers)
which are then used to perform calculations. For example, putting some chord in a different key
is a matter of adding a semitone delta and doing modulo 12.

While there are currently many chord calculators in existance, to my knowledge this project is the
first one that attempts to fully represent the entirety of Jazz theory as a mathmetical/computational
system exposed through an elegant object model.

Full Documentation

I’ve published the full RDocs which are available here and are very complete.

Examples

Any musician/programmer will appreciate these examples; far more are available in the rdocs:

 Chord['Ebmaj7'].notes
 # => ['Eb', 'G', 'Bb', 'D']
 # Or specify key context with chained methods like this...
 Chord['maj7'].in_key_of('Eb').notes

 Chord['Bmaj7#11'].notes
 # => ['B', 'D#', 'F#', 'A#', 'E#']
 # Note E# - Correct theoretic value for this chord, not F

 Chord['Falt'].notes
 Chord['F7b9#9'].notes
 # => ['F', 'A', 'Eb', 'Gb', 'G#', 'C#']

 Scale['Major'].in_key_of('Eb').modes['Dorian'].notes
 # => ['F', 'G', 'Ab', 'Bb', 'C', 'D', 'Eb']

 Scale['Melodic Minor']['Lydian Dominant'].notes
 # => ['F', 'G', 'A', 'B', 'C', 'D', 'Eb']

 Scale['Major']['Dorian'].chords.symbols
 # => ['min7', 'min6']

 Chord['Amin7'].modes.names
 # => ['A Dorian']

 Scale['Major'][4].chords.symbols
 # => ['maj7#11']

This is definately still a work in progress though it has the potential to become very powerful. I have high ambitions for the front-end web interface for this as well as it could become a valuable tool for Jazz musicians and others trying to nagivate the complex roads of jazz…

21
Feb

Create Structured Data in Migrations

Occassionally I’ll decide to create some structured data in a migration by issuing create statements against my model classes. In a project I’m currently working on, I had to do this several levels deep. Rather than using temporary variables to create the sub items and so-on, all in a lexically flat structure, I came up with this simple one-liner:

def self.with(o); yield o; end

Doing this now allows me to issue those creates with nested data as a series of nested blocks, which is looks much better. For example:

with ChordQuality.create(:name => 'Major', :code => 'MAJ') do |q|
  with q.chords.create(:name => 'Major Triad') do |c|
    c.chord_symbols.create(:name => 'maj')
    c.chord_symbols.create(:name => 'M', :case_sensitive => true)
  end
  with q.chords.create(:name => 'Major 7') do |c|
    c.chord_symbols.create(:name => 'maj7')
    c.chord_symbols.create(:name => 'M7', :case_sensitive => true)
    with c.children.create(:name => 'Major 7 #11') do |cc|
      cc.chord_symbols.create(:name => 'maj7#11')
      cc.chord_symbols.create(:name => 'M7#11')
      cc.chord_symbols.create(:name => 'lyd')
      cc.chord_symbols.create(:name => 'lydian')
    end
  end

  with q.chords.create(:name => 'Major 6') do |c|
    c.chord_symbols.create(:name => 'maj6')
    c.chord_symbols.create(:name => 'M6', :case_sensitive => true)
  end
end

Oh, the beauty of Ruby code blocks!

07
Feb

Overlap of Confidence with Static Typing

Since working with Ruby and other dynamic languages, I’ve thought a lot about the differences between statically-typed and dynamically-typed languages and what makes them different. Statically-typed languages guarantee some level of confidence of workability — but this comes at a huge cost of flexibility, and more importantly overlaps with software testing, not making efficient use of the concept of testing.

Software testing can be used to make up for some of the lost confidence resulting from dynamic typing, yet since they must be done regardless, the outcome is suboptimal with static languages – there is an overlap between the confidence generated from static typing and the confidence generated from the test suite. With dynamic languages there is much less overlap: the test suite makes up for the confidence lost from dynamic typing, yet is also there to ensure the software works as expected.

02
Feb

Wrapping Conditional Access with with_scope

ActiveRecord::Base exposes a great way of keeping access control DRY. A very common paradigm in web application development is showing “all” of something to administrators but only only “active” of something to regular users/visitors. In non-ORM PHP you might do something like like this in each SQL statement:

$sql  = "SELECT * FROM entries WHERE type = 1 ";
$sql .= (!$is_admin ? "AND active = 1" : "");

This isn’t a very well-architected approach since this type of tacking onto the SQL string would have to be done in any statement that involved this table, for all of your “actions” like show, edit, and index. It tightly couples this particularly piece of add-on logic to your base code. In Rails we can scope out this functionality to a “scope_access” method in our controller like so:

class EntriesController < ApplicationController
  around_filter :scope_access

  # (Action Methods)

  protected

  def scope_access
    unless current_user && current_user.is_admin?
      Entry.send(:with_scope, :find => {:conditions => 'active = 1'}) do
        yield
      end
    else
      yield
    end
  end
end

We are declaring an around_filter which uses with_scope if the current user is an admin, otherwise it will do so without scope. This is an excellent example of how Rails allows you to architect your code to be very elegant. Note that with_method is now a protected method on ActiveRecord::Base hence our need to use ClassName.send.

The with_scope method is actually useful for many other purposes including running many but similar find statements. Aside from finders, this can actually scope attributes on create and more. I'd highly recommend you check it out in the Rails documentation and start making extensive use of it.

02
Feb

What it takes to appreciate Ruby

Antagonistic attitudes towards Ruby and in particular Ruby on Rails abound. Many web developers feel uneasy about the rise of a strange new framework that is attracting disciples daily. I’ve casually chatted with a few people who have negative attitudes about Ruby and the most striking aspect about everyone I’ve spoken with is that after prodding a bit at their understanding and experience level with Ruby I find they only have a surface-level understanding of Rails and no experience whatsoever. I have not once found someone who was well-versed in both Ruby on Rails (as in.. has actually built an application using it) and in any of the other number of web technologies out there, who was not at the very least appreciative about Rails and optimistic about its future.

What I’m trying to get at here is that to appreciate Ruby you have to know Ruby, and know it well. A surface-level examination of Rails by myself over one year ago left me in the same ignorant state that many Ruby antagonists are at right now, complaining about Ruby’s ability to scale and the restrictive nature the Rails framework involves. Even reading a few chapters out of the Agile book might leave one with this characterization. Yet the more I began to understand Rails and even more importantly the dynamic Ruby programming language, the more positive my attitudes towards Rails were.

It’s interesting that I find this particular understanding imbalance even more widespread and frustrating in economics: to appreciate the free market, you have to understand the free market. So few people truly understand economics and as a result their arguments are ripe with economic fallacies and mischaracterizations of fact. Economists on average believe that the free market works significantly better than non-economists. This isn’t a conspiracy: it’s because they actually understand economics.

There will always be people in any field that attack something they don’t understand for whatever reason. Those making arguments against Rails at least owe it to their opponents to actually understand what they are talking about. I find such is rarely the case.

02
Feb

New SliceHost VPS

Until now I’ve been running a my personal sites and a few other random sites I host on a dedicated box running CentOS 4 and Plesk.  Last week I took the plunge for a SliceHost VPS and decided to configure everything myself and try to squeeze it all on a 256MB slice for $20/month.  Although there isn’t anything specifically about SliceHost that makes it well-suited for Rails hosting (after all, it’s just a Linux VPS – put whatever you want on it), the SliceHost guys are Rails developers and the documentation available on articles.slicehost.com is geared towards Rails production environments.

I wanted to use the switch as a learning experience with setting up a cluster of mongrels behind Apache 2.2, a setup I’ve never tried before.  I’ve used FastCGI with Apache and Nginx proxying to mongrel clusters, but I was looking for a more powerful setup using Apache as the front-end web server.  So I configured Apache 2.2 (with the Debian layout, much different than the “conventional” layout) with mod_proxy_balancer and PHP.  MySQL and Apache were fine-tuned to run with the smallest memory footprint that is practical.  Apache is proxying to a cluster of mongrels hosting BenHughes.name (which will eventually be a larger site) and a new Facebook application I’m currently developing.  

To reduce the memory requirement, and because I find it a better piece of software, I switched this blog and my economics blog to WordPress running as PHP within Apache.  I toyed with the idea of keeping these on Typo and Mephisto, respectively, and running them with just one mongrel instance, but doing so would really eat up my memory on my 256MB slice quickly.  WordPress is pretty nice and has a much larger community of people developing themes.

I also moved my two Subversion repositories over (one private, one public and yet to be used: http://svn.railsgarden.com/).  Previously I was hosting DNS and E-mail which was just a hassle, so I decided to switch all of my domains to Google Apps and host the DNS at SliceHost, maintainable through their management portal. 

I have to say I’ve been exceedingly happy with SliceHost thusfar – their management portal is simple and to-the-point with no BS.  They have dedicated resources and do not oversell.  $20/month for what I’m getting is a pretty darn good deal – it feels good to continue having root on my own Linux system out there in a data center.  Hell for $20/month a VPS is a great way to just fool around with and learn with.  I may get another slice just for that purpose.

06
Jan

Book Review: Advanced Rails Recipes

I’ve owned the original “Rails Recipes” book by Chad Fowler for a while now and it’s packed full of interesting information, but little of it I would consider “advanced”. When I heard a new book by The Pragmatic Programmers called “Advanced Rails Recipes”, meant to be similar in form to the previous book but explaining more advanced techniques, I was very interested. Unfortunately it seems the publish date of this book has been pushed back a few times and it is now mid-March. Luckily it is available in beta PDF form online so last night I took the plunge and decided to buy it. It’s quick to read through and several of the recipes I skipped over because I wasn’t particularly interested, but suffice it to say that there is a lot of good stuff in this book. Some of the content isn’t very original, but some recipes really exceeded my expectations in originality and usefulness.

I won’t give an outline of the book since that’s available online, but let me point out a few very interesting recipes:

  • Using IRB_RC to define useful shortcuts for yourself when navigating around your application with script/console.
  • Efficiently storing model-backed data in constants using class-level ActiveRecord find’s. Example: load all of your states into an Array when the application starts rather than loading them each time a form is displayed that needs to use them.
  • Capistrano multi-environment deployments which allow you to do things like “cap staging deploy” and “cap production deploy”. I’ve been doing this for a while with capistrano-ext but really capistrano-ext isn’t even needed. Every developer using capistrano should be making use of this and a staging environment.
  • Keeping database.yml and other files out of Subversion using a Capistrano after filter when deploying apps.
  • Keeping certain data outside the multiple-release capistrano paradigm by symbolic linking folders within public to subdirectories in shared. This is perfect for establishing a place to upload via FTP without requiring someone to go through the SVN commit and capistrano deploy route. I’ve also used this before but the mechanism described in the book is more elegant.
  • SQL query tracing – finding out where queries are being run and what is going on behind the scenes. Could come in useful when debugging a nasty situation.
  • Using a master/slave database configuration for large applications with Rick Olsen’s masochism plugin.
  • My favorite: Handling complex forms spanning multiple models each with possible one-to-many or many-to-many relationships using the “presenter” pattern. Essentially this allows you to have a layer of design abstraction between the controller and the models whereby you can design a “presenter” which acts as as “manager” of multiple model objects meant to be displayed using the same form. Difficult to explain in full here (buy the book!) but this sounds like a very elegant solution for more data-complex applications. I may do some refactoring with Rarenewspapers.com’s back-end to use this pattern.

The book is still in beta form and there are definitely errors. Hopefully some more recipes will also be added (I’m hungry for more!) before the book is released, but ultimately the knowledge presented in Advanced Rails recipes will be very insightful for professional Rails developers.

28
Dec

New MacBook!

This Christmas my parents got me an Apple giftcard which I promptly used to buy a new 2.2Ghz MacBook. With next day shipping, I had it in my hands at 10:30 yesterday morning (27th) – pretty fast!

All day yesterday I was setting stuff up (and to some extent today) and I think I’ve finally got everything moved over. I also invested in 4 gigs of memory from Newegg for only $110. Because of the small screen, I’ve found Leopard Spaces invaluable. I still have quite a bit to learn, but I’m glad I made the switch. I can finally start developing with TextMate.

My New MacBook





  • Ben Hughes

    I'm a freelance developer working with Ruby and other modern tools to build web applications, based currently out of Rochester, NY. I love to learn about new technologies and am always trying to achieve elegance and beauty through code.

    When I'm not writing software, I like to play tennis, dabble in jazz piano, and ponder economics. I'm a big fan of: world travel and cultures, jazz music, Korean food, coffee, and having interesting conversations.

  • Recommend Me
July 2010
M T W T F S S
« Jan    
 1234
567891011
12131415161718
19202122232425
262728293031