Rails: cleaner partials in forms

Damian pointed me to the patch ELC Technologies committed to Rails.

As he mentions previously you did something like

<% form_for(@client) do |f| %>
    <%= render :partial => 'form', :locals => {:f => f} %>
    <%= submit_tag 'Create' %>
<% end %>

but now you can just do…

<% form_for(@client) do |f| %>
    <%= render :partial => f %>
    <%= submit_tag 'Create' %>
<% end %>

Cleaner and more intuitive, nice!

So I’d say Apple pretty much killed it today

And by ‘it’ I mean Blockbuster (and possibly Netflix but they’re a bit more agile). If weren’t one of the gazillion people hitting on the Engadget and Gizmodo live blogs Apple released a bunch of new shise today.

The MacBook Air will get most of the attention but I think Movie Rentals is a bigger deal because it revives the Apple TV as their stake in the living room. Think of all the companies that had (have) an in but have funked it up, Microsoft and Sony have the XBox and PS3, and were so preoccupied with the blue-ray HDDVD war they didn’t even think of adding a Movie Rental service into their boxes. If any one at Blockbuster had half a clue they would have been begging Microsoft/Sony to help them deliver movies over the net and into a gaming box. Instead Blockbuster can only see Netflix as its main competitor and copies their service while Apple sneaks past both of them.

Flickr on Apple TV is pretty cool too, I was *this* close to signing up for SmugMug account over Flickr pro literally two days ago (price and smugmug’s craptastic templates were the deciders then).

Log into Facebook with Adobe AIR (without leaving the desktop)

Introducing ActionSnip

My new year’s resolution is to organize my ActionScript snippets, so I made a website to do just that actionsnip.com.

I know yes another snippet site, but none of the others highlight ActionScript properly. And because I don’t only collect snippets but blog posts about ActionScript as well there’s a feature called scraps which lets you save useful posts along side your snippets.

Other features include saving favorite snippets/scraps that others have posted, and a ’steal this code’ link which gives you highlighted code to embed in your blog just like the example below (here’s the original on ActionSnip)

Returns true if inputed email is valid.

function emailValid( email:String ):Boolean
{

    var emailRegExp:RegExp = /(A(s*)Z)|(A([^@s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})Z)/i;
    return emailRegExp.test(email);

}


Usage …

// returns true
trace(emailValid("user@domain.com"));
// returns false
trace(emailValid("user@domaincom"));

// returns false
trace(emailValid("user%domain.com"));



If you don’t like the Flex Builder styling you can overide it with your own styles. Currently it supports just ActionScript but I’m working on MXML and MXML/ActionScript.

Most of the bugs are squashed but if you see anything let me know (it seems to bug out with a snippet over 500 lines of code so please just snippets for now). Constructive (and even destructive) criticism is welcome.

Snip away!

Subversion with a custom port on OS X

Setting up subversion to checkout and over a custom port number is one of those tasks that I do once every six months, and immediately forget, then I waste time a’Googling to find it again.

Open up subversion’s config file

mate /Users/myuser/.subversion/config

Then find the section marked [tunnels], and add a line naming your custom port (replacing ‘1234′ with the port number)

myproject = ssh -p 1234

Then when you checkout your project you replace svn+ssh with svn+myproject

svn checkout svn+myproject://myuser@mydomain.com/home/myuser/data/svn/myproject/trunk .

That’s it!

Hacking attachment_fu to work with Flash/Flex uploads and crop square images

Rick Olson’s attachment_fu is my favorite file upload plug-in because let’s you use three different image manipulation tools [rmagick, mini-magick, image science] and storage options [file system, database, amazon s3]. However it doesn’t yet support two features I use on every CMS I build, Flash/Flex file upload (images will upload but won’t be resized) and square image cropping. Here’s how to tweak it to get both features working.

First up, support for Flash/Flex upload (I should really drop the ‘Flash/’ part as I only use Flex now) , first up Flex upload… Ilya Devers posted the solution on Google groups, but I get to claim 1% credit as my blog is mentioned in his post :P

The problem is really on the Flex side of things as all uploads come through as ‘application/octet-stream’ for the mime-type. attachement_fu can upload any kind of file so it checks the mime-type before running it’s resize code, since it’s looking for an image it skips over the Flex uploaded files. Ilya’s rather ingenious solution is to override attachment_fu and use the file system to check the file type. To overide attachment_fu add the ‘uploaded_data=’ and ‘get_content_type’ methods to your upload model.

class Upload < ActiveRecord::Base
  belongs_to :image

  has_attachment :content_type => :image,
                 :storage => :file_system,
                 :processor => 'MiniMagick',
                 :max_size => 2000.kilobytes,
                 :resize_to => '620x465>',
                 :thumbnails => { :thumb => [90, 90] }

  #override from has_attachment plugin
  def uploaded_data=(file_data)
    return nil if file_data.nil? || file_data.size == 0
    self.filename = file_data.original_filename if respond_to?(:filename)
    if file_data.is_a?(StringIO)
      file_data.rewind
      self.temp_data = file_data.read
    else
      self.temp_path = file_data.path
    end
    # in the original the next line occured earlier, and just used file_data.content_type
    self.content_type = get_content_type((file_data.content_type.chomp if file_data.content_type))
  end

  #uses the os's "file" utility to determine the file type, yanked and modified slightly from file_column.
  def get_content_type(fallback=nil)
    begin
      content_type = `file -bi "#{File.join(temp_path)}"`.chomp
      content_type = fallback unless $?.success?
      content_type.gsub!(/;.+$/,"") if content_type
      content_type
    rescue
      fallback
    end
  end
end

Next is cropping square images with mini-magick. Currently if you request a square image attachment_fu will stretch rather than crop the image, this time I’ll ‘borrow’ the solution from Craig Ambrose. This time you have to dig deeper down into the depths of the rails plugins directory to edit ‘vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb’ and replace the resize_image method with the following.

# Performs the actual resizing operation for a thumbnail
def resize_image(img, size)
  size = size.first if size.is_a?(Array) && size.length == 1
  if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
    if size.is_a?(Fixnum)
      resize_and_crop(img, size)
    else
      size[0] == size[1] ? resize_and_crop(img, size[0]) : img.resize(size.join('x'))
    end
  else
    img.resize(size.to_s)
  end
  self.temp_path = img
end

def resize_and_crop(image, square_size)
  if image[:width] < image[:height]
    shave_off = ((image[:height] - image[:width])/2).round
    image.shave("0x#{shave_off}")
  elsif image[:width] > image[:height]
    shave_off = ((image[:width] - image[:height])/2).round
    image.shave("#{shave_off}x0")
  end
  image.resize("#{square_size}x#{square_size}")
  return image
end

To crop an image you use ‘:thumb => [90, 90]‘ as in the Model code above. That’s it!

Flex Builder 3 Beta 3 is out

http://labs.adobe.com/technologies/flex/flexbuilder3/

UPDATE: and stuff compiles waaaaaay faster nice!

Rails 2.0 is go

Tons of new stuff, my favorite is Cookie store sessions

The default session store in Rails 2.0 is now a cookie-based one. That means sessions are no longer stored on the file system or in the database, but kept by the client in a hashed form that can’t be forged. This makes it not only a lot faster than traditional session stores, but also makes it zero maintenance. There’s no cron job needed to clear out the sessions and your server won’t crash because you forgot and suddenly had 500K files in tmp/session.

Akelos PHP framework apes Rails

Monkey see monkey do. I’m usually wary of PHP frameworks that are ‘inspired’ by Ruby on Rails but the Akelos folks have done a really good job with their port. They even have a screencast narrated by guy who’s funny accent you can’t quite place :P

Every now and then I get a project that has to be in PHP (usually because of hosting requirements) so it’s nice to have everything laid out in a familiar way.

Two new ways to load data into Flash

SWX Ruby is a port of SWX (originaly PHP), which claims to be “Ruby’s fastest library for exchanging data with Flash” I haven’t tried it because it doesn’t yet support Flash player 9 but I wouldn’t doubt it’s the fastest as many other methods aren’t too speedy (Although RubyAMF is much quicker lately).

as3yaml, you guessed it, is an Actionscript 3 YAML 1.1 parser and emitter.