Bauble, Bauble... 52

Posted by Uncle Bob Sun, 20 Jul 2008 20:42:29 GMT

In Ruby, I hate require statements that look like this:

require File.dirname(__FILE__)+"myComponent/component.rb"

So I decided to do something about it.

This all started when my Son, Micah, told me about his Limelight project. Limelight is a jruby/swing GUI framework. If you want to build a fancy GUI in Ruby, consider this tool.

I have neither the time nor inclination to write a framework like this; but my curiosity was piqued. So in order to see what it was like to do Swing in JRuby I spent a few hours cobbling together an implementation of Langton’s Ant. This turned out to be quite simple.

The result, however, was a mess. There was swing code mixed up with “ant” code, in the classic GUI/Business-rule goulash that we “clean-coders” hate so much. Despite the fact that this was throw-away code, I could not leave it in that state – the moral outrage was just too great. So I spent some more time separating the program into two modules.

The first module knew all about Langton’s ant, but nothing about Swing. The second module was a tiny framework for implementing cellular automata in Swing. (Here are all the files).

I was quite happy with the separation, but did not like the horrible require statements that I had to use. The cellular_automaton component had two classes, in two separate files. In order to get the require right, I had to either use absolute directory paths, or the horrible File.dirname(__FILE__)... structure.

What I wanted was for cellular_automaton to behave like a gem. But I didn’t want to make it into a gem. Gem’s are kind of “heavy” for a dumb little thing like “cellular_automaton”.

So I created a module named “Bauble” which gave me some gem-like behaviors. Here it is:


module Bauble
  def self.use(bauble)
    bauble_name = File.basename(bauble)
    ensure_in_path "#{bauble}/lib" 
    require bauble_name
  end

  def self.ensure_in_path(path)
    $LOAD_PATH << path unless $LOAD_PATH.include? path
  end
end

This is no great shakes, but it solved my problem. Now, in my langton’s ant program all I need to do is this:


require 'bauble'
Bauble.use('../cellular_automaton')

All the ugly requires are gone.

I’m thinking about turning Bauble into a rubyforge project, and making a publicly available gem out of it in order to give folks a standard way to avoid those horrible __FILE__ requires. I think there are several other utilities that could be placed in Bauble such as require_relative etc.

Anyway, what do you think?

Comments

Leave a response

  1. Avatar
    Bil Kleb about 3 hours later:
    If you used Hoe’s sow command, e.g.,
      $ sow bauble
    
    you may have a gem before you might expect.
      $  sudo gem install hoe
    
  2. Avatar
    Jim Weirich about 22 hours later:

    I’ve never been a fan of the require/FILE idiom either. However, I also don’t like using paths like ”../cellular_automaton” either … mainly because (if I’ve read you code right), the location of the cellular_automaton directory is calculated based on your current directory. That’s fine for running in the project’s directory, but what if I want to run it from my home directory. IMHO, refs to ”../dir” do not belong in code.

    Here’s what I do. I project is structured like this:

    • project_dir
      • lib
        • langton
          • cellular_automaton
          • ui

    All requires would be of the form: require ‘langton/cellular_automation/whatever’. This only requires a -Ilib option on any manually typed ruby command (ie. all refs are relative to ‘lib’). The standard rake test task understands this and will add a -Ilib option automatially). This removes the need for any FILE relative requires.

    And the truly lazy can put ‘lib’ into their RUBYLIB environment variable.

    This scales nicely to installed libraries, which would either copy the ‘lib/*’ to a directory listed in $LOAD_PATH, or as a GEM which would add the projects ‘lib’ directory to $LOAD_PATH.

  3. Avatar
    Micah Martin about 23 hours later:

    Using Bauble.use instead of require would be a bit unorthodox. But you could get used to it.

    I imagine you could monkey patch Kernel.require to do exactly what Bauble is doing. That’s a bit scary though.

    I agree that require statements can get nutty. I blogged about Ruby require guidlines a while back. In a nut shell, I recommend using File.dirname(__FILE__) one time in your code base to set up a search path, and never use it again.

  4. Avatar
    Unclebob 1 day later:

    The problem I am trying to solve is when I have many different components that I want to import into my app and I don’t want to turn them all into gems.

  5. Avatar
    craigslist reviews over 2 years later:

    Here the info is interesting and we all learn from it… GUI is always very useful… I like your blog and i must visit it next time… These kind of information is not provided by every blog… great Idea… http://yourlistings.org

  6. Avatar
    Alina's List over 2 years later:

    I do agree that such type of require statements are really irritating statements.But if we don’t include these statements in our code,i think we would have to write a couple of lines to present this single line.And the code will be not a precise code but in fact it will be a bulky code.

  7. Avatar
    dupont lighter over 2 years later:

    dupont lighter, dupont lighters, st dupont lighter, s.t. dupont lighters. As classical music evolved, distinctive characteristics developed. Changes in form were seen along with changes in phrase structure.

  8. Avatar
    dupont lighter over 2 years later:

    dupont lighter, dupont lighters, st dupont lighter, s.t. dupont lighters. As classical music evolved, distinctive characteristics developed. Changes in form were seen along with changes in phrase structure.

  9. Avatar
    gucci wallet over 2 years later:

    gucci wallet, gucci wallets, mens gucci wallet, women gucci wallet.
    Bedrooms are a place for rest and relaxation. The simplicity of modern bedroom designs creates a calmness that makes that feeling even more prevalent, There are funny and strange bedrooms with different shapes .

  10. Avatar
    Hermes belt over 2 years later:

    Hermes belts, Elegant Hermes belt, Fashion Hermes belts for men, Hermes mens belt.
    The earpiece also works with most phones that allow Bluetooth connections, although Earloomz suggests users check their phone manual to be sure.

  11. Avatar
    Men’s belts over 2 years later:

    Men’s belts, LV men’s belts, Fashionable Gucci men’s belts, Attractive style Hermes men’s belts.
    Physical fitness was seen as important in the stylish thirties and in various forms was popular across Europe especially in Germany and Austria.

  12. Avatar
    armani belt over 2 years later:

    armani belt, armani belts, armani belts for men, armani mens belt. Adjusting your diet to a healthier way of eating is a way to lose belly fat without dieting that works for many people. Instead of putting yourself on a restrictive and often unsafe diet, you can try adjusting the way you eat. Instead of five cookies, maybe have one small slice of low fat angel food cake. Simple exchanges like that will provide you with a way of eating that will keep you healthy your entire life.

  13. Avatar
    designer belts over 2 years later:

    Men’s belts, LV men’s belts, Fashionable Gucci men’s belts, Attractive style Hermes men’s belts.
    So long, old world who can, with its non-self, and it could be longevity. Is a sage, putting himself in and outside the body and the body exist. Non their selfless not? Which gives it private.

    —————————————————————————————————————————————————

    designer belt, designer belts, designer Mens belts, designer belts for men. mens omega watches, mens omega watch.
    Physical fitness was seen as important in the stylish thirties and in various forms was popular across Europe especially in Germany and Austria.

  14. Avatar
    waist belts over 2 years later:

    studded belt, studded belts, studded Mens belts, studded belts for men. rolex watches for sale, rolex watch for sale. gucci mens wallets, gucci wallets for men, gucci wallets, gucci mens wallet.
    As classical music evolved, distinctive characteristics developed. Changes in form were seen along with changes in phrase structure.

    —————————————————————————————————————————————————

    waist belt, waist belts, waist Mens belts, waist belts for men. vintage rolex watches, vintage rolex watch.
    Although basing a restart on changes to the script file may seem better, it also has its own problems because of the multi process nature of Apache and because the initial Apache process receiving the request would generally be running as a different user to the application. This process therefore may not have the privileges necessary to send a signal to a application process to get it to shutdown and restart before a request is sent to it.

  15. Avatar
    pandora uk over 2 years later:

    The first module knew all about Langton’s ant, but nothing about Swing. The second module was a tiny framework for implementing cellular automata in Swing.

  16. Avatar
    http://www.blacktowhiteiphone4.com over 2 years later:

    Merry Christmas! What’s your most desire present you want to get? Hmm maybe you and me have one thing in commend, the white iphone 4.

  17. Avatar
    dvdsoft over 2 years later:

    With the right tool, you can easily burn mp4 to dvd and itunes to dvd. Also, you can use drm removal tool to remove drm protection from itunes, zune, amazon legally. wmv to dvd, mov to dvd, mp4 to dvd, itunes to dvd

  18. Avatar
    US Criminal Record over 2 years later:

    The first module knew all about Langton’s ant, but nothing about Swing.

  19. Avatar
    Tenant Screening over 3 years later:

    I was quite happy with the separation, but did not like the horrible require statements that I had to use. The cellular_automaton component had two classes, in two separate files.

  20. Avatar
    Criminal Records over 3 years later:

    The standard rake test task understands this and will add a -Ilib option automatially). This removes the need for any FILE relative requires.

  21. Avatar
    SEO Firm India over 3 years later:

    Thank you for the sensible critique. Me & my neighbor were preparing to do some research about that. We got a good book on that matter from our local library and most books where not as influential as your information. I am very glad to see such information which I was searching for a long time.This made very glad

  22. Avatar
    donna-borsa over 3 years later:

    your blog is so good`

  23. Avatar
    okey oyunu oyna over 3 years later:

    thanks uncle bob. I follow you

    internette görüntülü olarak okey oyunu oyna, gerçek kisilerle tanis, turnuva heyecanini yasa.

  24. Avatar
    high power leds over 3 years later:

    I just wanted to say that I found your blog via Google and I am glad I did. Keep up the good work

  25. Avatar
    Hermes belt over 3 years later:

    Hermes belt store offers high quality and cheap designer belts, please have a look.

  26. Avatar
    Basil over 3 years later:

    Nice code indeed! kyivstar blog kyivstar subscribers carsnet blog mechanic tool sets partners unit

  27. Avatar
    San Diego Criminal Law Firm over 3 years later:

    This is a really interesting article, I find your blog in google and use translate tool to understand the topic, I hope that publish more articles like this in the future, thanks.

  28. Avatar
    http://www.runningshoes2usa.com/ over 3 years later:

    After again period of time, discovered that this flea has not hit this cover again, but the freedom beats under the cover. one day later, the laboratory technician starts this cover to pick off gently, the flea did not know that the cover had already removed, it continues in the original this altitude to jump.

  29. Avatar
    what is seo over 3 years later:

    ??????? ?????? ? ?????????

  30. Avatar
    ysbearing over 3 years later:

    Slewing bearing called slewing ring bearings, is a comprehensive load to bear a large bearing, can bear large axial, radial load and overturning moment.

  31. Avatar
    borse louis vuitton outlet over 3 years later:

    Another great characteristic of Tiffany and Co jewelry is that it is rock-solid silver and any buyer can easily feel the weight in their hands. Replicas that are still not genuine copies may be quite hollow and light in weight. In the jewelry markets, it is difficult tiffany and co rings to find jewelry links that are soldered together instead of being squeezed closer to fit such as in bracelets. Tiffany’s jewelry carries this feature that is a clear guiding light for buyers who should not easily detect the start and end points of every link.

  32. Avatar
    grad school personal statement over 3 years later:

    Glad i came across your post, very informative indeed.

  33. Avatar
    mudre izreke over 3 years later:

    I agree with your conclusions and will eagerly look forward to your next updates. Saying cheers will not just be sufficient, for the wonderful clarity in your writing.

  34. Avatar
    backup iphone sms over 3 years later:

    If you have neither the time nor inclination to write a framework like that. You should be able to clean the code.

  35. Avatar
    ralph lauren over 4 years later:

    Hiver n’est pas terminée, mais les grandes marques ont commencé le début de ce printemps, Ralph Lauren est l’un d’entre eux. Marque sous le soleil printanier et séries allé à los angeles plage en Californie, Etats-Unis, avec le thème de los angeles côte de los angeles Californie, los angeles série de femmes répartis en Californie du Nord avec not layout bohème et setting rétro, comme theme flower, robe en mousseline de soie corps mince et ainsi de range.http://www.vetementpoloralphlauren2012.net

  36. Avatar
    Babolat Rackets over 4 years later:

    Organizers as well as owners of this particular championship have maintained this particular tournament in order to promote tennis within UAE.

  37. Avatar
    Backup iPhone SMS over 4 years later:

    Backup iPhone SMS to computer and you can import the contacts file to email address book or other mobile phone. good luck.

  38. Avatar
    Prada Sale over 4 years later:

    See you blog on yahoo.and I have searched this kinds of articles for days.Thanks for your nice great,I really like it.

  39. Avatar
    Cheap Power Tools over 4 years later:

    You must be validate this account “I take them I am exhausted during the day.”

  40. Avatar
    Makita Repair Parts over 4 years later:

    We will survive this “This is why the female lion is only suitable for mature men, mature men, they know they occasionally fleeting unease, they will make their own arrangements without the lion women worry about their own affairs, when the female lion is a little bird.”

  41. Avatar
    M4V to MOV over 4 years later:

    Glad i came across your post, very informative indeed. convert m4v to mov, drm m4v movie to mov for windows os and mac os

  42. Avatar
    md5 calculator over 4 years later:

    This website is providing the some topics are visible in this blog and the great technology in this blog. I am very much satisfied by the info in this blog. Thank you very much for providing the great info in this blog.

  43. Avatar
    birkin hermes over 4 years later:

    How much is too much to spend on a designer hand bag? An Hermes’ Birkin just sold at auction for more than $80,000?

  44. Avatar
    birkin hermes over 4 years later:

    How much is too much to spend on a designer hand bag? An Hermes’ Birkin just sold at auction for more than $80,000?

  45. Avatar
    cheap air shoes over 4 years later:

    architectonics is now the appetence by everybody. How to escape from the exhausted of the ultraviolet can look for their most favorite outfit from the web or radiation below the affronted sun

  46. Avatar
    air mens shoes over 4 years later:

    important is acclimation for the ladies. Personalized may sometimes an accomplish you in focus. Your able allocation of your face are able below the, appropriately it reflect a aftereffect of

  47. Avatar
    shop cosplay over 4 years later:

    http://www.outfitscosplay.com/cosplay-catalog/beelzebub-cosplay Deluxe Beelzebub Cosplay Costumes for Sale.Find your favorite characters and cosplay outfits from all the popular anime and games.

  48. Avatar
    Pc expert over 4 years later:

    I think this is the 2nd article for the lime project.Like the 1st one this article has also given me some useful codes with may help me in my upcoming project.Pc expert. hope to get more tips.

  49. Avatar
    cheap snapback hats over 4 years later:

    feel great but they aswell the analysis calefaction in your able to accumulate you warm. The adjustment of fur attainable is about limitless, includes mink, ermine for those of us who access

  50. Avatar
    cheap snapbacks free shipping over 4 years later:

    occasions when you may be attending the games from your favorite team, it is certain that what you would should get is the complete group of outfit that may add the and also the However,

  51. Avatar
    air mens shoes over 4 years later:

    alive on below than dollars a day How can they ascribe all individuals to stick to a budget capricious and male, boyish and age-old to assure themselves from HIV To save the lives of over

  52. Avatar
    cheap air shoes over 4 years later:

    who die ceremony year in childbirth What will it crop to actualization boyish bodies alive in abasement that they acquire a anemic in development as able as a accomplishment for the future

Comments