Showing posts with label ruby. Show all posts
Showing posts with label ruby. Show all posts

Friday, May 23, 2008

Notes and Notes

A couple of recent life, the universe, and everything notes:

  • I realize I've been away from here for most of the last couple of weeks -- a side project has been eating up a lot of time. I should be done with in next week, and back to posting here more regularly. I know, I always say that.

  • I'll be at RailsConf 08 later this month, and I'll probably have some number of copies of Professional Ruby on Rails to do something promotional with, but I haven't exactly decided what. If you are going, I hope to see you there.

  • The rails_iui plugin was mentioned on the Rails Envy Podcast -- thanks to Gregg for the mention. There are now just over 35 people following the project on GitHub. I do plan to add more features over the coming weeks.

  • On a related note, I've turned in a 3-part article for IBM DeveloperWorks about iPhone development with Ruby on Rails. No idea when it'll show up, though.

Friday, March 21, 2008

My Favorite Monkeys

New post at Pathfinder on monkey patching.

Friday, February 22, 2008

Shipping!?

Amazon is now saying that Professional Ruby On Rails is in stock! I haven't seen my copies yet, and I suspect Amazon purchases will actually go out next week, but it's a real page and everything.

The link to purchase is right here.

I've also added a running list of errata and updates. Check back on that every now and then.

Much more on the book over the next week.

Monday, February 11, 2008

Hey, Free Book Samples!

As I've mentioned here a few times, I have a book coming out, "Professional Ruby on Rails", available later this month.

If you'd like a sneak peek, Wrox has put some samples online as PDF files. You can also just buy the book.

  • Chapter 1 -- This sets up the sample project used in the book, and talks about the new REST features in Rails.

  • Table of Contents -- Take a look at this to see if your favorite topic is covered.

  • Index -- A more detailed way to see if your favorite topic is covered. Also, maybe you collect indexes...

I'm not sure if the publisher plans on adding more sample content -- if so, I'll update this post.

Sunday, December 30, 2007

Professional Rails Online?

In response to the commenter who asked if there was going to be a beta book.

UPDATE: Clearly I should ask about these things before I post. Jim Minatel from Wrox added the following in comments:

  • There will be a PDF about six weeks after the print book, meaning end of March or thereabouts. There will also be an Amazon Kindle version, eventually.

  • Also after 6 weeks, the book will be available via Wrox's online subscription service: http://wrox.books24x7.com.

  • It won't be on Safari, apparently Wrox books aren't part of the deal there (which I actually was kind of wondering about). Meaning I still haven't placed a book there)

I now return you to my earlier, ill-informed, blather...

Unfortunately, I'm pretty sure the answer is no. Not only doesn't Wrox tend to do that kind of thing, at this point, the book is do to go to press in about two weeks, so the amount of time to get feedback would be sharply limited.

At one point, I was told that sample chapters would be available online before release, but I don't have any information on whether there will be an e-book available. I don't think there will be a direct purchase of a PDF, but it seems as though Wiley just joined the Safari book store, and the book might be available there. I'll try and find out for sure this week.

Sunday, December 09, 2007

Things I Learned

Some things I learned about Rails and writing while working on this book:

  • The great benefit of working on a project like this book is that it enabled me to compress about two years worth of research into Ruby and Rails tools into six months. In my case, this was a great opportunity to really dig into some tools to find that I've only been using a fraction of their power and also really get a sense of how elegant and flexible the tools are.

  • Ever since I learned how to type back on an actual typewriter in the mid 80s, I've always followed the old-time typographical convention of two spaces following a period. Which was burned into my fingers despite multiple people telling me that was a silly and counterproductive thing to do in the brave new world of proportional fonts. In fact, on the wx book, I actually did a global search and replace for a period followed by two spaces to get the manuscript to correspond with the publisher's expected conventions. Somehow, I managed to break that habit while writing this book.

  • The hardest stylistic thing for me to get around was avoiding using "we" and "us". In other books and articles, I tend to introduce examples by saying things like "Now we should type the following" or "Let's see how that's implemented". Wiley/Wrox house style, though is to avoid "we" and write the examples as "Now you should type the following" or "I'll show you how that's implemented". Even more preferred is avoiding the pronoun altogether with "Here's how that's implemented" or "type the following". I'm not saying one way is better or worse -- I find the "we" style to be conversational, the Wiley editors clearly disagree. It did take some getting used to, though.

Thursday, November 29, 2007

Two Pathfinder Blog Posts

Two things on the Pathfinder blog.

  • Agile Publishing, on publishing experiences and agile methods.

  • Live Ruby: Testbed, an attempt to work through a small test and metaprogramming problem live and on the blog.

Enjoy.s

Thursday, August 30, 2007

The Rails Edge

I was fortunate enough to attend Pragmatic's Rails Edge mini-conference here in Chicago last week. I have two blog posts up on this at Pathfinder, the first is made up of quotes from my notebook, and the second is some general thoughts. Enjoy.

Pro Rails Book Related Things

A few things I forgot to put in the last book update:

  • The Amazon listing has the book at 600 pages. That's almost certainly optimistic. The contract calls for 400-500.

  • As far as the schedule goes, I'm currently hoping to turn the complete draft in on October 26th, which is about ten days after the original date. The publisher says that pushes publication out to April, six to eight weeks after the original date. I don't quite understand the math, but I suspect that it has to do with the logistics of availability of printing equipment and the like.

  • Chapter Seven appears to be on track to be delivered this week, which makes the book just a smidge less than halfway done.

Monday, August 13, 2007

And Now, A Special Announcement

Sorry for the radio silence for the last week or so, but I was waiting to be able to announce this:

Today I started a new job at Pathfinder Associates, as a senior software engineer in charge of Ruby on Rails projects. Needless to say, I'm thrilled to be back in the Web game professionally, and even more thrilled to be working on Rails projects.

Everybody at Pathfinder has been super great so far, and I'm looking forward to doing exciting and fun things.

I'll also be blogging on their web site roughly once a week, either at their Technical Development blog or their Agile/Ajax blog.

If you happen to be one of the maybe five people who read this blog regularly, don't worry, I'll continue to post here with updates about the book and thoughts about programming and technical publishing that wouldn't quite fit on the Pathfinder site.

Thursday, June 14, 2007

Didn't I Say I Wouldn't Compare Languages?

I posted a version of this to JJ Behrens' Blog post about Ruby, and decided it was probably worth also posting here.

I use and like both Ruby and Python, here's why...

Things I like about Ruby with respect to Python



  1. I think Ruby is the only language that gets accessors right. The thing you want to do 95% of the time -- simple access -- is trivial, and the thing you want to do 5% -- something fancy in your accessor -- of the time is a pretty easy override. Plus, it's nicely encapsulated, and you never have to wonder if that thing in another class is accessed directly or via a method.

  2. Blocks. I find that my kind of functional style flows pretty easily in Ruby. It's also not hard to pass named functions. When I first started with Ruby, it used to bother me that you couldn't tell from a method signature if it took a block, but I've since managed to deal.

  3. Being able to add method to existing classes. Although I know this really bugs some people, sometimes adding a method to String cleans up the code significantly.

  4. Expression-based syntax. The implicit return in Python always causes me at least one error per sessions. Plus I like writing a ternary operator as an actual if statement.



Things I like about Python with respect to Ruby



  1. Consistency. Python enforces it. As a result, my Python code is more likely to be readable by me six months later. Ruby tends to be more concise, but some parts of Ruby are still a little too Perlish...

  2. Real keyword arguments (coming to Ruby soon). The Ruby syntax magic of gathering up map pairs into a hash is sort of annoying.

  3. I find Python's multiple inheritance mechanism to be easier to understand then the Ruby package/module setup. It always seems like I'm messing up the difference between 'require' and 'include'...

  4. On balance, I prefer Python immutable strings to Ruby's mutable string/symbol split.

Sunday, May 13, 2007

from internet import *

Three posts that caught my eye today.

Ruby School


Gregory Brown over on O'Reilly net has an article about using Ruby in Computer Science courses, at least in later algorithm classes. It's not a bad argument, but I think it'd be more convincing if the Ruby example was a little cleaner and easier to read compared to the pseudo-code.

Let's see... The last time I had to care about this issue was about eight years ago when my grad institution was going through a somewhat controversial revamp of the CS curriculum. The fight, as always, is between the theorists and the pragmatists. The theorists want to teach a lot of "pure" CS up front -- Turing machines, big "O" analysis, computational theory, that kind of thing. The pragmatists want the students to be able to get jobs.

You should know that I spent the better part of three years as part of a group working with an object-oriented class that we taught in Squeak Smalltalk. Lovely language, to be sure, but we had to spend part of every course explaining to some nervous students why we weren't teaching them C++ or Java...

At the time, the initial CS classes were moving to Java, with some relief. This is because a) nobody wanted to inflict C or C++ on unsuspecting new CS majors, and b) the previous most common language, Pascal, was woefully obsolete. Java is reasonably straightforward to teach and is actually used in real programs, both high points.

Personally, I think you can make a pretty nice case for a scripting language like Python or Ruby in the initial CS class. They are both pretty easy to get started with, the syntax is clean enough that algorithms are easy to visualize (which was Brown's original point). In Python you can do it without introducing objects (which most CS1 classes didn't do eight years ago, don't know if that's changed). In Ruby it's easy to teach meta-programming.

Cha-Ching


Paul Julius of ThoughtWorks about how CruiseControl can save you $12,535 per broken test. The money coming from the difference between the cost of fixing a bug immediately versus not catching the bug until integration testing.

I dunno. I love continuous integration, and would shout about it from the rooftops if they'd let me on the roof, and that number still sounds a bit more "look what I can do with numbers" than "look what I can do with Continuous Integration". But then I'm skeptical of nearly every numerical analysis of programming productivity.

Plus, Marshmallows


Over at Roughly Drafted, Daniel Eran goes on about the smooth, harmonious relationship between Apple and Sun. Naturally, I want to talk about one of his sidebars...

The name of Apple's Mac OS X frameworks was even named Cocoa in part to associate it with Sun's Java. The other reason was that Apple already owned the Cocoa trademark, having using it earlier for a children's programing environment.


You know, I've always wondered about that. The original Cocoa was a project that was being worked on in Apple's Advanced Technology Group the summer I interned there, plus it some buzz in Educational Technology circles for a while. Internally, it was called KidSim, but the name was changed to Cocoa when it was being prepared for release. Java was programming for grown-ups, so Cocoa was programming for kids. It seems like Apple isn't really using that connotation of the name anymore.

The project (now called Stagecast Creator) is a graphical rule-based programming language, something like a cellular automata program. The user specifies an initial arraignment of sprites on the screen, then specifies how that arrangement should change in the new time slice. Complex programs could be created with almost no typing (although, like all such programs, you still had to use drawing tools to create your own sprites -- that was still hard). Stagecast still seems to be around, although it's been ages since I tried the software. It was pretty cool, though.

Wednesday, March 28, 2007

Posting to Blogger via Ruby

TextMate has what seems to be a very nice blogging bundle for programmatically sending posts to your blogging engine of choice. Except that it doesn't work for the new Blogger API. Or at least it didn't the last time I checked. Mostly I just wanted to see if I could write my own script to send to Blogger.

This is a Ruby script based on the Python script located at http://djcraven.blogspot.com/2006/10/success-posting-to-blogger-beta-using.html -- the author of that script did the heavy lifting in terms of the GData API calls, what I did was translate it into Ruby in a somewhat more flexible structure. At least I hope so. I also hope this will look like decent, idiomatic Ruby and not like a horrific hack. And I'd like a pony. If you're asking.

Let's do this in pieces. The first piece of the puzzle is using the Google ClientLogin API to get an authentication token. The token is then passed as a parameter to later calls when we actually want to post something. Google says that the lifespan of the token is dependent on the application being used, but I don't see where they specify how long Blogger keeps them.

Here's the start of our class. We're in a module called Blogger and a class called Blog. I've got an external dependency here on BlueCloth because I'm also going to automatically translate Markdown later, but that's not something you need to do...


module Blogger

require 'net/https'
require 'net/http'
require "uri"
require "bluecloth"

class Blog

attr_accessor :account, :password, :blogid

@@auth_url = "www.google.com"
@@auth_path = URI.parse('/accounts/ClientLogin')

def http
http = Net::HTTP.new(@@auth_url, 443)
http.use_ssl = true
http
end

def request_data
["Email=#{account}",
"Passwd=#{password}",
"service=blogger",
"service=TestCompany-TestApp-0.0"].join("&amp")
end

def auth_headers
{'Content-Type' =>
'application/x-www-form-urlencoded'}
end

def auth_token
response, data = http.post(@@auth_path,
request_data, auth_headers)
return nil unless response.code == '200'
data.match(/Auth=(\S*)/)[1]
end


After the setup lines, we've got three methods here. The first two define the data objects. The first one creates a Ruby HTTP object, set up for an HTTPS connection to the Google ClientLogin URL. The second builds the request data string, tying together the four pieces of data into a single string. They are both used in the auth_token method -- I'm taking advantage of one of my favorite features of Ruby, which is the lack of distinction between local variables, no-argument methods, and data field getters.

So, http, request_data, and auth_headers are just dropped into the auth_token code as if they were local, even though they are separate methods. To me, that makes the code read cleanly, and encourages moving small bits out to separate methods where they can be separately tested and documented.

The auth_token itself takes the path, the request_data, and the headers, and uses the HTTP object to make a secure post call. Request data, by the way, has account and password information that I'm assuming would be defined in an abstract subclass of this Blog class. If the response code is 200, we're good to go, and we do a little regular expression magic to extract and return the authentication token.

We use the authentication token in our actual post call, the one that contains the blog post itself. We need to build up the XML Atom document to send to the Blogger server. Step one is to get the data. Since I'm going to be doing this from TextMate, I'm going to assume we're going to start with the file name that will eventually be provided by the TextMate command. First, we'll convert it to an array of lines.


def read_data(filename)
text = open(filename) { |f| f.readlines }
end


In case it's not already clear, this method and the ones that follow are all parts of the
Blog
class. We're splitting this into lines to facilitate some processing of the text. I'm assuming that the first line of my file will be the title of the post, the second line will be a comma-delimted list of category labels, and the remainder of the file will be the body, written in Markdown. Obviously, that specific format is a weird quirk of the particular blog I'm posting to, which is set up to take XML and not to preserve blank lines. In your case, do whatever you need to do. Building that data structure
is quite simple in Ruby.


def build_data(lines)
categories = lines[1].split(",").map {|c| c.strip}
body = BlueCloth.new(lines[2..-1].join(" ")).to_html
data_xml(lines[0], categories, body)
end


The last line of build_data calls the data_xml method that builds up the XML document:


def data_xml(title, categories, body)
result = []
result << "<entry xmlns='http://www.w3.org/2005/Atom'>"
result << " <title type='text'>#{title}</title>"
for cat in categories
result << " <category scheme='http://www.blogger.com/atom/ns#' "
result << " term='#{cat.strip}'/>"
end
result << " <content type='xhtml'>"
result << body.to_s
result << " </content>"
result << "</entry>"
result.join("\n")
end


I was going to use the REXML library for this -- normally I'm a big fan of building XML programatically. However, REXML really, really didn't like it when the included content contained HTML tags. So I decided it'd be much less aggravating to build the XML from scratch. Details on the syndication format can be found in the GData and Atom online docs.

Once we can create the data, we can finally make our post:


def post_headers
{'Content-Type' => 'application/atom+xml',
'Authorization' =>"GoogleLogin auth=#{auth_token}"}
end

def uri
"http://www.blogger.com/feeds/#{blogid}/posts/full"
end

def post(lines)
response, content = http.post(uri, build_data(lines), post_headers)
while response.code == '302'
response, content = http.request(response.location, entry.headers)
end
return response.code == '201'
end

def post_file(filename)
post(read_data(filename))
end
end
end # of module


Couple things to point out here. First, we call auth_token directly when we're building up our header in preparation for the call -- so that's when we perform the HTTPS login shown above. The while loop takes care of following along if Blogger decides to redirect the post. Finally, we return true if Blogger sends us an OK response code 201, meaning the post has been successfully added.

To use this, you need to set up your own subclass of Blog with the expected information, for example.


class MyBlog < Blog
def initialize
@account = "YOUR_GMAIL_HERE"
@password = "YOUR_PASSWORD_HERE"
@blogid = "YOUR_BLOG_ID"
end
end


As written, that would be included in the Blogger module, otherwise, you'd need to qualify the name Blog. The invocation of the whole thing looks like this. This assumes that the filename with the post is in ARGV[0], placed there by TextMate.


p Blogger::MyBlog.new.post_file(ARGV[0])


One problem, though. We're making an HTTPS connection for authentication to keep our password secure, but including the password in plain text in the script file. Good point. There's a cool way around that in TextMate, and probably

Wednesday, March 21, 2007

Rubies in My Coffee

Now two of the big Java IDE's are promoting Ruby language tools as a big thing. IntelliJ has a plugin in early beta, and NetBeans is also making a big deal of their new early beta support. Eclipse has had a Ruby/Rails plugin for about a year or so.

This is weird, weird, weird, that suddenly all the Java tools would feel the need to grow into somewhat ill-fitting Ruby IDE's (Eclipse has always styled itself as more of a meta-IDE, so that's a little less strange). But do we really need all these Windows Ruby IDE's to be attached to big, memory hogging, Java tools. (And in IntelliJ's case, I say that with love...)

I've played with all three now -- I've used Eclipse for Windows-side Ruby editing for a while, and for the last few days I've been going back and forth between IntelliJ and NetBeans checking them out on an existing Rails project. None of the three are going to make me ditch TextMate yet (although I'd say the big tools all have somewhat more developed project support that TextMate).

IntelliJ's plugin really strikes me as Not Ready Yet. For one thing, there's no syntax checking on .rhtml files, which is a big problem. Also, there's a cool Rails project view, that associates the .rhtml files with the appropriate controller method, but there didn't seem to be an obvious way to get to partial .rhtml files. Another minor frustration is that the Ruby syntax layout is not customizable yet, the way the Java one is. It's even hard to keep a separate setup so that Ruby files only have a two character indent. (And there's a good sociology of programmers paper, on why Ruby is canonically a two character indent, not four).

This seems like a good place to point out that I still haven't spent all that much time with any of the new tools, so it's entirely possible I just missed something. For instance, even though the IntelliJ docs say there are Live Templates for Ruby, my installation didn't seem to have them.

There's some nice stuff in the IntelliJ tool -- all the ctrl-N navigation works on Ruby classes and methods. It's very easy to run arbitrary Rake tasks from the UI (although they seem to run kind of slowly) I don't think syntax completion is there yet, but it does syntax check .rb files on the fly I'd like to see this one a few revs down the line.

The NetBeans tool is in their beta for version 6 (you have to download the tool, then grab Ruby support via the update center). I was kind of amazed to be liking this because I fled NetBeans in a huff around version 3 and haven't had any success in trying it since. The syntax coloring and layout seems to be a bit stronger. It appears to be using JRuby not just for internal parsing, but also as the default external engine for running, say, WEBrick. Which makes everything feel a little slow. There is some syntax-completion -- I found it a little hit-and-miss in terms of getting useful alternatives. The project view is nice -- it flattens out all the /app subdirectories, but I couldn't see an obvious way to run arbitrary rake tasks or the test suite. Although there is a keyboard shortcut to run an individual file, and if you try it in a view page, it attempts to open that action in a browser. My app has a slightly nonstandard route configuration, though, so it didn't quite work for me.

I also had some stability problems, mostly with trying to run the server from NetBeans, it either hung or took a really long time to load. Development on this seems to be progressing rapidly -- they are releasing new versions much more quickly than IntelliJ, so all these things could be fixed by Thursday.

Right now, NetBeans would be my pick of the three if I couldn't use TextMate. I'm as surprised as anybody by that conclusion, but it felt pretty good as I was using it. Adding easy test hooks would help. All three tools are still under development (RDT for Eclipse just released a new version, and RadRails just passed to a new owner with new development promised). So, watch this space, I guess.

Update: Looks like NetBeans has a bug in reformatting code -- it kind of messed up some of my source files. Nothing permanent, just kept indenting and not noting the end to outdent so the file kept creeping to the right.

Thursday, August 31, 2006

Languages I Use

Continuing in the getting to know you kind of vein, I thought I'd ground some of what I say by talking about the three programming languages that have made up the bulk of my professional and hobby work for the past five years or so -- Java, Python, and Ruby.

Java: I've been programming Java since either just before or just after the 1.0 release... can't quite remember at this point. I think I've covered most of the major Java libraries (although I've done very little EJB work). Basically, Java is the station wagon of programming languages. It's not elegant or efficient, but it gets you where your going and you won't offend anybody along the way.

Far and away the best feature of working in Java is the tool support, especially the IDE support. If you're doing something in Java, odds are somebody has done it before and there's an open source .jar file somewhere that will help. Plus, IntellJ IDEA makes working in Java almost as productive on a time-basis as working in a scripting language.

Java is, of course, famously verbose, and there's the constant sense of telling the compiler things that the compiler should already know. (The 1.5 language features improve this somewhat, at the cost of moving some of the verbosity elsewhere). Java's original design goal was basically to get C programmers to do object-oriented stuff without scaring them away, and at that it's a success, but that does lead to oddities like having both basic types and object wrappers for them, and keeping the ridiculous C-style switch statement.

There's also the "Java style" of OO design, enshrined early on by Sun, and followed by many third-party libraries. To oversimplify, there's a lot of design made complicated by the desire to make less common tasks as privileged in the API as more common ones. For example, the need to spell out what are basically boilerplate properties in a web.xml file or a Struts config file. Swing has several features like this, including the event system and say, supporting multiple listeners for a button click.

Python: With Python I suppose you have to start with the whitespace thing, although I know that anybody who actually works in Python is sick of hearing about it. I wrote what I hope was a spirited defense of it in the Jython book, and I'm not going to repeat myself. What I like most about working in Python is the conceptual consistency -- objects are like classes are like modules are like dictionaries. I find that to be a very powerful equation, and it makes Python code more predictable to me. I also think the syntax is very clear and readable. (I particularly like the list comprehension syntax.)

On the down side, although there probably is more Python libraries than Ruby ones floating around (although I'm not as sure of that as I was even a year ago), there's no central repository so they are harder to find. It is true, though, that Python style quirks are more likely to bleed into my programming in other languages than vice-versa -- I write a lot of Java code that really looks like it wants to be written in Python.

Ruby: I actually got into Python, Ruby, and XP at about the same time. I started on Ruby because a number of the early XP gurus were excited about it. And while I know I'm supposed to pick a side or something, I actually like Python and Ruby both quite a bit. There are some particular bits of Ruby syntax that I think are particularly well done, for example the way that accessors are handled. I even like that you can leave parentheses off method calls if the line is unambiguous, although a little of that can go a long way. Blocks make the language very flexible, and very easy to build non-redundant code in.

There are a couple of pieces of Ruby syntax that make me nervous, like the syntactic sugar for hashes as the last argument of a method or the way you don't have to specify that a block is needed in the signature of a method. To be fair, I haven't experienced practical problems with these features yet. Ruby has a lot of syntax sweetener compared to Python, which is sometimes good (elegant Ruby code is very elegant) and sometimes bad (I've had some trouble following Ruby examples if they are very magical). Because Ruby has been the focus of a lot of XP/Agile writers, the testing tools and general XPish support is very good. For a long time, I thought that general library support lagged Python, but that's becoming less true daily. And of course there is also Rails, about which more at another time.