Safe Nils and Try

March 1st, 2008 1 Comment »

Chris over at ozzm.org just posted an awesome little snippet of code.

class Object
  ##
  #   @person ? @person.name : nil
  # vs
  #   @person.try(:name)
  def try(method)
    send method if respond_to? method
  end
end

I took it a step further and allowed args and blocks to be passed to it.

Object.class_eval do
  def try(method, *args, &block)
    send method, *args, &block if respond_to? method
  end
end

Now not only can you do things like @person.car.try(:running?) but you can do things like Kernel.try(:puts, "Oh Wow This Is AWESOME!")

The block portion lets you do things like:

def blah
  yield
end

try(:blah) do
  puts "wow, blah works and it yielded to this block!"
end

All in all it’s pretty sweet, but it definitely lets you abuse demeter. And by abuse it I mean the taking out back and beating with a rubber hose kind of abuse. For example @car.try(:person).try(:parent).try(:siblings).try(:first).try(:is_male?).

So, don’t be evil, use it well.

Rails Form Authenticity Token in Javascript

December 15th, 2007 10 Comments »

Hey guys, just a basic little snippet to get and encode the form authenticity token new in Rails 2.0, but in Javascript.

var AJ = {
  encode_authenticity_token:function(token) {
    return encodeURIComponent($(token).value)
  },

  authenticity_token_query_parameter_for_page:function() {
    return 'authenticity_token=' + AJ.encode_authenticity_token(document.body.select('input[name="authenticity_token"]')[0])
  },

  ajax_request:function(url) {
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:AJ.authenticity_token_query_parameter_for_page()})
  }
}

You can call AJ.ajax_request(url) to do a rails-style link_to_remote post and execute, or just get the form authenticity token in a format ready for the query string by using AJ.authenticity_token_query_parameter_for_page()

Hope this is helpful!