CoffeeScript Tips & Tricks

Following on my CoffeeScript talk at the Ithaca Web Group and my company, GORGES, I downloaded the new Pragmatic Programmers book on CoffeeScript. I have completed the language reference part, and wrote down the tips and tricks I learned along the way. I’ve published my notes on CoffeeScript to a Gist on GitHub. Anything missing?

May 26, 2011 in Uncategorized

Casey Dreier’s Rack presentation

This evening Casey Dreier of Singlebrook Technology gave an excellent talk on Rack. As he explained, Rack the Ruby gem provides a common interface between Ruby applications and web servers. It allows you to develop a Rails application locally using Mongrel or Unicorn and deploy it on Apache. You can “mount” applications to paths on your domain, allowing you to do things like “drop in” the Resque admin screens, which are built in Sinatra. Or in our brave new world, take your app that currently runs on Apache/MRI and port it to JRuby/Trinidad with a minimum of fuss.

You can think of middleware as an around filter for your application. To call your application, Rack starts at the bottom of the middleware stack and bubbles up to the application. The application yields its response, and bubbles that response back up the call stack. Through middleware, you have the opportunity to manipulate the server environment variables (session, cookies, url, environment variables) before the request ever gets to Rails. You can even prevent the request from getting to Rails at all. On the flip side, you can manipulate the response all the way back out, and even replace the Rails response with “Hello world” if you like. Its main use in Rails is to prepare the environment to invoke an action on the controller.

I learned a couple of things in Casey’s talk:
1. That a Rails 3 controller is a Rack endpoint. I did not realize that I could “use” middleware beyond the initializers and the dispatcher.
2. That I should not be afraid to mount Sinatra apps using config.ru and bypass the now gigantic Rails middleware stack.

Then my feelings began to diverge. I came to Casey’s talk having watched Aaron Patterson’s keynote at RailsConf, in which I showed all the hacking he had to do to get Rack to work with Rails 3.1 output streaming. Along the way he saw that Rails 3 is actually slower than Rails 2, mainly because the tall middleware stack triggers Ruby’s garbage collector in a mean way.

Casey’s simple example was a timer middleware that appends the response time to the response body in an HTML comment. Simple enough and fairly taken. Then there was a quick look at his recent gem, “rack-unscripted”. The gem inserts a piece of middleware that looks for the end of the head tag and the beginning of the body tag, and inserts some HTML snippets that, if you don’t have JS enabled, will tell you that you should enable it if you want the application to work. The snippets themselves are clever – I will give them a further look.

My first response betrays my having just watched Patterson’s talk, with three months of exile from Rails in the PHP world under my belt. Why would you add a layer to the call stack for a 0.1% use case? Why perform gratuitous regex subs on the response body when you could add that to your layout? Casey’s response was twofold: 1. He wanted to learn Rack, and this was the immediate use case. 2. Now he can include it in any application via a gem.

Then I started thinking. Inserting HTML into the response body is not the concern of middleware. If it’s not going to be a helper function used in the layout, it could be an after filter on ActionController::Base. You can still put it in a gem for ease of installation. It properly belongs in the V part of MVC; and middleware is for abstracting away non-MVC concerns so that the application itself remains focused on models, views, and controllers.

Having said that, I sure wish that the framework of my current project (Yii PHP framework), has middleware. Because the project is targeted at IE7 as a minimum (at least not IE6!), I wanted to introduce the Rails way of simulating PUT and DELETE requests. That is to add a hidden input named ‘_method’ to the top of a form. If $_POST[‘_method’] exists then set $_SERVER[‘REQUEST_METHOD’] to its value. Perfect use for middleware: manipulate the environment variables so your app thinks it’s dealing with a DELETE request before it gets to the router.

In the end, I had to do it a different way. I had already extended CWebApplication to handle namespaced controllers, and updated index.php to call MWebApplication instead of CWebApplication. I added a call in createController that does the _method check. In retrospect that would be a place to introduce support for “inbound” middleware.

What do you think? Both from an efficiency standpoint, and from separation of concerns (concern that all hell breaks loose when you start manipulating the views somewhere other than the view layer).

Thanks Casey for the engaging talk, and to Singlebrook for hosting the Ithaca Web Group.

May 20, 2011 in Uncategorized

Comment Spam I’d Like to Use

WordPress comment spam almost worth saving to use on student papers if I were still teaching:

Comment:
Together with the whole thing that appears to be developing within this particular subject matter, many of your perspectives are rather refreshing. On the other hand, I appologize, because I can not subscribe to your entire plan, all be it refreshing none the less. It appears to everybody that your comments are not completely justified and in reality you are generally yourself not even completely confident of the assertion. In any case I did enjoy reading through it.

December 10, 2010 in Uncategorized

Firefox Extension Toolbarbutton CSS in Windows 7

Lesson learned today:

If you have a Firefox extension and you use the toolbarbutton element.

In Windows 7 you can only use list-style-image to style it. Background color, -moz-linear-gradient, and -moz-border radius don’t do anything, plus you get a special fancy hover effect.

I ended up converting the toolbarbutton tags to a tags and moving on with life. Had to convert oncommand to onclick and say goodbye to the tooltiptext.

October 15, 2010 in Uncategorized
Tagged , , ,

Instance variable not assigned in view

I just spent a few minutes in la-la-land trying to figure out when an instance variable assigned in the controller stopped showing up in the view, despite all evidence that it was getting set correctly in the controller.

The answer was that there were several conditions that would case an update action to render :action => :edit. I was being clever by moving them to the top of the function, however then I was assigning that instance variable AFTER I had called render.

Lesson learned: Although controller code keeps on executing after you call render (unless you follow it with an explicit return), no more instance variables will get passed on to the view. It is obvious now why: a Rails request executes a given action in a controller. The controller executes before filters, executes the action, yields to whatever template has been defined (or searches for the automatic one if render has not been called). The view then yields back to the controller, which executes its after filters then back up through the middleware and out the door. (Ever notice if you try to yield between methods in a controller it wets the bed?) If you render before you’re done doing what you need to do, the controller has initialized the view template but keeps on executing controller code before yielding to it.

April 7, 2010 in Ruby on Rails, Uncategorized

Blue Red Conversation

A Facebook conversation worth repeating. The context is that I’m trying to understand why almost everyone I grew up with in Georgia, which I left 16 years ago and to which I have not returned, has gone way far to the right since I left. I went to college with the <Anonymous Conservative> in the early 90s.

<Anonymous Conservative> is very disapointed that the democrats are not going for a debt level of 100% GDP…
CBO report: Debt will rise to 90% of GDP – Washington Times
www.washingtontimes.com
President Obama’s fiscal 2011 budget will generate nearly $10 trillion in cumulative budget deficits over the next 10 years, $1.2 trillion more than the administration projected, and raise the federal debt to 90 percent of the nation’s economic output.
Sat at 8:49am · Comment · LikeUnlike · Share

<Me>
When the CBO reports that the current Health Care bill is budget neutral, it gets ignored, downplayed, or said to be “voodoo”, but when the CBO says that a proposed budget would balloon our debt more than Obama’s accountants think it would, then it’s news.

(Democrats don’t want to expand the debt either. They’re the ones in power so they have to … See Moretake responsibility for cleaning up the mess that W left him, while all the Republicans have to do is oppose everything, convince us that W wasn’t really a Republican, and blame the debt on the Democrats).
Sat at 10:16am ·

<Anonymous Conservative>
You will not find me defending W…I thought he was too much of a big spender…I blame him as well as all democrats for spending that is out of control…as a platform issue Republicans tend to favor smaller government; whereas Dem’s do not…
Sat at 11:28am

<Me>
Our government is representative of our people. Looking at the national debt data, what most struck me is that private debt is even more out of control. We need to fix the system, just my reading of history is that peole/corporations left to their own devices act beneficently for themselves but not for society.
Sat at 12:04pm ·

<Anonymous Conservative>
That’s where Christianity come in…
Sat at 3:34pm

<Me>
Yeah. Another lesson is that societies built on a prescribed ideology only survive through fear. I don’t want to live there – my wife grew up in one.
Sat at 7:34pm ·

<Me>
It sounded like you were suggesting chistianity come in in regulatory manner, rather than moral compass in civil society…
Sat at 8:19pm ·

<Anonymous Conservative>
ummm…how about both?
Sat at 10:46pm

<Me>
I’d much prefer the latter, and would refer you to Tehran or Riyadh for reasons to stay away from the former.
Sat at 11:45pm ·

<Anonymous Conservative>
True Christianity is tolerant of other religions because they (we) do not fear ungodly religions. So I would prefer to live in the U.S. which was founded as a Christian nation…Christianity cannot be compared to any flavor of Mohammadism…
Yesterday at 9:03am

<Me>
Then the problem must be that “True Christianity” is hidden somewhere, because the “Christianity” that is associated with conservatism, Republicans, and the Tea Party Movement is more motivated by fear than any political movement to come through America in a long long time.

Fear of the white middle class losing its dominance because of going bankrupt helping nonwhite people with unearned handouts.

Fear of the United States losing its dominance because of showing too much humility and giving the terrorists room to recoup and attack again…. See More

Fear of the so-called “liberal media” because of their increased likelihood to call a spade a spade. (Although this one has always baffled me, because liberals avoid mainstream media just as much if not more because of its rightward bias.)

Fear of intellectuals and preference for a leader they can talk football and converse with on a personal level, regardless of their fitness for running a country or even serving their real social and economic interests.

I’d have to turn it around and say that today’s fundamentalist uprising is almost entirely about fear.

Second, the point I was trying to make was that once you legislate religious law, you open yourself up to the panoply of questions you find in Islam. Which Christiniaity is the True flavor? Which laws do you pick, the ones that seem fair in 2010 or all of them? Will the Catholics get 40% of the choice, or will the Congregationalists and Unitarians have any say at all? Once you start making these choices and forcing the everybody else to get in line, you’re relying on coercion and “if you want to feed your family you will do this” rather than the true belief and liberation you were hoping to foster in the first place.

Lastly, Christianity can be compared to your pick of flavors of “Mohammedism”. Societies don’t operate in isolation from each other and according to different rules of social dynamics. People respond to the same pressures and respond within the coordinates of their individual culture.
Yesterday at 9:56am ·

<Anonymous Conservative>
Not buying that Republicans are the only ones that are motivated by fear. How about “Republicans want you to die quickly?” by demo. Grayson from FL…ummm sounds like fear to me…

As a conservative, I am to motivated by fear as much as expressing concern. The US Government has increased in size proportionally to the population since the founding…T or F?

Rightward bias in the media? Are you kidding me? Name the right leaning newspapers and cable channels and the left leaning ones? … See More

As far as “fear of intellectuals”, are you putting Obama in this category? I believe that leadership is a better quality…I do not put much faith in a man who speaks to elementary students using a teleprompter…

What’s wrong with football?

I am not in favor of legislative religious law…but most of our founding laws were based on Christian principles…no? The US survived just fine up to the 1950’s and 60’s with Christian principles until the breakdown in our morality i.e. Roe vs. Wade, so-called Women’s Movement, NAMBA, Jimmy Carter, double stuff oreo’s…

Depending on the government for more and more of your needs will yield less and less freedom…remember the ole hammer and sickle?
Yesterday at 9:26pm

<Me>
I would agree that there is a lot of fear all around. On the left, the fear that this is really our last chance to act on a host of pressing issues before calamity strikes, and that republicans not only don’t see it but also push in the opposite direction.

I would answer true to your question about government increasing in size, yes it has vastly increased in size proportionately to the population since 1776. However it is still half the size of your average industrialized nation. At #144 in terms of government spending as portion of GDP, we’ve got a long long way to go before we start to qualify as having a “big government”.

Re: media bias. Fox? I’d put NPR toward the left but you have to listen to stuff like Democracy Now or PRI before you’re really on the left…. See More

“Republicans want you to die quickly” is pretty minor compared to the flood of Republican fearmongering in the health care “debate”. “You lie!” “death panels” “Obama wants to kill grandma” etc etc etc.

Re: fear of intellectuals, yes Obama is in that category. If you think the teleprompters were there so Obama could speak to elementary school students, you are either very gullible or disingenuous.

Nothing is wrong with football. I was suggesting that the ability or desire to discuss it with you over beer is a poor criterion for selecting a leader.

I think we found out with W where leadership takes you when not combined with intellect. (Although I also think he played dumb so he could appeal to the same folks who like Palin today, meanwhile alienating the half of the country that wants a visibly intelligent leader.)

Our “founding laws” were not based on “Christian principles” as such. They were a marriage of English common law with Enlightenment principles, which were historically as much a reaction to traditional Christianity as “based on Christian principles”. The Founding Fathers were personally Deists and freemasons not “Christians” the way you think of it.

Moreover, I don’t think anyone doubts Jimmy Carter’s Christian principles, during his Presidency or otherwise. How is he responsible for a breakdown in morality? He took over a bum economy after a lost war and Watergate.

Maybe the “US survived just fine until the 50s and 60s on Christian values” statement is over the top? Do black people belong at the back of the bus, and women at home with the kids? (You mockingly refer to Roe v Wade and the “so-called Women’s Movement” after stating that we need to go back to the 50s…)

If Christian morality helps prevent social breakdown without causing oppression, go for it. I just don’t think you can count on it as a regulatory force if it isn’t law, and law it cannot be.

I do remember the ole hammer and sickle quite well. My wife grew up under it. I’ve spent quality time in a post communist country. However the idea that “more government” leads to the Soviet Union or even to 1950s and 1960s Great Britain is preposterous. Why do so many Americans think “more government” has to go that way, instead of, say, Germany or Canada?

And I am always puzzled about that in relation to health care. What American doesn’t look forward to when they qualify for Medicare? If you have health insurance, how much choice did you have in selecting it? You take what your company offers you, if they offer it. Where does the freedom lie?
10 hours ago ·

<Anonymous Conservative>
http://www.nowpublic.com/world/addressing-elementary-school-children-obama-uses-teleprompter
3 hours ago

<Anonymous Conservative>
Well I see that we see this country differently; I will not change your mind nor will you change mine…fun debate however…I strongly disagree with you that the founding fathers were not Christians…one can pull writing after writing about their referrence to God and Christ personal and professional…

Here’s a poll taken about media bias as viewed by viewers: http://www.mrc.org/biasalert/2009/20091005025345.aspx

Enjoy your Monday …
3 hours ago

<Me>
Everyone saw the stories about the teleprompter, I was saying that afterward the right wing blogosphere became excited about it, it became clear that they were not there because of the students, but for a talk to reporters afterward. Then the jeering switched to why he needed a teleprompter to talk to reporters. As to how that makes Obama unintelligent or a mindless automaton, I’m not sure. I’d say it’s more a case of confirmation bias.

On the next point, I wasn’t saying that the founding fathers weren’t Christians, but that they were not Christians in the sense that Christianity means to you. The Enlightenment and English common law were more important for the founding laws, and the idea that they were forming a nation founded on self-evidently rational *law* that didn’t require some mystical-mythical-religious or personal-as-in-king-george basis to uphold or justify it. That’s one of the reasons it is so durable.

It became clear quite some time ago that we see the country differently, and that it isn’t about changing minds. That is unlikely to happen in a Facebook convo after 15 years. … See More

I’m trying to figure out why almost everyone I know from Georgia has become way more right wing and religious than they were when I last lived there in 1994, and at least understand where you guys are coming from.

In any case, enjoy your Monday. It is Monday for all of us.

March 29, 2010 in Life

Can Coding Standards Be Enforced Programmatically?

We’ll find out. Saw this today, can’t wait to give it a try:

http://github.com/flyerhzm/rails_best_practices

A program that checks your Rails code against the “best practices”.

January 7, 2010 in Ruby on Rails

DVD Burning Woes on MacBook Pro Solved Happily

“The disc can’t be burned, because the device failed to calibrate the laser power level for this media.”

This error plagued me on my 2007 model MacBook Pro until I realized I had bought DVD+R discs. When I tried DVD-R, it worked fine.

January 3, 2010 in Uncategorized

Event scoping with jQuery in OOP: Controlling the value of ‘this’

One of the things I have always liked about jQuery since I first started using it is how easy it is to bind events to elements, and have easy access to the bound elements via “this”. However, when you start programming object oriented JavaScript, you lose access to the object’s “this” unless you use closure:

var self = this;
$('#special_link').click(function(){
  if (self.editing) {
    // do something special
  }
}

Other frameworks such as ExtJS and Mootools allow you to specify the scope of an event handler. JQuery does not. I thought that was a drawback until I figured out that they allow for it in a way that gives the best of both worlds:

$('#special_link').bind('click', {self:this}, this.onClick}
...
onClick: function(e){
  var self = e.data.self;
  // this = the element that was clicked
}

This way you have both the element that was clicked and the object whose scope you wanted. On the other hand, it means you’ll have to be mindful of what “this” and “self” refer to throughout your code.

That’s a price I can pay for now…

December 30, 2009 in JavaScript

Javascript Templates

Just found John Resig’s javascript templating engine, even though it’s been around a while:
http://ejohn.org/blog/javascript-micro-templating/

November 20, 2009 in JavaScript