Skip to navigation

Syntactic fantastic

Published September 08, 2006

I could rewrite Ruby syntax all day.

From ActiveResource::Connection:


def http
  unless @http
    @http             = Net::HTTP.new(@site.host, @site.port)
    @http.use_ssl     = @site.is_a?(URI::HTTPS)
    @http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @http.use_ssl
  end

@http

end

Using a bit of ||= and Rails’ returning we can get the same result without a temporary variable and less logic to follow:


def http
  @http ||= begin
    returning(Net::HTTP.new(@site.host, @site.port)) do |http|
      http.use_ssl     = @site.is_a?(URI::HTTPS)
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE if http.use_ssl
    end
  end
end

Isn’t that sexier?

@http ||= says to me “use @http or set it”

returning doesn’t quite read as nicely because it sounds like I want to return what I passed in (i.e. the new HTTP object) when in fact it returns the result of the block.

…and I wish I didn’t need that begin after the ||=

Thoughts

toolmantim

I’m Tim Lucas, a user experience developer currently in Sydney Australia.

I occasionally write, snap photos, present on various technical topics, tweet my going-ons, share teh codes and post tidbits to the scrapbook.

Most recently I published Simplifying ticket sales on sydneyoperahouse.com (February 16, 2010)

Work with me via Agency Rainford, or shoot an email to and say hello.

Powered by the present moment