Synthesis

Asset Packager – Rails 3 / Ruby 1.9 Compatible

Hello! Here is a long overdue update to Asset Packager, which now makes the main branch Rails 3 and Ruby 1.9 compatible. Thanks to all those on Github who sent me patches with these fixes.

Updates

  • Fix thread safety issue.
  • JSMin compatibility fix for Ruby 1.9.1 – Fixnum#ord
  • Rails >= 2.3 test compatibility
  • Rails 3 deprecations – change RAILS_ROOT to Rails.root, change RAILS_ENV to Rails.env, move tasks to lib dir

Agile JavaScript Testing

A couple weeks ago, I gave a talk at the Open Source Bridge conference in Portland Oregon on Agile JavaScript Testing.

In this presentation, I first gave an overview of Test Driven Development for those front-end JS developers who might not have heard of it yet (!) and then the difference of TDD vs. Behavior Driven Development.

I then walked through some tools:

  • Screw.Unit, a nice BDD framework for JS that is quite similar to RSpec in Ruby land.
  • Blue Ridge, a plugin for rails that integrates Screw-Unit with Rhino and Env.js and some rake tasks to create a command-line driven headless (no-browser == fast) testing workflow.
  • JS Test Driver, a project that mounts one or more browsers as slaves, and a command-line tool which notifies all the listening browsers to run tests and aggregates the results. Very cool!

In the actual presentation I even did some live coding examples of Blue Ridge and JS Test Driver, and they worked perfectly. Here are the slides from the talk:

Starting Fresh, Without the Big Rewrite

If you’re working on a project with a couple years of code under it’s belt, you may have moments of desire to completely throw the whole thing out and start anew. But, if you’re working for someone else, you know that your boss or client probably won’t like that. After all, he’s paying you to finish feature A! But, you lament, feature A builds on top of feature B that already exists but is written in a terribly unidiomatic, pre-TDD, pre-REST way, way before you or someone else learned the dark arts of coding mastery. Legacy code, argh!

So what should you do? What are your options? A) Ignore the problem and build the new feature on top of the existing badly written code. Watch things get even worse. B) Try to quickly fix the badly written code in-place so you can get on with it. Trigger cascading test failures, and palm your face. C) Start over and rewrite the entire project, get fired for being 6 months late on your estimate. None of these sound any good!

I think I may have found a solution that works for me, especially with Rails.

Start a fresh Rails project. Boom! It’s fresh and clean. Now you have room to work. The beauty of Rails is how quick it is to get started. Choose the aspect of the project you want to work on. Got some legacy code thats bugging you? TDD/BDD it from scratch, the Right Way. The idiomatic, Rails Way. Once you get it to the point where it’s working correctly and passing all tests, you can merge the new code into the main project, replacing the older, ugly, what-were-they-thinking legacy code that was getting in the way.

Now you can work in a clean environment and just focus on the problem at hand. This allows you to make progress quickly, and get rid of the old crap without having to completely start from scratch.

AssetPackager update

A long overdue update of AssetPackager is finally here:

  • Rails 2.2 compatibility fixes
  • Packages generated on demand in production mode. Running the asset:packager:build_all rake task no longer necessary.
  • Now compatible with Git, and any other revision control system since revision numbers are no longer used.
  • No more mucking with internal Rails functions, which means:
    • Return to use of query-string timestamps. Greatly simplifies things.
    • Multiple asset-hosts supported
    • Filenames with ”.”’s in them, such as “jquery-x.x.x” are supported.

Get the latest at http://github.com/sbecker/asset_packager

Thanks to the many forkers for ideas and solutions.

AssetPackager Tracker

Asset Packager now has a tracker where you can submit tickets. You can find it here.

If you have a bug to report, and/or a patch for Asset Packager, this is the place.

WeoGeo – AWS Startup Challenge Finalist

My company WeoGeo made it to the final round of the Amazon Web Services Startup Challenge. In the top 7 out of around 1000 entrants, not too shabby.

Check out the videos for the finalists, and vote for WeoGeo!

RubyBrigade.org – A Rails Rumble Success

Just wanted to mention our Rails Rumble project, RubyBrigade.org. Jason Perry, James Seaman and I
worked through the weekend to build RubyBrigade.org – a geographically aware database of Ruby User groups.

Big thanks to James for the killer hand drawn illustrations and interface. Big thanks to Jason & Katie for letting us take over their house for the weekend.

Features:

  • Google Maps Integration
  • Sub-domains for each group
  • Geocoding: either by the search box or by sub-domain!
  • RSS and iCal feed parsing
  • Display latest user groups
  • Display upcoming events across all groups
  • Display blog posts & upcoming events for individual groups
  • ReCAPTCHA for spam prevention
  • No authentication required

More Screenshots

View a Brigade

Edit a Brigade

Delete a Brigade

404 Message

If you like what you see, vote for us!

Are you SURE?! (How to confirm HTTP methods in Rails)

In Scott Raymond’s excellent book Ajax on Rails I came across a cool (non-ajax related) pattern for insuring a request’s method is POST and showing a confirmation form if not.

This is really useful in situations such as confirmation links in emails, where a form can’t be displayed and javascript won’t work, yet we don’t want a destructive action occurring through a GET request.

Here’s an example:

def unsubscribe
  if request.post?
    @user = User.find(params[:id])
    @user.update_attributes :subscribed => false
    redirect_to home_url
  else
    render :inline => %Q(
      <% form_tag do %>
        <%= submit_tag 'Confirm' %>
      <% end %>
    )
  end
end

One other piece of code you’ll need to get this to work, assumming you’re using RESTful routes, in config/routes.rb

map.resources :users, :member => {:subscribe => :any, :unsubscribe => :any} 

This states that we have a couple extra actions in our controller, and we’re not going to mandate a specific HTTP method to get there. This way we can handle it within the action if the HTTP method is wrong.

Now if your user comes to your page from a straight GET request, he’ll get prompted to confirm the big destructive action he’s about to commit.

(In a real app we’d make this form look a bit nicer.)

Wouldn’t it be nice if we could re-use this pattern, without writing out the inline form code every time? Seems generic enough.

DRY it up!

We could abstract that out, and also support any HTTP method we want. Lets follow Rails / RESTful conventions , and require PUT for updating a model. Using some handy ruby block syntax, we could write something like, say:

def unsubscribe
  confirm_unless :put do
    @user = User.find(params[:id])
    @user.update_attribute :subscribed, false
    flash[:notice] = "User is now unsubscribed"
    redirect_to users_url
  end
end

Much better. But how?! Keep reading.

Get one for yourself!

To get the confirm_unless method for yourself, slap the following code into app/controllers/application.rb:

def confirm_unless(method)
  if request.method == method
    yield
  else
    render :inline => %Q(
      <% form_tag({}, :method => :#{method}) do %>
        <%= submit_tag "Confirm" %>
      <% end %>
    )
  end
end

We could take it one step further and make it a before_filter, but I’ll leave that for a possible future post.

How to generate CSV files in Rails

A while back someone posted on rubyonrails-talk asking how to export to CSV from Rails. I posted a solution, and people seemed to dig it, so I’ll share it again here.

Use FasterCSV

Get the FasterCSV gem. Why? It’s faster, and easier to use. Once you’ve got it, require it in environment.rb. Here’s an abbreviated version of my working controller method. Copy/paste/modify. And you’re done!

def export_to_csv 
  @users = User.find(:all) 
  csv_string = FasterCSV.generate do |csv| 
    # header row 
    csv << ["id", "first_name", "last_name"] 
 
    # data rows 
    @users.each do |user| 
      csv << [user.id, user.first_name, user.last_name] 
    end 
  end 
 
  # send it to the browsah
  send_data csv_string, 
            :type => 'text/csv; charset=iso-8859-1; header=present', 
            :disposition => "attachment; filename=users.csv" 
end

HTML or CSV, have it your way

Now, if we wanted to get all clever about it, we could go further and serve both html and CSV data with only one action, using respond_to. This also requires that you add a RESTful route (map.resources :users) to your routes.rb file:

def index 
  @users = User.find(:all) 
  respond_to do |wants| 
    wants.html 
    wants.csv do 
      csv_string = FasterCSV.generate do |csv| 
        # header row 
        csv << ["id", "first_name", "last_name"] 
        # data rows 
        @users.each do |user| 
          csv << [user.id, user.first_name, user.last_name] 
        end 
      end 
      # send it to the browsah
      send_data csv_string, 
                :type => 'text/csv; charset=iso-8859-1; header=present', 
                :disposition => "attachment; filename=users.csv" 
    end 
  end 
end

Now if the user requests:

/users

she’ll get HTML. If she requests:

/users.csv

You get the point.

Random Permutation in Ruby

This post on Algo Blog about random permutation shows a cool a little algorithm for randomizing an array which apparently impresses interviewers. I thought it might be fun to write it in Ruby:

def permute_array(a)
  1.upto(a.length - 1) do |i|
    j = rand(i + 1)
    a[i], a[j] = a[j], a[i]
  end
  a
end
 
# alternate version
def permute_array2(a)
  0.upto(a.length - 2) do |i|
    j = rand(a.length - i)
    a[i], a[j] = a[j], a[i]
  end
  a
end

This is actually a pretty fun little function to use. For example – to find all the unique possible combinations of letters in my name: (Secret Scrabble weapon)

(1..5000).map{ permute_array("scott".split("")).join }.uniq.sort
 
=> ["costt", "cotst", "cotts", "csott", "cstot", "cstto", "ctost",
"ctots", "ctsot", "ctsto", "cttos", "cttso", "ocstt", "octst",
"octts", "osctt", "ostct", "osttc", "otcst", "otcts", "otsct",
"otstc", "ottcs", "ottsc", "scott", "sctot", "sctto", "soctt",
"sotct", "sottc", "stcot", "stcto", "stoct", "stotc", "sttco",
"sttoc", "tcost", "tcots", "tcsot", "tcsto", "tctos", "tctso",
"tocst", "tocts", "tosct", "tostc", "totcs", "totsc", "tscot",
"tscto", "tsoct", "tsotc", "tstco", "tstoc", "ttcos", "ttcso",
"ttocs", "ttosc", "ttsco", "ttsoc"]

Archives

buy viagra internet
newestpills
buy viagra per pill
brand cialis
viagra sample
buy viagra online order
buy viagra prescription
buy generic viagra viagra
cheap free viagra
viagra oral
buy levitra canada
levitra 100mg uk
ordering viagra onl
buy cheap levitra
viagra free trial offer
cheap free viagra viagra
buy line viagra where
cheap generic viagra
generic levitra
real viagra
how can i buy viagra online in canada
buy no online prescription viagra
cheap viagra india
cheapest uk supplier viagra
buy viagra usa
cheap pill pill sale viagra
buy generic viagra
buy-viagra
cheap soft tab viagra
buy cymbalta
walmart cialis price
buy viagra online uk
cheap india viagra
viagra coupons and discounts
buy viagra online order generic viagra
buy levitra viagra
buy viagra online a href
over the counter viagra
Sildenafil citrate 100mg
cheap man viagra
female viagra
key buy-viagra
buy cheap viagra
cialis without prescription
buy viagra onli
purchase cialis online
buy viagra onlines
buy 100 mg viagra
buy viagra 50mg
canadian levitra vs usa levitra
cheap generic overnight viagra
buy cheap viagra online
female use of viagra
cheap viagra generic
buy viagra other drug online
buy viagra online and get prescription
viagra for women
cheap generic 50 mg viagra
buying viagra online
buy sildenafil viagra
buy cialis from india
buy viagra online get prescription
buy cialis no prescription
brand cialis 20
buy say viagra
buy generic viagra usa
viagra rrp australia
buy viagra pharmacy online
shipping viagra to australia
viagra cheap
cheapest cialis
watermelon viagra
cheap kamagra viagra
buy online online pill viagra viagra
buy viagra powered by phpbb
buy discounted viagra
buy viagra montreal
viagrasuperforte
Viagra greate britain
cheap generic india viagra
buy generic viagra buy
buy price viagra
viagra prices walmart
cheap viagra in the uk
viagra professional
buy internet viagra
cialis no perscription
cialis vs viagra
cheap meltabs viagra
cheap no prescription viagra
cheap generic viagra uk
buy viagra online paypal
buy generic viagra pharmacy online
buy now viagra
herbal viagra reviews
buy viagra over the counter us
viagra and cialis
buy cheap viagra online
cipro 20
amazon viagra
buy viagra online off pharmacy prices
cialis replacement
buy online online viagra viagra
buy cheap viagra online uk
buy viagra using paypal
buy viagra now
buy discount cialis
buy line viagra
cialis-buy-info/
buy viagra online without prescription
buy viagra Australia
cheap herbal viagra viagra
buy viagra or cilas
cheap generic viagra worcester imc
purchase viagra online
buy internet viagra
buy later now pay viagra
buy viagra over the counter
discount cialis
online viagra
ebay + cialis
buy viagra online discount
buy viagra overnight
buy kamagra viagra india
buy viagra cialis levitra
effect of viagra on women
cheap viagra canada
india viagra cialis vicodin
buy viagra online online pharmacy
cheap viagra
is viagra safe for women
buy in spain viagra
buy viagra online
Cialis online
buy viagra online
cheap viagra without a prescription
buy discount soma
cialis online
viagra oral jelly
buy cialis canada
q buy viagra online
cheap drugs viagra cialas
where to buy viagra in beijing
cialis coupons
viagra price in india
viagra and hearing loss
marijuana and viagra
cheap generic viagra from usa
cheap viagra in uk
buy viagra order viagra
buy viagra and cilas
generic-viagra
cheap deal viagra
buy now online viagra
free viagra
buy viagra all information
buy viagra cheapest best prices online
generic viagra
homemade viagra
lowest price viagra
buy viagra on-line
buy viagra online
buy lexapro
buy viagra online in uk
accutane for sale online
buy viagra online
cheap viagra fast shipping
buy viagra online paypal vipps
buy prescription vaniqa viagra
buy online order viagra
buy viagra online india
cheap viagra online canada
free viagra in the uk
cheap cialis online
buy generic viagra img
cheap kamagra uk viagra
cheap discount viagra
viagra uk
buy viagra on the internet
purchase levitra online
Viagra Oklahoma city
cialis voucher
viagra jelly
ordering cialias
viagra rrp australia cost
viagra suppliers in the uk
cheap discount viagra viagra
buy viagra online u
buy viagra online in australia
viagrafree samples
try viagra for free
buy discount viagra
uninsured cost of cialis
buy cheap cialis
viagra over the counter walgreens
buy viagra pills
free viagra sample
purchase levitra
uk viagra sales
buy generic viagra online
cheap meltabs online viagra
free viagra without prescription
buying viagra in uk
cheap generic viagra overnight delivery
buy viagra online no prescription
buy levitra
buy viagra online pharmacy
cheap genric viagra online
cheap mexico viagra
viagra alternatives
cheap sale viagra
viagra pro online
cheap pill viagra
cost of viagra
buy viagra prescription america
buy site viagra
buy viagra online ireland
buy now cialis
levitra online
buy viagra online now buy viagra
ed pro trial pack
generic vs brand name viagra
cheap pharmacy viagra
buy cialis online
buy viagra online in the uk
drugstore 365 org order levitra online
cheap phizer viagra
buy cialis now
buy viagra online canadapurchase cialis
buy real viagra
womens viagra
buy viagra online in
buy nexium
cheap prescription viagra
how does viagra work
buy duscount viagra online
problems with viagra
buy kamagra viagra
buy real viagra online pharmacy
buy get online prescription viagra
buy viagra online cheapest
buy viagra cheaply
viagra pfizer
viagra and cialas
cialis online
cheap generic viagra online
buy low price viagra
viagra online uk
buy prescription viagra without
buy online levitra cialis viagra
viagra dosage
buy cheap tamiflu
viagra for sale
cheap generic substitute viagra
buy viagra online at lowest price
viagra generic
order viagra
cheap genaric viagra kamagra
cheap discount cialis
viagra and cialis cheap
viagra online
buy viagra online at
buy viagra online at cheap price
alternative to viagra
buy keyword online viagra
generic viagra from india
cheap generic viagra substitute
cheap viagra viagra
guaranteed cheapest viagra
cheap discount levitra online
buy in online usa viagra
buy viagra online alternative viagra
herbal viagra
viagra online
buy discount viagra viagra viagra
cialis no prescription
cheap molde ticket viagra
cheap cialis overnight
viagra india
buy levitra now
cialis super active review
cheap inexpensive viagra
buy real viagra pharmacy online
buy sale viagra
online overnight viagra
cheap drug viagra
viagra liver damage
buy locally viagra
buy generic viagra
buy real viagra online
buy viagra online web meds
ed. trusted medstore in cialis
where can I buy cialis 20mg
cheap pharmaceutical viagra
buy viagra online australia
buy now levitra
buy viagra cialis
viagra super active
buy levitra viagra online
viagra for sale without a prescription
does watermelon have viagra effect
sex shop viagra
buy viagra cheapest
cheap herbal viagra
price of viagra
cheap generic viagra no prescription
buy viagra
cialis overnight shipping
buy online drug viagra pharmacy
viagra without prescription
buy viagra alternative
viagra uk cheap purchase buy
cheap generic viagra substitutes
Viagra for sale
buying viagra
tadalafil canada
non prescription viagra
generic cialis
buy viagra online au
cheap generic viagra no script
viagra quebec
buy viagra pill online
buy in online uk viagra
buy generic viagra online pharmacy online
buy levitra online viagra
cheap prescription viagra without
cheap site viagra
cheap levitra online
cheap generic online viagra
discount viagra
buy prescription viagra
buy female viagra