Friday, February 07, 2014

Dart: I'm probably doing it wrong...

...but it feels pretty good.

This file exists purely so that I can write code like this:

   AnimationBuilder.on(entity)
      ..animate('foo1', 1000)
      ..animate('foo2', 1000);

Instead of:

    new AnimationBuilder(entity)
      ..animate('foo1', 1000)
      ..animate('foo2', 1000)

Or, without the 'DSL wrapper' entirely:

   var ani = new Animation();
   ani.animationSteps.add(new AnimationStep('foo1', 1000));
   ani.animationSteps.add(new AnimationStep('foo2', 1000));


If I could have actually have a function called 'AnimationBuilder' that would call "new AnimationBuilder" under the hood, that would have been even better. The Nokogiri gem for Ruby does this: there's a class called Nokogiri and a function called Nokogiri. The function calls the class, so you can write code like "Nokogiri(xml_content).foo.bar" and just Get It Done.

I am kind of a stickler for these aesthetics issues. I want my code to look good, because it's 2014 and programming is still text-based and I have to be the one staring at the result for 8 hours a day. It doesn't matter that there is literally no savings in terms of characters: the code reads more naturally with the 'DSL' so that's what I went with. That third block of code is simply not an option, but I included it anyway because I actually wrote it once before I recoiled and said "nope" and introduced AnimationBuilder.

I'm probably dragging some of my Rubyisms into Dart, but I figure I'm an odd duck out anyway (everyone seems to be coming to Dart from C# or Java), so whatever.

Gotta have fun, or why code at all?

Monday, January 27, 2014

Half a year with Dart.

So I've been fiddle-fucking around with Dart for about half a year now. I've used it for some internal stuff, and a small open source project.

Pros:

Flexible problem solving: Aside from executing arbitrary code at top-level and serious metaprogramming (both of which I sorely miss, coming from Ruby), Dart is a very flexible language. It embraces type inference, closures, top-level methods instead of one liner abstract classes. You're not going to find any amazing stuff like RSpec, Rake, or the Rails Router coming to Dart, though: the language is simply not that flexible. But if metaprogramming / DSLs / etc aren't your thing, Dart kinda lets you barrel through.

Structured ecosystem: Dart has its own package manager, coding conventions, baked in "dartdoc" comments-as-documentation -- all the things you'd expect of a 2014 language. JS is still waffling: RequireJS or CommonJS or AMD? Bower for the client, npm for the server, and you sure as fuck aren't going to be using a single package from either source for both frontend and backend dev.

It's fast: this and the clean syntax is ultimately why I chose it for a project over JavaScript. If the mythical ES6 or Harmony had shown up that day, I would have used that instead: decent performance, more flexibility, and a clean syntax would have won out over Dart's great performance and syntax.

ES6 is Java's Project Lambda: it'll arrive several years late and JavaScript devs are going to have an aneurism when they see what the module syntax looks like.

Batteries included: they packaged pretty much everything you need to get running quickly.

Cons:

The library / parts syntax: the way Dart handles including files in a library is very bizarre. The library declaration is straight-forward: `library foo;` in your library file. Simple right? You also have to specify that a file is part of a library, too; that's fine: `part of foo;`.

Off to the races, right? Wrong. Because you have to go back to the library file again, and then add `part 'filename.dart'` as well. For every file in your project.



This is obviously for the compiler's benefit, because any human being wanting to know what file belongs to what project would just look at the source tree on the file system, like every other sane language on the planet.

This is flexibility without convenience.  You have flexibility in that you can, if having downed a six pack and are now in a drunken stupor, mix several different libraries and their implementation files in one directory and make out OK.

But you don't have the convenience of declaring all files in a directory to be part of your library, even though that's what 99% of how everyone everywhere lays out their source tree.

It's good to be flexible, but it's bad to be inconvenient.

Mirrors API: Mirrors are analogous to C#'s reflections API and Java probably has something similar. There's not a lot of affordance in the API: using `dart:mirrors` means you are going to be writing a lot of code unless you are using it at its most base, simple level.

No generators: Dart doesn't have generators, so List(...).where(...).map(...), is two iterations over a list; if your "where" returns every item in the list, you've done O(N) twice: once for the where, then once again for the map.

For a language trying to be fast, this is a weird oversight since List is heavily used (and expected to be heavily used) in public APIs everywhere.

UPDATE: Dart actually gets around this by using lazy iterables: where() returns a lazy iterable, and map() returns a lazy iterable based on the previous iterable. Thanks to +Lasse in the comments for pointing this out.

"The Editor Will Do It": Dart relies heavily on using an editor of some kind. The Dart Editor is great for starting, but its weaknesses show when you move beyond 1-2 files for a project: there's no built-in keyboard-based navigation, no source control integration, no syntax highlighting support / integration for LESS or SASS or HAML or Slim or any of the popular templating languages -- despite being built on the Eclipse platform.

A plugin exists for Eclipse, but it feels like a red-headed stepchild. I finally figured out how to import the files of an existing Dart project into my workspace by creating a "new" Dart project; when it asked me for the "project name" I just put the directory the existing files were located in, and walla, fooled the IDE I guess.

I have a licensed copy for RubyMine, and thus can use the Dart plugin, but it needs serious love.  It's obvious whoever is developing that plugin has never used it for anything other than ensuring the plugin seems to work.

Maybe it's just me, but having to stop coding and mouse around clicking the '+'s and '-'s on a file picker to find the file I want consumes an inordinate amount of time and makes it hard to keep track of what I was doing. CTRL+SHIFT+R and done, son.

In the end, Dart is still a respectable development choice. With ES6 being god knows where, doing god knows what, with god only knows how long until you can actually "use" it, Dart is a strong contender as long as you don't need that JS magic.

But goddamn do I want to use a Light Table supported language.

Wednesday, January 15, 2014

oDesk and eLance

I followed news of the oDesk and eLance merger with trepidation. So far, lots of "for nows" when it comes to whether oDesk will change.

Personally, as long as they remain two separate business entities, I'm not concerned. The whole "client quality" kerfuffle everyone wants to keep starting is meaningless: there is nothing inherent to eLance OR oDesk that keeps crappy clients out. For all the flamey trollbaiting, I just checked my eLance account (I have an account on all the major freelancing sites), and I see your typical lunatics pitching insane projects for a pittance, same as oDesk:

This post is for software engineer that already completed successfully an exchange for bitcoin and other cryptocurrencies.
Anyone thinking that one freelancing platform is an asylum and the other isn't is drinking some serious kool-aid. The entire "client quality" issues stem from the self-serve nature of freelancing platforms in general: without another human to say, "Hey, this is crazy and way out of your budget" what you sometimes get are clients who are projecting their hopes and dreams instead of realistic job proposals. That will never change.

All things being equal, ultimately platform preference comes down to usability and features.

Personally, I use oDesk for the simple fee structure: you get paid, oDesk gets paid. No worry about membership levels and the restrictions based on membership level. That makes oDesk's focus laser-tight on connecting freelancers and clients, and for me that's a perfect combination.

Sunday, December 29, 2013

Bitcoins and MMORPGs.

I've been mulling over this question awhile now:

How do you make a free to play MMORPG that is not driven by a cash shop but is still sustainable as a business. In other words, how do you make a "clean" game in which no gameplay decisions are driven by the concept of microtransactions?

When gameplay decisions have to factor in the business side, the game inevitably suffers: see a million generic Korean grindfests where the only way to escape the monotony and get to the action is to pay for items. Very few games seem to escape this fate. The fewer players there are, the more expensive and disruptive items have to be in order to be profitable. The more players there are, the less items have to be disruptive -- the free to play community at large won't want to deal with players who "boosted" their way to the top but have no idea how to play the game.

But what if you designed a system where every player paid to play your game, but invisibly, in the background, with no effort and cash required?

Bitcoin!

It came to me a few hours ago as I was mulling over some game concepts. A minimalistic survival game, with no real UI to speak of, no macros or quest hubs. The game is its own user interface, similar to how Dead Space handled inventory management: every interaction you had with your inventory was part of the game. Nothing stopped, the world kept running as you fumbled through your equipment while the lights in the hallway ticked off one by one and the howl of monsters got closer and closer.

In a game like that, you can't have cash shops. Can you imagine walking up to an NPC vendor in the game, talking, then clicking through some immersion breaking dialogs to click through an immersion breaking gateway in order to buy some credits for $5 that will help you cut down trees faster, all because the tree-felling portion of the game was made more grindy to encourage players to buy something to cut down trees faster?

To me, it seemed like the only real option for sustaining a game like this was a subscription, which may as well make the game stillborn. The time of subscription-based games is over. WoW has sucked the air out of the room in that regard.

But I was browsing /r/bitcoin earlier, not even sure how I got there, but just passing the time when it hit me:

What if your users mined bitcoins for you while they played the game?

Their computers provide labor in exchange for being able to access and play your MMO*. In that sense, the concept of a subscription-based MMO* can survive through cryptocurrencies. You receive a currency (Bitcoin, Litecoin, even Dogecoin) while the user themselves put no tangible effort giving that currency to you.

It seems too perfect. For end-users, the entire thing is seamless: they turn on the game, they play, they turn it off. For you, you get paid when your players are playing. If you have a love of games, this is Heaven: the more fun you make your game, the more users you get, the more money you get. You never have to compromise your vision of fun in order to make money, because a fun game that people like to play is metaphorically a "gold" (Bitcoin!) mine.

It's a crazy thought, but it does make me wonder...

Wednesday, April 03, 2013

JRuby on Heroku? Bah, humbug.

My experiments with JRuby on Heroku have mostly been a bust.

I migrated a fairly simple 2.0.0 application over to JRuby, which didn't involve much other than switching to Kramdown from RedCarpet 2, and spending some time fucking around with my `database.yml` so the `activerecord-jdbc-postgresql` gem would actually connect.

But goddamn, the problems.

I let the JRuby 1.7.3 version of the application run for a little less than 24 hours, and in that time I got:

* about 6 hours of downtime spread sporadically throughout the period
* four or five "memory quota exceeded" at peak time, which didn't seem to do anything
* several random dyno crashes I wasn't seeing under Ruby 2.0.0, which were followed by...
* ...many, many "boot timeout" errors, which I never saw under 2.0.0 unless I had a bad configuration / initializer that was causing the app to crash

And those are just the critical errors. Performance across the board was crap: the New Relic comparisons from last week versus the switch to JRuby were pretty bad looking. Lots of request timeouts. Lots of request timeouts. And request throughput was apparently crap.

That last thing -- throughput -- bothers me almost as much as the random crits above. The setup is running puma, a threadsafe web server for Rack, so I was expecting to see much better request throughput than what I actually got. For those of you not in the know, JRuby has "real" threading, where-as Ruby MRI has a GIL and green threads, which means threading performance is not very good.

Switching to JRuby should have given me a real boost in throughput, but, unexpectedly, performance was piss-poor and there was a significant increase of request timeouts. The site's not getting _that_ much traffic, and the assets are stored on Cloudfront, so...

I don't have any idea what to make of this. Apparently the setup is working well for others (I don't see any complaints on Google, at least). But with such a simple setup on Heroku going sideways, I'm not sure what to make of it. Is it a bug in JRuby 1.7.3? A Heroku-specific problem?

Meh. I've redeployed on MRI, and the numbers are turning back to normal.

That concludes that experiment.

UPDATE 4/4/2013:

For curiosity's sake, I ended up chasing the source of the downtime to a bug in Kramdown not being able to deal with some erratically formatted content. The code doesn't throw an exception, it just... hangs, I guess. New Relic reports a ridiculously long runtime of 1.5 million milliseconds, but I'm not sure if that's because it actually takes that long to render, or something (probably Herkou) killed the process, and that's just how long it took. RedCarpet has no problems with the markdown in question, which explains why I wasn't seeing any problems before the switch to JRuby.

Monday, February 18, 2013

OS X 10.8 vs...

Fedora 18 / Gnome 3.6

Gnome 3.6 is very, very nice. It's not as refined as OS X yet, but you can see the Gnome team clearly closing the gap. The new lock screen is very nice and polished. Utilizing work-spaces is a snap. Gnome 3.6 has a very distinct, appealing style: once you open an application, there is little to no clutter. All you have is your app and the top bar showing you vital system information (battery life, wifi status, etc).

The user interface is where the polish ends. As you'd expect if you've used any non-Ubuntu Linux distribution in the past few years, installing and updating applications is terrible. The built in method of installing applications from Fedora's repositories is awful; application packages (RPMs) you download from major vendors like Google (Google Chrome) have to be installed from the command line.

It's unfortunate such a pleasant user experience like Gnome 3.6 attached to an unpleasant way of managing applications.

Ubuntu 12.10 / Unity

Unity feels like a kind of forgotten Frankenstein's monster. HUD, the system for quickly selecting items in an application's menu, only works sometimes. The global menu bar suffers the same schizophrenia, leaving you with an overall inconsistent experience. When they work, they work beautifully. When they don't... well, meh.

The dash is nice and responsive, but often the search results hit the barn wall. Dash draws in search results from websites like Amazon.com, cluttering search results with unrelated items: searching for "photo" brings up Shotwell Photo Manager, as well as Birds of Prey, Kindle Fire HD, and what literally looks like a pornographic video. ... okay, no, it's apparently a smutty adult novel with a risque' cover. Still, not exactly what I was looking for, and definitely not what I want anyone to see if they're looking over my shoulder.

Installing applications is nice and straight-forward: the Ubuntu Software Center is a little sluggish, but search results are easy to browse. Installing applications from the Internet -- Google Chrome, Scrivener for Linux -- is straight-forward and very painless.

Unity needs a lot of shine, but seems promising.

Errata

Some things I really like about OS X that have no Unity / Gnome 3.6 parallel.

 * The Command button. I didn't understand how great this single button was until I started using it. Mac's have the standard Alt and Ctrl buttons, but the Command button is the primary modifier for interacting with applications. Command C always copies, Command V always pastes. Command W always closes a window, and Command T always creates a new tab. And because these keystrokes are divorced from the Ctrl key,  you can actually copy and paste inside of a terminal window exactly the same as you'd copy and paste from a GUI application. The uniformity is great.

* Built-in gestures. You can summon application window overviews with a simple swipe, move between windows, open the notification panel, pinch and zoom... gestures don't feel like a tacked on feature. If Unity or Gnome 3 have a similar feature, they're hard to discover. OS X told me straight up during the setup procedure how to use the mulit-touch gestures.

* Coherent animations. When you download a file from Safari, the file's icon goes flying into the "downloads stack." When you minimize an application, you watch it disappear to its place on the dock. There's never any question of where a window went or a button just did. Most things in OS X have a nice, smooth animation that visually elaborates. It's thoughtful.

Tuesday, February 05, 2013

Ruby: Ensure blocks can alter flow control!

This one bit me -- I've only found it documented in one place, here, but I also discovered the behavior after debugging a strange problem I was having with some command line processes not exiting properly when they received the exit command.

Basically, if you exit from an ensure block with "return" it behaves the same as if you had done a "rescue Exception" statement, which means it swallows up all exceptions, including exceptions raised to terminate the Ruby process when it receives SIGTERM, SIGQUIT, SIGINT, etc.

Sunday, September 16, 2012

FTL isn't a Roguelike -- or if it is, its a very bad one.

FTL was just released this week -- it's the space ship management game where you cut a swathe of destruction across the galaxy because something bigger and badder than you is doing just the same, nipping on your heels the entire time.

The game is pretty simple: you got crew inside your tiny tin-can cruising the galaxy. You got weapons, you got shields. You got systems the enemy can target on your ship to disable your shields, life support, steering, and you can do the same thing to them.

It sounds like fun, and it is, for awhile.

It purports itself to be a roguelike though, and that just ain't so. It is entirely too random to be a roguelike. In a roguelike, when you die, there's that moment where you go, "Why did I do that?"

You ask yourself "why did I do that?" because you understand that your character's death was totally avoidable. You could have checked the room you just entered more thoroughly. Maybe you were distracted and were just mashing one of the direction buttons, and your character walked over a trap or fell into a barely noticeable crevice to his doom. You could have totally looked at the frost giant in that next room (the one that killed you with one shot), decided you weren't ready, then turned around and went looking for better equipment, or a way around. Or maybe you just had to drink that unidentified potion because you are a freakin' lush and can't stop rolling the dice with your intestines on the line. In a roguelike, death sucks, but you did it to yourself, so while it is annoying, it rarely becomes too frustrating, because "how can I avoid that next time?" immediately follows. That's where some of the fun is.

FTL is the exact opposite of that. The game can and will literally set you up to fail; it is unavoidable and incredibly unfun. I'll go as far as to say that the game is more frustrating than fun once the charm wears off -- there is nothing like canting your head to side, staring at the screen and muttering "wtf?" because in the second sector you ran across an enemy that has 3 shields -- and you only have enough weapons power to fire 3 laser shots at a time. The game is structured in a way that you are either lucky or you are not. If you are lucky, you will come across some weak enemies, get some missiles and "drone" weaponry early on. If you are unlucky, you will barely scrape along, if you survive at all.

And barely scraping along is meaningless, as I found out the first time I made it the boss.

The boss had four shields, a laser cannon, a beam cannon, and something that fired at least 3 missiles every volley. I had four lasers shots a volley, an empty missile launcher, and a beam weapon that doesn't work if shields are up.

Despite the enemy ship being the size of a small planet, if I missed even /one/ laser shot, it would be impossible for me to damage the boss ship at all -- in FTL shields regenerate a few seconds after they've been depleted, leaving you with a very narrow opening. So in one volley you absolutely need to knock down all four shields with all four shots, or else you'll have to wait another 15 seconds to try again. If you miss one its a meaningless gesture; you can't damage the hull, so you can't destroy the ship.

So of course that's what happened: the game, having decided I would fail early on, let me struggle through to this last moment, where it put me in front of an enemy I had no way of beating.

You can only visit a handful of planets in a sector before the enemy armada starts blocking off the left side of the map, encroaching ever closer to your current position., You don't have the choice of sticking around and trying to scrap together as much "scrap" as you can get to afford new weaponry and crew members; you are either lucky, and on the journey to the sector's exit you got some easy scrap and nice weapons, or you are unlucky, in which case you will be unable to achieve victory.

Once I realized how the core of the game worked, I would be a few sectors in, less than halfway to the final showdown, and I'd look at the state of my ship and go "I'm not going to make it to the end." It's a realization that sucks the life out of the game, because there's nothing you can do to correct your course. You're screwed.

For a $9 game, I guess it was worth the 6 or so hours I got out of it, though.

Saturday, September 08, 2012

Boobytrap your Monkey Patches!

If you are going to override an entire method with a monkey patch, at least do this:

raise "Make sure I'm still required!" unless Gem.loaded_specs["GEM_NAME"].version.to_s == "VERSION_THAT_REQUIRED_PATCH"

somewhere inside the file that does the monkey patching. Consider it a courtesy for everyone else, including yourself.

...

Okay, so I spent about 7 hours fiddle-fucking around with an inexplicable circumstance that came down to someone monkey patching an entire goddamn class by copying and pasting the Git HEAD version of that class so that an older version of the gem could use some of the newer version's functionality. Of course, 10 months later the underlying gem got upgraded way past the version the monkey patch came from, so a whole subset of functionality just broke "like magic!"

Devise: Logging in a user from a custom controller.

"Devise is a nightmare I have suffered only for the shining jewel called Omniauth clutched jealously within its thorny tentacles." -- a wild Arron under the influence of several frappucinos.


If you want to log in a user from a custom controller in Omniauth, this is your only hope:

user_params = params[:user] || {}

user = User.find_by_username(user_params[:username]) || User.find_by_email(user_params[:email])

if user && user.valid_password?(user_params[:password])
  sign_in :user, user
else
  # destroy the world.
end

 


You're probably thinking, "Can't I use warden.authenticate and cut down on the code and not have to do that nasty || at the beginning?"

No. See this question on StackOverflow for an explanation, but the short version is Devise doesn't want you to be able to use warden.authenticate anywhere outside of Devise::SessionController derived classes. Hilariously, if you go trolling for information on warden.authenticate you will find mostly unreplied to threads in Devise's Google Group, which is too many capitalized words in a row. If Google is a verb, can I refer to its products in lower case as well?

Goddamn. Does anyone remember Authlogic?

User#authenticate anywhere you wanted and you were fucking done, son. Yeah, Authlogic doesn't (or didn't) come with pre-built views like Clearance or Devise, which probably had a hand in it falling out of favor, but still, it was simple and almost impossible to screw up.

Theoretically you can get Omniauth up and running with anything, really, including Authlogic, but realistically setting up Facebook / Twitter login with Devise + Omniauth takes only seconds, and by the time you are screaming obscenities at your IDE it's too late to use anything else, assuming you even could -- I'm seeing that a lot of nifty stuff like rails_admin uses Devise under the hood.

Still hate the shit out of Devise for custom stuff, though.

That's right, hate. I am a mean coder. Rawr. Rawr!

Get out of here. Shoo.

Sunday, July 29, 2012

The Tablet Interface is coming to a PC near you: Thank God!

I absolutely cannot wait until tablet interfaces come to every operating system. I just spent the last 2 hours watching my mom fumble through Windows 7 shitty interface as I taught her how to copy files from "My Pictures" to "Dropbox."

I'm not even going to go into the whole "oh fuck, which cloud service do I tell her to use so she can easily back up her important photos" conversation I had in my head for like 10 minutes before that. On the desktop, all experiences are equally shitty; it ultimately came down to a matter of, "which service provided least friction."

It was Dropbox, of course; they ask for your name, an email address, and a password and then you're off to the races. She could manage that part on her own. Navigating through the files was a total pain, though, and I realized just how idiotic file manager interfaces are for regular every day computing. I mean, I'm a programmer, so I'm used to stuff being designed-by-stupid, but watching someone else struggle with these kinds of basic computing tasks is eye-opening.

The experience with Android + Dropbox is much easier. Smooth, intuitive for even someone who has no idea what they're doing.

Right then I realized that despite all the bitching about tablet interfaces, they do the Unix philosophy just right.

Each app does one thing, but each app does that one thing very, very well.

The Dropbox app? It lets you view and upload your Dropbox files. In a few clicks any file you want is uploaded or downloaded. It's that easy.

And, much like Unix pipes, integration is everywhere: anything that uses the standard "share" mechanism on Android can send a file to Dropbox. And Dropbox can send those files back using the "share" mechanism.

Tablet / Mobile interfaces like Android 4.0 are probably the best thing to happen in computing since... I don't know. All time?

I cannot wait until tablet interfaces come to PCs. Most of the savvy dudes and dudettes are going to turn them off because we need to get at the technical shit, but for everyone else? Kiss going over to your neighbors to show them how to send a file to their friend goodbye.

Friday, May 25, 2012

KittyCaptcha works!

So, I've got a site I've got some problems keeping spam out of. I integrated with Akismet, which hits the barn wall as far as this site is concerned, and I also do a little bit of heuristics, based on poster location, amount of links / keywords in a particular piece of content, etc.

Akismet catches a lot of valid content as spam, so every few days I go through the spam bucket via the admin console and blindly white-list anything that doesn't look like spam. That was working OK for awhile.

Anyway, a few days ago I look and see that there are 163 identical bits of content, all of which completely skirted Akismet. Genius. It was obviously a bot. Now, part of this problem was that I had previously removed reCaptcha a few days ago as usability wise its terrible, and I actually failed a few of the reCaptcha tests myself because the scrambled words it presents are almost impossible to read these days.

So I figure, "Akismet will catch most everything, why use a captcha?"

As it turns out Akismet seems to catch very little, even when I'm marking items as spam. Even when things are *obviously* spam -- several dozen links, incredibly high keyword density -- it just completely misses the mark.

I rack my brain.

HashCash? No good implementation details, plus the concept hasn't been proved yet anywhere.
Simple math captchas? I hate math.

Then I remember way back when. A few years ago, people were talking about Microsoft Research's Assira and some random dude's KittenAuth. Neither caught on: Assira has good image breadth but looks like crap, and KittenAuth isn't very detailed regarding its implementation. Back then I initially dismissed it as a fruitless endeavor: where would you even get a large assortment of kitten pictures from? You'd have to partner with someone like Microsoft or come up with your own small batch of images that would quickly be "solved" by a human being paid 10 cents an hour.

But that was a long time ago. Now we've got Flickr, Instagram, Google Image Search. I have all the Internet's random kitten pictures at my disposal. I just need to use them to their fullest, cutest effect.

So I dig around, study some techniques on form signing with encryption, how to avoid replay attacks -- cracking the captcha once, by hand, then using it to resubmit over and over and over again ... -- and about 2 hours later I have a simple but adorable KittyCaptcha.

I deployed it into production last night, and haven't had a single drop of automated spam almost 24 hours later. Regular content is flowing through quite nicely.

This was a pretty poorly written post, I realize, but it's mostly stream of consciousness and I can't be bothered to go back and edit anything.

Friday, October 28, 2011

accepts_nested_attributes_for, belongs_to, and has_many#build

There's a self-explainatory code sample before.

Basically, if you have accepts_nested_attributes_for on a belongs_to relation, you can't use model.has_many_relationship.build params[:has_many_relationship] -- Rails bugs out.

This is because, AFAIK, model.has_many_relationship.build params[:has_many_relationship]

assigns params[:has_many_relationship] first, BEFORE assigning the foreign keys that link the relationship with the model.

Code:


class User < ActiveRecord::Base
has_many :papers
end

class Paper < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end



class PagesController
def create
# The below line FAILS;
# current_user.papers.build params[:paper]
paper = current_user.papers.build
paper.attribute
end
end


"current_user.papers.build params[:paper]" does this under the hood:

# this triggers accepts_nested_attributes_for, when user_id is currently blank, so it will fail.
Paper.new params[:paper]
Paper.user_id = current_user.id # too little, too late!

Wednesday, August 10, 2011

"What do you think of Cloud9 IDE?"

I think it'll fail.

Cloud9 IDE is bills itself as "development-as-a-service", but it's really just a web-based editor with some built-in support for running Node.js applications. Don't get me wrong, it's a really good web-based editor, but alone isn't going to cut it.

I mean, sure, you can run Node.js... but what about Ruby? Python? PHP? Yeah, you can edit the files, but what good is that without being able to test those changes? Deploy them to a staging server? Production? Run your project's test suites?

Frankly, I think they're got the right idea but the wrong product.

I think they should be selling a "Cloud9 DE" -- a cloud-based development environment.

Let me tell you a story about an old, old Rails project I worked on. It was a popular site -- had millions of visitors a month -- but it was built using the 0.x series of Rails. Old as dirt. Development on it had started way before we got sweet things like Bundler, a more robust Rubygems, etc. And that was reflected in the codebase and some of the hand-written C libraries we had to use to hook into system libraries, etc.

In fact...

It was so damn old and brittle that we couldn't get a local copy running, for any of the developers. Instead, what Our Glorious Leader decided was that he would make copies of the actual production instance running on EC2, scrub the database, and then spin up an EC2 instance with these modified images for each developer.

We worked through SSH, mainly using Vim or Nano, but I actually got some "SSH filesystem" deal going on Ubuntu (can't remember, FUSE?) and could edit my files using Gedit and etc.

It was awful, fucking awful, let me tell you. A completely miserable experience. But if the code weren't such shit, and the concept had been fleshed out just a little more...

So, interlude over, and back to the topic at hand: Cloud9 IDE is the right idea, wrong product.

I think they should be selling remote development environments -- prepackaged Amazon EC2 images, spun up and down on demand, billed by the minute and ready to go for whenever you need to start hacking.

One click should get me a prepackaged EC2 instance ready for the latest Ruby on Rails development, and one more should get me a public (or private) Git repo checked out and ready for development on that EC2 instance.

You'll always get a clean system for every project. Don't run MySQL/etc in the background if this project doesn't need it.

You'll always have SSH access, so if you need to do some tooling around in that project's instance, no problem. Need to run tests, or some other custom shell command? No problem.

You'll always have access to your development machine, no matter where you are, via the Cloud9 IDE itself. Don't like the interface? Mount the filesystem using FUSE and hack the code with your favorite IDE.

Taking it one step further, let teams create their own prepackaged developer images so that getting a new developer set up is as simple as adding him to a team in the Cloud9 IDE. Now you're suddenly measuring developer set up time in minutes.

That's valuable. That's worth money.

A web-based editor for $14.99/mo? No.

Remote development environments like the one above ~$60/mo? Hell yes.

Thursday, May 26, 2011

oDesk WTFs

Applicants that:
  • Apply to a job, but state very clearly when asked that they have no experience in the relevant technology and have no intention of learning the required technology
  • Apply to a job, but state that they have no intention of finishing the project within the alloted budget
  • Apply to a job, beg for a chance, then completely ignore instructions and try to sell you some half-baked CMS they had developed for another client

Sunday, May 15, 2011

Ubuntu v. Fedora

WTF.

So many bugs in Ubuntu 11.04, all of them with Unity.

  • Crazy graphical errors that make it impossible to work (I mean that literally),
  • Unity steals title bars at random so I can't can't drag some title bars for dialogs or windows,
  • the global menu steals some (SOME) of the menu bars in Eclipse, but not others, leaving me in a fucked up wasteland of not being able to access functionality without knowing the keyboard shortcut,
  • Unity decides that no, it does not need to hide at the moment, and there's nothing you can do about it, so the leftmost 50ish pixels of my applications are completely inaccessible,
All this shit for a dock that doesn't do anything yet.

Fedora 15 works like a dream on my laptop, no weird errors or anything like what Unity's been boning me with. I'm looking into exactly what it would take to migrate my development machines from Ubuntu 11.04 to Fedora 15.

The only alternative is to wait 6 months and *hope* Unity stops being so goddamn buggy. I want to like it, but Unity seems less like a product and more of a promise of what could be.

Saturday, April 30, 2011

UJS drivers (rails.js / jquery-ujs.js) -- load them LAST.

Don't load your UJS driver (rails.js or jquery-ujs.js) before your application logic JavaScript.



Why? Because your UJS driver is going to hook into the submission events for ajax elements. If you need to run a validation (or anything like it) that has to be executed BEFORE form submission occurs, because it may cancel the submission event, you need to have that code hook into the submission events before your UJS driver does.

Therefore, load your UJS driver last.

Friday, April 08, 2011

Mint.com is pretty awful now.

Mint sucks. What happened? After Intuit bought them, they added support for one of my previously unlisted banks, but then almost immediately all four Bank of America accounts I had inputted stopped updating.

And just awhile ago, my Prosper account stopped updating.

So now I have:

* a PayPal account I get non-stop "low balance" warnings for, even though the balance hasn't changed in over a year,
* a car note account that doesn't show my remaining balance,
* An Ally CD,
* and one bank account.


The most hilarious moment of this has to be that today I got an email from Mint, claiming that they've improved their back-end so now they don't talk to a 3rd party any more to get your bank updates: they connect directly to the financial institutions instead. Too bad connecting directly with the banks is apparently less robust than connecting through that 3rd party, am-i-rite?

Runner up for most hilarious moment: Mint claims that you have to turn off all (ALL) of Bank of America's three-factor security mechanisms in order for Mint to work, because they're "unsupported." I have an account with another bank that updates perfectly fine via Mint, and it uses the same three-factor security that Bank of America does.

It's unfortunate that Wesabe and the rest of them died off so quickly; they probably could have used this moment to start picking up customers as they drop off of Mint.

There is no way I'm turning off any bank's additional security. I've already had my identity thiefed twice (caught by the bank both times before they did any real damage), I am not making it easier for someone to ninja my bank account, because, you know, there is MONEY IN THEM THERE ACCOUNTS.

Wednesday, April 06, 2011

Making Jammit jam with Heroku

So, you want to use Heroku and Jammit together, and you've come here of all places! I know, there's no good solution for this floating around The Interwebs, so I figured one out myself, and now I'm publishing so that you, YOU THE VIEWER, can be both shocked and amazed.

There's a nicely formatted gist right here, or you can read it inline below:





Yes, that large hack floating around in the middle is specifically for Heroku. If you're on another cloud service that is a little less wizardly, you can drop the class_eval block entirely and you should be good to go.

If you're wondering if the resultant files will be cached by Heroku's Varnish HTTP accelerator: yes. Rack::Static will return the fetched files as Rack::File objects, which Heroku caches.



UPDATE: if it's not obvious, this needs to go into config/initializers -- so it runs once on app start up.

Monday, March 21, 2011

Ubuntu --> openSuse --> Fedora --> Ubuntu

Last night:

Installed openSuse on my laptop, overwriting my Ubuntu Natty install. Installer is laggy. Doesn't have the firmware for my wireless. Can't get the gnome shell setup script to work without modification. Gnome Shell build fails anyway. Can't get wireless drivers installed. Give up.

Install Fedora 15. Install is clumsy and demands internet connection. It detects wireless, but won't activate it. Installer allows me to continue anyway. I end up at a strangely themed Gnome 2 desktop. I dig out a wireless USB adapter and start the install over. This time, I end up with Gnome Shell. Looks good. Nice performance. Oh, nice security update notification. Start installing updates. Screen suddenly fades as I'm surfing web. The screen is locked, asking for a password. Mouse works, keyboard doesn't. I let the updates go for an hour; when I come back, keyboard works again. I play around a little, then restart. Can't get past Fedora's boot splash.

Wait an hour, then install Ubuntu. Cant detect wireless at first. Nothing bad happens, and on first boot it asks if I want to enable my wireless. I do. It works. It rebooted fine.

All I wanted to do was use Gnome Shell, but if it isn't available for Ubuntu, its gonna be a problem.