CommandLineMac.com RSS http://www.commandlinemac.com The Power of the Prompt admin@commandlinemac.com admin@commandlinemac.com Copyright 2008 CommandLineMac GeekLog Thu, 10 Jul 2008 18:37:14 -0400 en-gb Date validation in Ruby using the Date object http://www.commandlinemac.com/article.php/200807091821123 http://www.commandlinemac.com/article.php/200807091821123 Wed, 09 Jul 2008 18:21:00 -0400 http://www.commandlinemac.com/article.php/200807091821123#comments News Ruby has a date library to help you manage and manipulate dates. The date library provides Date and Date/Time objects that can be used to validate dates. In addition to straight Ruby, this helps work around a particularly nasty problem in version 1.x scaffolding date fields created by Rails. <h4>The Date object</h4><p>To use the date library, add this line near the top of your Ruby program:<br><br><code>require 'date'</code></p><p>The date library provide the Date object and the DateTime object, which adds time attributes to the Date object. To create a new Date object, pass the year, month, and day to the new Date constructor:<br><br><code>mydate = Date.new(2008, 7, 11)</code></p><p>To get the current date, use the Date.now method. You can access different attributes of a date object like this:<br><br><code>mydate.year<br>mydate.month<br>mydate.day</code></p><p>Converting a date object to a string returns a "YYYY-MM-DD" format. For example:<br><br><code>mydate.to_s<br>"2008-07-11"<br></code></p><h4>A simple validate function</h4><p>One way to test for a valid date is to try to create a Date object. If the object is created, the date is valid, and if not, the date is invalid. Here is a function that accepts year, month, and day, then returns true if the date is valid and false if the date is invalid.<br><pre> def test_date(yyyy, mm, dd) begin @mydate = Date.new(yyyy, mm, dd) return true rescue ArgumentError return false end end</pre></p><p>The creation of the date object is wrapped in a begin...rescue...end block so that the error can be trapped if the date is invalid. Ruby throws an ArgumentError if the date is invalid and in that case, the function returns false. This version uses an instance variable (@mydate) because I wrote it to be used in a Rails application.</p><h4>The nasty date problem in 1.x Rails scaffolding</h4><p>In version 1.x of Rails scaffolding, date fields in the edit view are generated with three drop down boxes, one for the year, one for the month, and one for the day. However, you are free to select invalid month/day combinations like February 30 and November 31. When these parameters are passed to the Rails update function in a scaffolding generated controller, it fails.</p><p>The crude solution I used to work around it was to edit the date prior to the attempt to save the record. In this case, the view sends the year to the controller in the dob(1i) field, the month in dob(2i), and the day in dob(3i). I convert them to integers, then call the function above to validate the date. If the date is invalid, I set a flash message and return to the edit screen.<br><pre> # date validation code @allparms = params[:dependent] @yyyy = @allparms["dob(1i)"].to_i @mm = @allparms["dob(2i)"].to_i @dd = @allparms["dob(3i)"].to_i if test_date(@yyyy, @mm, @dd) == false flash[:error] = "Invalid date " + @mm.to_s + "/" + @dd.to_s + "/" + @yyyy.to_s redirect_to :action =&gt; 'edit', :id =&gt; params[:id] return end</pre></p></p>It seems like this rather basic problem would have been worked out in the Rails scaffolding, but it wasn't. I haven't tested Rails 2.0 scaffolding to see if it has similar issues. Other people have come up with more comprehensive solutions, like the <a href="http://www.methods.co.nz/rails_date_kit/rails_date_kit.html">Rails date kit</a>. Take a look at something like that if you want more than a quick and dirty solution.</p> http://www.commandlinemac.com/trackback.php/200807091821123 Useful Mac OS X Terminal Commands http://www.commandlinemac.com/article.php/2008062720334588 http://www.commandlinemac.com/article.php/2008062720334588 Fri, 27 Jun 2008 20:33:00 -0400 http://www.commandlinemac.com/article.php/2008062720334588#comments Symlink Art of Geek has an <a href="http://artofgeek.com/2006/09/22/useful-mac-os-x-terminal-commands/">interesting list of commands</a> to handle unusual problems. http://www.commandlinemac.com/trackback.php/2008062720334588 Beginning a Rails app -- for beginners http://www.commandlinemac.com/article.php/20080604213612724 http://www.commandlinemac.com/article.php/20080604213612724 Mon, 09 Jun 2008 09:36:00 -0400 http://www.commandlinemac.com/article.php/20080604213612724#comments Tips <p>After some trial and error, I got my first significant Ruby on Rails application off the ground. By significant, I mean a dozen related tables, about 20 controllers, and some tricky business logic. I had been exploring Rails for a while and created a few toy applications, but hammering this one out still presented a challenge. </p></p>If you are used to programming CGI, PHP, or any application not built on a Model-View-Controller (MVC) framework, the learning curve is steep. While I can't offer up best practices -- I still have too much to learn -- I can offer up how-the-hell-do-I-get-started practices. For my own benefit, I created a list of steps to ease the pain of getting started.</p> <h4>Don't start here</h4><p>As I mentioned, unless you are coming from another MVC framework, the learning curve is kind of steep. Rails has lots of nooks and crannies, lots of helpers and shortcuts that are not obvious at first. So, even though this is a beginning Rails article, it is not a good place to start learning about Rails. I suggest starting with a good book.</p><p>The three books I always have at hand when working in Rails are:<ul type="square"> <li> Programming Ruby: The Pragmatic Programmers' Guide (pickaxe)</li> <li>Agile Web Development with Rails</li> <li>Rails Cookbook</li></ul></p><p>Also, I spent no time telling you <a href="http://lowendmac.com/ed/winston/08kw/rails-posgresql-leopard.html">how to install or set up Rails on your system</a>. There are many places to find such information, and if you are running a Mac, you already have Rails installed, though you may need to set up your database.</p><h4>Four terminals at Rails central</h4><p>I do my text editing with vim (and sometimes nano), performing all work in the Terminal. Textmate and other GUI editors are popular but I prefer to stay in the Terminal. I have found that 4 terminal windows (or tabs) is ideal for working on a Rails application. That's 4 terminals for each Rails application, so if I was going to work on two at the same time, (unlikely), I would open 8.</p><p>I keep the Terminals ordered left to right and dedicate the first to working on Models, the next one for Views, the next one for Controllers, and the fourth one for performing other tasks such as debugging, reviewing logs, running scripts, etc. Keeping them in MVC order helps me stay organized while working and lets me switch between related views and controllers quickly.</p><p>Of course, I also have a browser window open to test changes as I go.</p><h4>Start here</h4><p>Keep in mind, these are not rules, just basic guidelines that can help you approach a new project.</p><p><ol> <li>create the app structure with "rails appname", this command generates the directory structure for the application and all the configuration files</li> <li>create the database and tables (outside of rails), this is not the "rails" way, using migrations, but I prefer to do create/modify my database outside of rails</li> <li>configure /config/database.yml with database details</li> <li>create models, one per database table in app/models/</li> <li>add validate helpers and validate methods to models in app/models/</li> <li>create initial controllers/views using scaffolding with "ruby script/generate scaffold <i>Model-name</i>";run once for each table/model using the singular form of the table name for the controller.(The model name is capitalized and singular).</li> <li>add business logic to a controller and set instance variables with data that will be needed in the view</li> <li>customize the default template in /app/views/layouts/. Layouts are used to hold common HTML andembedded ruby such as headers and footers for your pages. Usually, there is one layout per controller.</li> <li>fill in the views (often rhtml files), one for each method in the controller. Views and layouts control the presentation.</li> <li>repeat each step above starting with step 6 (the scaffolding step) for each table/model in your application, you can come back and add or change models later</li> <li>create new controllers not related to any models with "ruby script/generate controller <i>Controller-name</i>" and add methods and views as needed</li> <li>edit config/routes.rb to set the default URL for the application, rename public/index.html to index.html.old,<br>e.g. map.connect '', :controller =&gt; "main", :action =&gt; "list"<br>it must be the first map in the routes file.</li></ol></p><p>For pure data entry forms, create an empty controller method with a corresponding view. The view will contain the form and call a different method to accept the data and display the results (in yet another view).</p><p>If authentication is needed, use a "before_filter" at the top of each controller to handle logins and set session data.</p><p>In Rails version prior to 2.0, the scaffold script generates non-RESTful code, while in 2.0 and later, it generates RESTful code. This is a concern if you were used to the way Rails worked before 2.0. I am not sure RESTful is really better, but either way it can be confusing if you upgrade to Rails 2.0 in the middle of developing an application and find that scaffolding no longer works the same way.</p><h4>Rails is flexible</h4><p>One of nice things about Rails is that it is flexible. You can use Rails helpers when constructing your views and web forms, or you can code them using standard HTML. If I was not comfortable using a particular form helper or could not get the syntax just right, I fell back to coding it in regular HTML. Rails had no problems merging form helpers and regular HTML in the same form within a view. In many parts of Rails, it is not all or nothing. You can use all, some, or none of the shortcuts.</p><p>The ease of modifying applications is another strength of Rails. It is relatively easy to add new functionality, tables, or features. You don't have to figure out everything before you start. It is also easy to rewire your application if you don't like the way it flows between screens or the way the pages are linked together.</p><h4>Testing</h4><p>I think the official best practice to test a Rails app is to write test scripts that assert conditions and report problems found. I haven't used test scripts yet, my skills are not advanced enough. Up to now, I have relied on three other techniques.</p><p>The first is using the "script/debugger" to stop my application at certain points so I can display the values of objects and variables. I think the script/debugger was either removed or replaced in Rails 2.0.</p><p>The quick and dirty way to test is to write data to <b>:flash</b> and view the contents of variables that way. The flash is a built in hash, part of the session data, used to display informational or error messages to the user. It is an easy way to debug simple problems.</p><p>For deeper problems, I write data to the log file using the <i>logger</i> object. It takes a little time to sift through all the stuff in the development log file, but you can see trends and what is passing through the application before and after the trouble spot.</p><h4>Railsbrain</h4><p>Finally, I want to point out an extremely useful reference web site for working with Rails: <a href="http://railsbrain.com">Railsbrain</a>. It has an Ajaxy API reference for multiple versions of Rails along with syntax and sample code.</p><p>I expect to come back to this article in six months and laugh at the inefficiency of the way I started doing Rails, but for now, it was enough to get that first useful application done.</p> http://www.commandlinemac.com/trackback.php/20080604213612724 Ruby Snippets http://www.commandlinemac.com/article.php/20080516232506615 http://www.commandlinemac.com/article.php/20080516232506615 Wed, 21 May 2008 23:25:00 -0400 http://www.commandlinemac.com/article.php/20080516232506615#comments Tips As I get deeper into the Ruby world, it is helpful to have a few snippets of working code and syntax for common tasks to copy as needed. I expect to add to this tiny reference over time.<br><i>updated July 9, 2008 to add a one liner to remove DOS line endings from a text file</i>. <h4>Formatting numbers</h4><p>To format numbers, use the sprintf method.<pre>x = 1.00puts "x is &#36;" + sprintf("%#0.2f", x)puts "x is " + sprintf("%#2d", x)</pre></p><p>The output is:<pre>x is &#36;1.00x is 1</pre></p><h4>The defined? method</h4><p>The defined? method can be used on any object to see if it exists.<pre>x = 1if defined? x puts "x is defined"end</pre></p><h4>Case statements</h4><p>Case statements are a more elegant way to handle a large number of conditions than using nested if statements.<pre>x = 3case xwhen "1" result = "x is 1"when "2" result = "x is 2"when "3" result = "x is 3"else result = "x is something else"end</pre></p><h4>Substrings</h4><p>Ruby has (at least) two ways to reference parts of a string object. One is to use the slice method:<pre>x = "abcde"y = x.slice(0,1)</pre>The result is y = "a".<pre>x = "abcde"y = x.slice(-1,1)</pre>The result is y = "e".<pre>x = "abcde"y = x.slice(2,3)</pre>The result is y = "cde".</p><p>The second way is to treat the string object as an array of characters like the C programming language.<pre>x = "abcde"y = x[2,3]</pre>The result is y = "cde".</p><h4>One liner to edit a file in place</h4><i>These one liners are also in the general Ruby article.</i><br><p>This command edits a file in place, performing a global text search/replace. The <i>-p</i> switch tells ruby to place your code in the loop <code>while gets; ...; print; end</code>. The <i>-i</i> tells ruby to edit files in place, and <i>-e</i> indicates that a one line program follows.<br><br><code>ruby -p -i -e '&#36;_.gsub!(/248/,"949")' file.txt</code></p><h4>One liner to remove DOS line endings from a file</h4><p>A Unix or Mac text file uses a single line feed character to mark the end of a line (hex 0A). Files created on DOS or Windows use two characters, carriage return and line feed (hex 0D 0A).This command edits a file in place, removing the carriage returns.<br><br><code>ruby -p -i -e '&#36;_.gsub!(/&#92;x0D/,"")' file.txt</code></p><h4>One liner to edit files in place and backup each one to *.old</h4><p><code>ruby -p -i.old -e '&#36;_.gsub!(/248/,"949")' *.txt</code></p> http://www.commandlinemac.com/trackback.php/20080516232506615 Boot Camp http://www.commandlinemac.com/article.php/20080414111256278 http://www.commandlinemac.com/article.php/20080414111256278 Mon, 14 Apr 2008 11:12:00 -0400 http://www.commandlinemac.com/article.php/20080414111256278#comments News <p>Boot Camp is a set of tools to make dual booting an Intel Mac with Windows XP or Vista easy. The main reason you might want to dual boot as opposed to running Windows in emulation is for the extra performance from running natively. You might need this for gaming or a demanding application like CAD or photoshop where running in a virtual is just too slow.</p><p>You must have a CD or DVD with the full version of Windows XP or Vista. An upgrade disk will not work.</p> <h4>Update firmware</h4><p>Before beginning the process, Apple recommends updating the firmware on your Mac to the latest version. If you are applying all software updates, then you are probably already at the latest revision. If you are not sure, run the Software Update command from the Apple menu.</p><h4>Boot Camp Assistant</h4><p>The next step is to run the Boot Camp Assistant program in the Utilities application folder. The first button in the assistant prompts you to print the installation and setup guide. I <i>highly</i> recommend you take that advice. I didn't and (temporarily) ended up with a Mac that would not boot. The guide is 25 pages long and covers all the details to get Windows installed. For that reason, I'll just cover the juicy bits and tell you the mistakes I made along the way.</p><p>The assistant provides a disk partitioning tool that lets you carve out part of your disk for Windows. I allocated 12 GB and proceeded to installation.</p><h4>Installing Windows</h4><p>I don't own Vista, so the rest of this article applies to Windows XP Pro SP2.<p>The installation of Windows works exactly like it does on any PC. When you get to the part where you have to choose what partition to install Windows on, select the one labeled <b>[BOOTCAMP]</b>. Also, it is important to have Windows format the partition (as either NTFS or FAT32), or it will not be able to boot back into the partition after copying its files to disk. The mistake I made was not formatting the disk. Even though the Windows installer could copy files to the disk, it was not able to boot back into the partition, leaving my Mac temporarily out of order.</p><p>I was able to get back into OS X by holding down the mouse button during boot, which ejected the Windows CD. Then I printed the installation guide, where I learned about the formatting requirement.</p><h4>Installing Windows drivers</h4><p>After Windows is installed, the next step is to install all the drivers for the Apple hardware. This was one of the best thought out parts of the process shows Apple's superior focus on human interface design. All you have to do is insert the OS X DVD while in Windows and it will start the driver installation wizard. Apple includes drivers for the video, audio, built-in camera, wireless airport, bluetooth, and more. It was the most painless Windows installation I have ever done.</p><h4>Booting between OS X and Windows</h4><p>To boot into OS X from Windows, you have two options. The first is to right click on the Boot Camp tray icon that gets installed during the driver procedure and select the option to boot back into OS X. You can also choose to make OS X the default boot option in the Windows Boot Camp control panel applet.</p><p>To boot into Windows from OS X, go to System Preferences / Start Up Disk and select the Windows partition as the default.</p><p>Finally, you can select which operating system to start at boot time by holding down theOption button.</p><h4>Keyboard quirks on a Macbook</h4><p>The differences in Apple and Windows keyboards is a source of minor annoyance. The keys are mapped in a reasonably intelligent way, but there are enough differences between the systems that some Windows features are awkard to use.</p><p>For example, to perform a right click, you hold two fingers on the trackpad and click the mouse button -- not a natural maneuver. The installation guide has a table that shows which keys and combinations map to Windows equivalents. Fortunately, most applications have some ability to map keys to make using them more comfortable.</p><h4>Getting rid of Windows</h4><p>Finally, the Boot Camp Assistant program has an option that lets you delete the Windows partition and restore the space set aside for use with OS X again. So, experimenting with a dual boot set up is not a one way ticket. Easy to try, easy to undo. http://www.commandlinemac.com/trackback.php/20080414111256278 Mountain West RubyConf 2008 http://www.commandlinemac.com/article.php/20080324170957972 http://www.commandlinemac.com/article.php/20080324170957972 Mon, 31 Mar 2008 17:09:00 -0400 http://www.commandlinemac.com/article.php/20080324170957972#comments News I attended the Mountain West RubyConf 2008 in Salt Lake City, UT.<br><br><a href="http://mtnwestrubyconf.org/"><img width="120" height="91" src="http://www.commandlinemac.com/images/articles/20080324170957972_1.gif" alt=""></a><br><br>It promised to be enlightening, and was. Some of the best sessions were unexpected gems (no pun intended). Following is my take on the sessions that provided some unique insights. Videos of all presentations are available on the <a href="http://mtnwestrubyconf.org/">Mountain West site</a>. <h4>First Impressions</h4><p>The trip to Salt Lake City was uneventful and I got to my hotel without incident. The walk from the hotel to the Library where the conference was about a mile. It's not really a long distance, but with the temperature slightly above the freezing point of water and a some wind gusts, it made for an unpleasant trek. Fortunately, the presentation room was top notch and there was plenty of power for all the laptop toting Ruby fans.</p><p>Nearly every attendee had a laptop fired up and I was a little shocked to see that <b><i>Macs outnumbered PC notebooks 4-1</i></b>. I heard the telltale boot up drum roll of Ubuntu a few times and saw one XO laptop (OLPC) in use. I wonder if the Apple appeal is limited to the Ruby glitterati or if it represents a wider trend.</p><h4>Opening Keynote -- Rubinius</h4><p>Two speakers were scheduled for the opening keynote presentation.</p><p>The first one was given by Evan Phoenix, the founder of the <a href="http://rubini.us/">Rubinius project</a>. I have to admit that I didn't know anything about Rubinius before the conference. It turns out it is a project to rewrite most of the Ruby interpreter in Ruby itself (though small parts of it remain in C). The current interpreter is written in C and I heard it referred to as MRI version, though I don't know what MRI means. The two other main implementations are JRuby, written in 100% java, and IronRuby, written in 100% C# for the Microsoft .Net VM.</p><p>Evan said Rubinius can now run the interactive Ruby shell (IRB), and Ruby gems, but he still considers it alpha software and has a ways to go before the 1.0 release.</p><p>He talked a lot about community, about his philosophy of accepting any contribution, no matter how small the size, and what the last year was like working on Rubinius. Evan mentioned that it is his personal goal, but not the project goal, to eventually be the standard Ruby interpreter.</p><p>From my perspective, it seems like an interesting project, but I'm not sure I see the need. I'm also skeptical about the performance impact, given that performance is already an issue for Ruby. However, I am keeping an open mind.</p><h4>Opening Keynote -- Merb</h4><p>The second keynote was given by Ezra Zygmuntowicz on the <a href="http://merbivore.com/">Merb web framework</a>.</p><p>Ezra introduced Merb, originally an acronym for Mongrel and Erb (embedded Ruby), but he said the project has transcended the original meaning. Merb is a full MVC web framework similar to Ruby on Rails. The project tagline is "All you need, none you don't". While he appreciates Rails, he said he wanted a leaner framework to build applications with less cruft.</p><p>Ezra said Merb was feature complete and may approach a 1.0 release later this year. He said it was refactored to be more more modular, and supports more options for back end data storage, not justrelational databases.</p><p>Merb prefers simplicity over magic as much as possible, with no need for monuments to personal cleverness. Merb claims to execute faster than other frameworks. He mentioned a line I heard in several other presentations: <b><i>People come for the rails, but stay for the ruby</i></b>.</p><p>Here are some other Merb factoids:<br><ul> <li>merb-core only uses 12MB of ram</li> <li>merb can run on ebb, mongrel, fastcgi, thin, and webrick web servers</li> <li>it has a logger and exception screens</li> <li>it can cascade applications (try calls to each until one returns something other thana 404)</li> <li>can handle restful transactions and routing</li> <li>can route based on user agent or anything in the request header, not just the parameters</li> <li>has code generators</li> <li>has mailers and parts (partials?)</li> <li>has before and after filters</li> <li>haml and Erb for templating</li> <li>caching</li></ul></p><h4>Domain Specific Languages: Molding Ruby</h4><p>Joe O'Brien presented a fascinating way to address problems in specific business areas by extending Ruby to create a meta-language, or mini-language, useful only within that domain. He talked about targeting the domain specific language (DSL) at primarily non-technical users, while a traditional API would be used for programmers.</p><p>He discussed the evolution of computer languages from machine-centric to programmer-centric to user-centric. For example, he showed this general progression of languages:<br><ul> <li>assembler</li> <li>C built on assembler</li> <li>Ruby built on C</li> <li>DSL built on Ruby</li></ul></p><h4>Enough stats so Zed won't yell at you</h4><p>Devlin Daley covered the use of httperf and how to approach performance measurement using statistics. He talked about how hard it can be to draw meaningful conclusions from raw data. He demonstrated the <a href="http://r-project.org">open source R statistical package</a> running on X11.</p><p>He discussed how the mean/average is not enough and showed how standard deviation was an important consideration when looking t a data set. He talked about how samples must be representative of the population.</p><p>He talked about a <i>z-test</i> to test how well a result compares to random guessing, and also the <i>t-test</i> to see if two samples are from the same population.</p><p>Zed quote (as relayed by Devlin) - "Programmers need to learn statistics or I will kill them"</p><h4>CouchDB</h4><p>Jan Lehnardt introduced <a href="http://couchdb.org/">CouchDB</a>, a non-RDBMS document based database. Instead of tables and records, it stores documents (objects) in JSON format. JSON is a text format similar XML, but easier to read/write. Similar documents don't need to have an identical schema. The read/write cycle works something like this:<br><br><code>Ruby object -&gt; JSON -&gt; CouchDB -&gt; JSON -&gt; Ruby object</code></p><p>CouchDB is written in Erlang, a language created by telco giant Ericsson. It features non-locking MVCC and ACID compliance. It doesn't support two-phase commits, just transactions on a single document read/write/update/delete.</p><p>Here is a sample document as stored by CouchDB:<br><pre>{"_id":"BCCD12CBB","_rev":"AB764C","type":"person","age":63,"dark_side":"true"}</pre>The _rev field stores the revision of the record, used to implement the MVCC.</p><p>Communication with CouchDB is done using HTTP REST, so no database abstraction layer is needed. You can use standard HTTP web server solutions to tune CouchDB like analyzers, load balancers, etc.</p><p>Here are some other CouchDB factoids:<br><ul> <li>Supports "view" which are used to create SQL-like functionality</li> <li>filters, aggregates, etc. done in view</li> <li>powered by map/reduce (special design documents), that define the functions executed by CouchDB</li> <li>Views can be written in JavaScript, Ruby, or Python</li> <li>View stats are saved in indexes and only updated when requested again</li> <li>Designed to take advantage of distributed machines/processors for high performance</li> <li>Comes with Lucene integration for full text search</li> <li>open source project created by Damien Katz, now funded by IBM</li></ul></p><h4>Ruby Internals</h4><p>Patrick Farley, from <a href="http://thoughtworks.com">ThoughtWorks</a>, gave what I thought was the most compelling presentation of the conference on the inner workings of the Ruby interpreter. </p><p>He began with snippets of C code from the interpreter showing how Ruby objects and classes are constructed and how method dispatch works. Methods are implemented by passing messages to an object. Ruby objects don't have methods attached to them, only their class and superclass. All method tables are attached to classes, so when you execute a method, Ruby looks at the object's class table to find it. It if doesn't find it in there, it looks at the method table of the superclass, then the superclass of the superclass and on up the chain.</p><p>When a singleton method is created, a unique method for one object, Ruby creates a unique class for that object in the background, references the original class as the superclass, and attaches the method to the unique class. Ruby doesn't tell you it created a unique class and if you ask it, it will return the original class of the object. Patrick explained several situations where this was desirable, but parts of the session went by too fast for me to grasp it.</p><p>Here are the core C snippets:<br><pre>All objects are built with two structs:struct RObject { RBasic basic st_table *iv_tbl --&gt; instance var table, properties};struct RBasic { unsigned long flags; frozen, tainted, etc. VALUE klass; --&gt; class type};No place for methods to be stored in an object. All methods stored in a class:struct RClass { struct RBasic basic; st_table *iv_tbl --&gt; properties st_table *m_tbl --&gt; methods VALUE super;};</pre></p><p>Patrick went on to show how JRuby, IronRuby, and Rubiniuis each implement objects, classes, and method dispatch. Toward the end of the presentation, my head exploded.</p><h4>BDD and Shoulda</h4><p>Tammer Saleh introduced <a href="http://www.thoughtbot.com/projects/shoulda">Shoulda</a>, a testing framework for Rails that extends Unit::Test. The goal of Shoulda is to allow you write simpler and fewer tests for your Rails applications. If you can write it in one line of code, you should be able to test it in one line of code.</p><p>One of the most powerful features of Shoulda is the "should_be_restful" test which can generate up to 50 Unit::Test lines internally. Tammer was not sure if that feature would remain in Shoulda for various reasons.</p><h4>Wrap Up</h4><p>The conference went off without a hitch. Several companies were actively hiring, pointing to a bright future for Ruby. According to the organizers, the size of the conference more than doubled compared to 2007, and they believe it will require a larger venue for 2009.</p> http://www.commandlinemac.com/trackback.php/20080324170957972 Ruby http://www.commandlinemac.com/article.php/20080318101113804 http://www.commandlinemac.com/article.php/20080318101113804 Tue, 18 Mar 2008 10:11:00 -0400 http://www.commandlinemac.com/article.php/20080318101113804#comments News <a href="http://www.ruby-lang.org/en/">Ruby</a> is a popular text processing language that has gained a lot of momentum over the last few years, mostly due to the rise of <a href="http://www.rubyonrails.org/">Ruby on Rails</a>. It has a lot of the good things from Perl, but implements a fully object oriented model and syntax.<br><br>Ruby is part of the default install of OS X. <h4>Working with Ruby gems</h4><p>Gems are Ruby packages that can be installed to extend the language or provide additional functions. Gems are managed using the <code>gem</code> command. To find all Ruby gems (packages) currently installed:<br><br><code>gem list</code></p><p>To install a new gem:<br><br><code>gem install <i>package</i></code></p><p>To update the gems package manager:<br><br><code>update_rubygems</code></p><h4>Taint mode</h4><p>For untrusted scripts, add -T flag to ruby at the start of the script:<br><br><code>#!/usr/bin/ruby -T</code></p><h4>One liner to edit a file in place</h4><p>This command edits a file in place, performing a global text search/replace. The <i>-p</i> switch tells ruby to place your code in the loop <code>while gets; ...; print; end</code>. The <i>-i</i> tells ruby to edit files in place, and <i>-e</i> indicates that a one line program follows.<br><br><code>ruby -p -i -e '&#36;_.gsub!(/248/,"949")' file.txt</code></p><h4>One liner to remove DOS line endings from a file</h4><p>A Unix or Mac text file uses a single line feed character to mark the end of a line (hex 0A). Files created on DOS or Windows use two characters, carriage return and line feed (hex 0D 0A).This command edits a file in place, removing the carriage returns.<br><br><code>ruby -p -i -e '&#36;_.gsub!(/&#92;x0D/,"")' file.txt</code></p><h4>One liner to edit files in place and backup each one to *.old</h4><p><code>ruby -p -i.old -e '&#36;_.gsub!(/248/,"949")' *.txt</code></p> http://www.commandlinemac.com/trackback.php/20080318101113804 Intel vs. PowerPC Macs http://www.commandlinemac.com/article.php/20080301224413475 http://www.commandlinemac.com/article.php/20080301224413475 Sat, 01 Mar 2008 22:44:00 -0500 http://www.commandlinemac.com/article.php/20080301224413475#comments News I recently purchased a new Intel Macbook to replace my trusty iBook G4. Much has been written about the Apple's switch from PowerPC to Intel processors and there is no denying the market power of Intel, but I have some comments now that I have spent a little time with both kinds of Mac. <h4>RISC vs. CISC</h4><p>When comparing Intel and PowerPC micro processors, a common theme <i>used to be</i> the Intel complex instruction set (CISC) vs. the IBM reduced instruction set (RISC). This line of reasoning may have had some merit in the 1980s or early 1990s, but processor architecture has blurred, with each family incorporating the best designs of the other. I don't read much about this any more because it mostly doesn't apply.</p><h4>Big endian vs. little endian</h4><p>The <a href="http://en.wikipedia.org/wiki/Endianness">endianness of a processor</a> refers to the byte order of data in memory. Specifically, big endian processors, (traditionally the PowerPC line), stored the most significant bytes first, while little endian, (the Intel line), stored the significant bytes last. If you have ever debugged data or instructions in memory, big endian is the logical way you would expect to see things, a more natural or human way to read memory. Little endian data looks garbled to me.</p><p>I started my programming life long ago on an IBM mainframe (big endian) and wrote quite a few lines of assembly language. I actually enjoyed working with the mainframe register architecture and assembly was a joy. When I started working with Intel PCs, assembly language became a nightmare. The registers could be addressed partially using one mneumonic, fully with another, and the debugger showed bytes in the strange little endian order. It was a real buzz kill.</p><p>Today, with optimizing compilers and high level languages, it doesn't make much difference any more. Most modern languages are so high level (my current favorite is Ruby), that endianess is transparent. Some processors can even be programmed to change their endianess. So, other than personal preference, and a slight distrust of engineers that prefer little endian, this is a difference that doesn't carry much weight.</p><h4>Power, heat, and batteries</h4><p>PowerPC processors have nearly always been more power efficient than Intel. This translates into less heat (less time running a cooling fan), and longer battery life. The battery life between my new Intel Core 2 Duo Macbook and my G4 iBook is dramatic. Even though the G4 is over 2 years old, it still gets about an hour and half of extra battery life. Certainly, part of that is because it also has a smaller and dimmer screen, but the processor architecture is also a factor. I was shocked at how fast the Macbook battery ran out the first week I had it. It is still better than a Windows laptop, but a step backward compared to the G4.</p><h4>Binaries</h4><p>The operating system was not the only thing that had to be compiled to run on Intel processors. To take advantage of native speed, every application had to be recompiled. Some software vendors took their time building Intel binaries. Apple provided the "Universal binary" solution ahead of the switch so the application hit wasn't too harsh.</p><h4>The virtual plus</h4><p>Apart from the ability of Intel to supply Apple with enough processors, the switch enabled fast virtual machine technology that doesn't rely on software emulation to work. Applications like Parallels and Vmware Fusion give the Intel based Macs a vastly improved capability to run Windows, Linux, and other operating systems with OS X as the host. I tried running Linux on the free Q virtual machine on the G4 and it was almost too slow to use. Running VMware Fusion, I have a couple of Linux distributions running graphical X desktops at near native speed. In this sense, the switch to Intel was a virtual plus.</p><h4>Does it matter?</h4><p>How you weigh the positives and negatives above determines how you view the switch. In the end, the best things about a Mac still exist in the Intel world, and apart from the good folks at IBM, Motorola, and Intel, most people won't notice.</p> http://www.commandlinemac.com/trackback.php/20080301224413475 How to turn off Dashboard http://www.commandlinemac.com/article.php/20080228114813447 http://www.commandlinemac.com/article.php/20080228114813447 Thu, 28 Feb 2008 11:48:00 -0500 http://www.commandlinemac.com/article.php/20080228114813447#comments Tips The Dashboard is a handy feature of OS X to keep information flakes and small tools at the ready.<br>Read on for how to disable (and enable) the Dashboard. <p>To turn Dashboard off, run the following command from the Terminal:<br><br><code>defaults write com.apple.dashboard mcx-disabled -boolean yes</code></p><p>To turn Dashboard on:<br><br><code>defaults write com.apple.dashboard mcx-disabled -boolean no</code></p><p>Because Dashboard is a component of the Dock, you need to restart the Dock after making either change:<br><br><code>killall -1 Dock</code></p> http://www.commandlinemac.com/trackback.php/20080228114813447 Advanced BASH scripting guide http://www.commandlinemac.com/article.php/20080228102513952 http://www.commandlinemac.com/article.php/20080228102513952 Thu, 28 Feb 2008 10:25:00 -0500 http://www.commandlinemac.com/article.php/20080228102513952#comments Symlink User <i>forbade</i> pointed out this great guide from the Linux Documentation Project:<br><br><a href="http://tldp.org/LDP/abs/abs-guide.pdf">Advanced BASH scripting (pdf)</a><br><br>It is also <a href="http://tldp.org/guides.html">available in other formats</a>. <p>Speaking of BASH scripting, my favorite BASH book is published by O'Reilly, <i>Learning the BASH shell</i>. It covers a lot of basics and command line use in addition to programming.</p><p>Also, when I am writing a serious production script, I often start with new_script, a shell script that creates a solid template as a starting point. You can download new_script from the <a href="http://www.linuxcommand.org/script_library.php">LinuxCommand.org script library</a>.</p> http://www.commandlinemac.com/trackback.php/20080228102513952