Jeff Cohen and Brian Eng - Ruby on Rails Podcast

Posted over 7 years back at Ruby on Rails Podcast

The authors of the Softies on Rails blog talk about developing Rails apps on the Windows platform.
Also mentioned:

Rails plugin repository *is* on the way

Posted over 7 years back at Luke Redpath - Home

Ryan Daigle speculated on his blog that an official Rails plugin repository was in the works. He referred to an app checked into the Rails subversion repository recently.

I can announce that a Rails plugin repository is on the way, although not the one currently in the Rails repository. That particular app was a repository started by Rick Olson. The repository that is on the way is actually being worked on by myself and James Adam of Rails Engines fame.

Background and motivation

To give a bit of background to this; the idea of an official plugin repository was born out of a conversation between Rick Olson, James and Geoffrey Grosenbach at RailsConf. Work had already begun on improving the Rails plugin mechanism with RaPT, a project run by Geoffrey, James and Ben Curtis. I recently joined the RaPT team and after some discussion with the rest of the team, James and I started development on the project.

Some people may ask why an official repository is needed. Ben Curtis currently maintains a good repository of his own however it is unfair to rely on one person to keep the repository running. As more and more people use, develop and rely on plugins, the existing setup – a wiki page – is simply not scalable or maintainable. Plugins are the number one way of adding/changing Rails functionality without having to submit patches to the core – something that DHH actively encourages and something I fully support. I believe the core should be as lean as possible with additional functionality being provided by plugins.

Our original idea was to develop a plugin repository that sat somewhere between Rubyforge and the Mozilla Firefox extensions website – this included tagging, comments and ratings – the usual Web 2.0 suspects. However, after some discussion with the Rails core team we decided to drop those features in favour of making adding plugins as easy as possible and developing a way of detecting plugin health by gathering test run statistics to both encourage testing of plugins and make it clear how likely it is that a plugin will work with a particular Ruby/Rails version. The other downside to having ratings/comments etc. was the need to make users sign up for an account, something that is best avoided.

The other major feature that James and I felt was really important was the correct (and mostly automatic) handling of plugin releases and metadata. This includes reading plugin metadata from an about.yml file and handling plugin releases through either updates to the release number in the about.yml file or repository tags. One of the major failings of the current script/plugin tool is its inability to handle plugins that use the traditional trunk/tags/branches structure – something I feel is essential for anything but trivial plugins.

To sum up, the core functionality of the repository will be:

  • Make it easy to browse plugins and view plugin/release health/compatibility
  • Correctly and automatically handle plugin releases/versions and metadata
  • Make adding of plugins – either single plugins or entire repositories of plugins – as easy and foolproof as possible
  • Provide some Rake tasks to make it possible to announce new plugins/releases without having to go to the repository website
  • Improve the script/plugin tool and make it use the plugin repository as its main source, making it possible to install plugins by simply specifying the plugin name

Current status of the project.

James and I have made good progress on the project so far. You can view where we are up to here – do bear in mind that this is still under development and cannot be considered reliable at this point. We are aiming to move the project over to the Rails subversion repository in the next few days.

I cannot give an accurate ETA on when the project will be ready to go live, but we really want to have this up and running in time for the European RailsConf. In the meantime, have a play with what we’ve done so far and get a feel for it. If you have any suggestions please do speak up as it is the community as a whole that this is aimed at.

Update: James has also put up a post on his blog about the project.

New blogging engine and template

Posted over 7 years back at Luke Redpath - Home

Like many other people, I’ve moved my blog over to Mephisto by Olson and Palmer (doesn’t that sound like a 70s prog band?). I’d become very sick of Hemmingway though, even if I was using the less common white version, and with Mephisto coming with Hemmingway as its default theme its now even less unique, so it was time for a change. So I present to you…Sydney.

Why Sydney? Absolutely no reason whatsoever. It was the first thing that came into my head. The template itself wasn’t actually designed for my blog; it was designed for the new, forthcoming Unobtrusive Javascript plugin website, with a different color scheme. A bit of reworking later I now have it as a full-on blogging template for Mephisto and it supports multiple color schemes. The UJS website will be using “neopolitan”. I call this one “mintchoc”. I’m not 100% certain if I will stick with this color scheme but I’m very happy with the overall layout.

Unfortunately I will not be releasing this template for others to use…to begin with anyway. Its nice to have your own unique theme so I’d like to keep it that way for the time being. I have no doubt that I will release the template to the community in the future though.

Backwards compatibility

I’ve added a custom route to make sure all Wordpress URLs load the correct article – the only difference was the /index.php/ part of the Wordpress URL and a few of the article slugs needed tweaking. If you have any pages bookmarked, I’d recommend updating your bookmarks to the new URL. Archive pages will probably not work any more. I’m also yet to import the comments but I will do this over the coming days. Thanks to Chris McGrath for his article on converting typo URLs to mephisto URLs which was a great help in getting this running properly.

Awesome syntax highlighting

It’s also worth mentioning that code syntax highlighting is provided by Dan Webb’s awesome Javascript CodeHighlighter library, and a small Rails plugin that adds some Mephisto filters to use it. Dan hasn’t set up a permanent home for the library yet and some of the language definition files could do with a bit of fleshing out, but its very easy to extend and its very fast. Naturally, its completely unobtrusive – your code will still be displayed sans-highlighting if Javascript is disabled and there’s no more littering of your code with loads of span tags. Best of all, its completely language agnostic – use it with your Rails apps, your PHP apps, or with completely static HTML pages. Grab CodeHighlighter for your own website.

And finally…

On the subject of the UJS website, Dan and I hope to have this, along with a 0.3 release out on Monday. The new feature contains some neat new features, some bug fixes, improved test coverage and most importantly…caching. Keep an eye out on Monday for more information and the new UJS Rails Plugin website.

Rails Template Optimizer Beta Test

Posted over 7 years back at RailsExpress.blog

It's there. Finally. Get it while it's still hot. Be among the first to experience unprecedented rendering speed for Rails Erb templates ;-)

We all know and love the little helpers that Rails offers to speed up template coding. They're convenient and help us to keep the template code readable. But convenience almost always comes with a hidden performance cost. It's an unavoidable fact, at least in the IT business.

I started the Rails Template Optimizer project in order to reduce the hidden cost in using Rails helper methods. And I think the current version of this software shows that this is possible, to a great extent, although it is still in a beta state.

You can download the code from subversion. Since I'm pretty sure that there are still some bugs and problems with the code, I have set up a Trac installation. The start page contains information on how to obtain the template optimizer and links to additional information.

So, how does it work? And what kind of performance improvement can you expect?

Very early during my involvement in Rails performance improvement I observed that some of the Rails helpers would run rather slowly, most notably helpers that use route generation in some form. I worked around the problem by coding my own specialized methods (as decribed in my InfoQ article to avoid invoking the routing code at all. This was acceptable for my own purposes, but not really usable for larger applications, with complicated route setups. In addition, some of the helpers, especially those that create AJAX code, produce code so complicated that it would be insane to write it manually.

But after thinking about the problem for a while it dawned on me that a good part of the work the helpers were doing could be done once and for all at template compile time:

First, there are helper calls that have either no argument or all of their arguments specfied in the template code. These can safely evaluated when the template gets compiled. (Well, most of the time, the actual story is a bit more complicated than that. Use the source to find out more.)

Second, there are helper calls where the output produced depends to a large extent on the structure of the input data, and only slightly on the exact value of that data.

Consider the following link_to call:

link_to "Edit User",
   {:controller => "user", :action => "edit", :id => @user},
   {:class => "user_link"}

Assuming just the default routes, we know that this will always produce

<a href="/user/edit/#{@user.to_param}" class="user_link">Edit User</a>

And this is exactly the code that will be produced by the template optimizer at template compile time. It achieves this by performing a partial (symbolic) evaluation of the template code. (For details I'd like to refer you to the source code, for now.)

How much improvement will you get by using the optimizer? That's a tough question. It all depends on the actual source and may vary between no improvement at all and spectacular improvements.

As usual, I've benchmarked it. Here are two data sets. First, my own app with every link using link_to instead of my helpers.

page c1 totalc2 total c1 r/sc2 r/s c1 ms/rc2 ms/r c1/c2
/rezept/show/413 8.154515.23208 122.6191.1 8.155.23 1.56
/rezept/cat/Hauptspeise 9.853674.68909 101.5213.3 9.854.69 2.10
/rezept/cat/Hauptspeise?page=5 10.107214.84142 98.9206.6 10.114.84 2.09
/rezept/letter/G 9.861534.67950 101.4213.7 9.864.68 2.11

Second, the admin interface of an older Typo version:

page c1 totalc2 total c1 r/sc2 r/s c1 ms/rc2 ms/r c1/c2
/admin 1.499670.85967 66.7116.3 15.008.60 1.74
/admin/content 7.015671.84333 14.354.2 70.1618.43 3.81
/admin/pages 2.994671.31767 33.475.9 29.9513.18 2.27
/admin/categories 4.510333.12500 22.232.0 45.1031.25 1.44
/admin/sidebar 4.885334.04133 20.524.7 48.8540.41 1.21
/admin/themes 3.583002.29667 27.943.5 35.8322.97 1.56
/admin/users 1.411670.77100 70.8129.7 14.127.71 1.83

I would say these examples show some really nice improvement factors.

Enjoy.

Update:

You can svn co from http://railsexpress.de/svn/plugins/template_optimizer/trunk

And the template optimizer should now be compatible with rails 1.1.6

Unobtrusive JS 0.2.2 - "the two in one day!" release

Posted over 7 years back at Luke Redpath - Home

Update 15 Feb 2009: The UJS plugin for Rails is no longer actively maintained but you can find the the source on github.

I’m sure many people are aware of the risks in running pre-1.0 software/plugins and that there are likely to be many bugs discovered until that 1.0 release finally hits (and beyond).

Unfortunately, it takes really working with a Rails plugin to find problems and I have been doing so today. I encountered a strange error where the plugin was generating IDs for elements that shouldn’t have any javascript events attached.

Update 21/08/2006: The latest version of this plugin is 0.3 – please see [this post](http://www.lukeredpath.co.uk/2006/8/21/ujs-rails-plugin-0-3-new-name-new-website) and the [official UJS website](http://www.ujs4rails.com) for more information.

def tag_options(opts)
  unless opts[:inline]
    JAVASCRIPT_EVENTS.each do |event|
      if opts.include?("on#{event}") # this was the culprit!
        opts['id'] = generate_html_id unless opts['id']
        register_js_behaviour("##{opts['id']}:#{event}",
                  opts["on#{event}"]) unless opts["on#{event}"].nil?
        opts.delete("on#{event}")
      end
    end
  end
  rails_tag_options(opts)
end

What it turned out that was happening was that some Rails helpers were adding empty onclick handlers to some tags so they were being picked up by the above code. All that was required was a simple fix:

# get rid of this
# if opts.include?("on#{event}") 
# and use this:
unless opts["on#{event}"].blank?

So [grab Unobtrusive Javascript for Rails 0.2.2](http://opensource.agileevolved.com/svn/root/rails_plugins/unobtrusive_javascript/tags/rel-0.2.2/) while its hot!

Unobtrusive Javascript broken in Edge Rails, small fix release

Posted over 7 years back at Luke Redpath - Home

Update 15 Feb 2009: The UJS plugin for Rails is no longer actively maintained but you can find the the source on github.

We're currently using Edge Rails and the Unobtrusive Javascript for Rails plugin in the forthcoming Rails Plugin Repository and after a Subversion update today, something seems to have broken the Unobtrusive Javascript plugin.

I'm not sure what caused the breakage but the problem was a minor one; after some investigation it turned out that the unobtrusive javascript controller was not being automatically being required by Rails even though its parent folder had been added to the Rails load path. The fix was as simple as explicitly requiring the controller file and everything is now fine. Release 0.2.1 addresses this issue and also adds an about.yml file containing plugin meta-data.

Update: Please grab Release 0.2.2 instead.

If you are running on Edge Rails you will need to upgrade to this release. The plugin (version 0.2) continues to work just fine if you are running the new Rails 1.1.5 security fix so whatever caused this breakage doesn't appear to be related to the security fix.

The RailsConf Europe HooHa

Posted over 7 years back at Luke Redpath - Home

David posted an entry on the RubyOnRails weblog pushing people to go to RailsConf EU and a lot of people reacted negatively to it.

The thing that most people reacted badly about was the price. £575 is a lot of money to spend for most people, especially freelancers and enthusiasts and the early bird price of £475 is still not cheap.

The more cynical would think that the real reason David wants to encourage people to come along is because the organisers can make money from it. I doubt this is the case. However there has been a surprising lack of enthusiasm and hype surrounding the conference compared to the US conference which was hyped to the roof and I suspect the number one reason for this is the cost.

That being said, there is really little excuse for much of the whining and moaning that has been going in the comments for the above post and elsewhere. Ultimately, its not about whether or not the conference is expensive (and I do think it is overpriced and yes, I am going) but whether or not you can justify the cost.

If you can justify the cost, please, get a ticket and come along - I do feel it will be a worthwhile experience. You'll get to meet some interesting and clever people, talk Ruby and Rails for two days without people looking at you funny and its a great networking opportunity.

If you can't justify the cost - fair enough. But don't go on about it - get over it; move on. The world is not going to end because you could not attend the conference. Your RubyOnRails skills are not going to suffer. I'd consider myself a good Ruby and Rails programmer and I didn't get to the level I'm at today with a full time, well-paid Rails job by going to conferences. Even if I could have afforded the flight and tickets to the US RailsConf (and I would have loved to go) there was no way I'd be able to justify that expense.

Many people mentioned that the money they could spend on the conference would be better spent on books. Thats a fair point. If you have the money available do go and buy some books, you'll definitely benefit. I strongly recommend Rails Recipes by Chad Fowler and Domain Driven Design by Eric Evans.

As I said I do believe the conference is far too expensive; but some of the bile being aimed at the organisers is ridiculous. Yes it would be nice to go but going to a conference is a privilege, not a necessity. Nobody is pointing a gun at your head and making you go. If you are in the UK, you could always try visiting a local Ruby Users Group, or starting your own if there isn't one.

Regarding the price, if the main reason that it is so expensive is because it is being held in London - one of the most expensive cities in the world (I know, I live there!) then my advice to the organisers would be: hold it somewhere else. There are much cheaper venues with great air, road and rail transport links - Birmingham springs to mind. With the wealth of cheap flights out there, I'd even be happy to fly to somewhere on the continent for the conference - it would still probably work out cheaper.

Finally, a lot of people were bitching about such and such feature not being in Rails (il8n mainly) and how Rails was making a fatal mistake by not having it in the core. If people haven't really picked up on this yet, let me re-iterate - Rails is opinionated software and I hope it stays that way. Yes there are times when I've wished for a feature but with Rails' plugin system there is no longer any excuse for bugging the core team for a particular feature - if you need it that badly, implement it as a plugin and share it with the world. There are already efforts going into internationalisation and legacy database support.

The core should only ever have the key features that are essential to the majority of people - adding minority features (even if they are important minority features) will only lead to a bloated framework which is a contradiction to everything Rails is supposed to stand for. ActionWebService is already being stripped from the core into a plugin and there are other things I'd like to see extracted from the core into plugins as well - the Prototype/Scriptaculous helpers and most importantly the most useless Rails feature of all, scaffolding - a feature that anybody with an ounce of Rails experience has a need for other than for the occasional spike/prototype.

I'm well aware that the current Rails plugin system is far from perfect - installing plugins could be made easier and its a pain to install plugins that make use of the standard Subversion trunk/tags/branches structure. But there are efforts going on to improve this. If theres one thing you can do today to improve Rails and make yourself a more experienced Rails programmer - write a plugin!

Shugo Maeda - Ruby on Rails Podcast

Posted over 7 years back at Ruby on Rails Podcast

A report from RailsConf with Japanese developer Shugo Maeda. Translated by Stephen Munday.

Release: Unobtrusive Javascript For Rails 0.2

Posted over 7 years back at Luke Redpath - Home

Update 15 Feb 2009: The UJS plugin for Rails is no longer actively maintained but you can find the the source on github.

Dan Webb and I are happy to announce the latest release of the Unobtrusive Javascript plugin for Rails. This release packs in lots of cool new features, a few changes to old ones and some performance enhancements.

Update 21/08/2006: The latest version of this plugin is 0.3 - please see this post and the official UJS website for more information.

As I mentioned in my previous article, Dan had been working on his own plugin and we've now pooled our efforts and are working on the single plugin together, with much of Dan's JavascriptProxy functionality from his own plugin now rolled into Unobtrusive Javascript for Rails 0.2.

Here's a full list of changes and additions:

  • UPDATED: register_js_behaviour remains as an alias for backwards compatibility but is officially deprecated; it will probably be removed in the next release. There are also aliases for the American spelling of behaviour for our friends on the other side of the pond.
  • NEW: You can now attach behaviours directly to elements using @tag@ by passing in javascript event handlers in the HTML options hash (:onclick, :onmousedown etc.); they'll be extracted to the external behaviours file automatically.
  • UPDATED: The core Rails AJAX/Javascript helpers (link_to_remote, button_to_function, link_to_function, form_remote_tag etc.) now work out of the box.
  • NEW: There is no need to explicitly specify an HTML ID for the elements you want to attach behaviour to - if you don't, one will be generated automatically for you.
  • NEW: Options to render behaviour rules directly in your page inside script blocks instead of in the external behaviour file.
  • FIXED: Behaviours inside AJAX-loaded partials will now work.
  • UPDATED: event:Selectors and domReady javascript libraries are replaced with the lowPro.js library by Dan Webb
  • UPDATED: Javascript behaviours now have access to a single variable - @this@
  • UPDATED: Behaviours can now cancel the default action by returning false as well as using Event.stop(event). This also works properly in Safari.
  • FIXED: The required javascript files will be copied to your public folder automatically on installation. There is also a rake task for copying files across when upgrading the plugin.
  • NEW: Documentation!

There is currently only one known issue:

  • Behaviours are not being reapplied after an AJAX request in Opera 9

Here's a look at some of the new features, starting with writing behaviours using pure Ruby:

<% apply_behaviour "#mylink:click" do |page, element|
  page.alert "You clicked me! Now watch me fade..."
  element.visual_effect :fade
end %>

Attaching behaviours directly to elements with content_tag

<%= content_tag "div", "My funky box", :onclick => "alert('Hello World!')" %>

We want you to really put this release through its paces - does it conflict with other plugins? Does it cause unexpected problems with Rails itself? Are there any other features you'd like to see? The place to report these feature requests and bugs is of course the Agile Evolved Open Source Trac.

Further Information

Installation note: some people have reported that the plugin fails because the Rails plugin installation script installs the plugin to rel-0.2 instead of unobtrusive_javascript. This is a failing of Rails' plugin installation system in that it doesn't correctly handle the typical tags/trunk/branches Suvbersion repository layout. If you install the plugin using script/plugin, make sure you rename the rel-0.2 folder to unobtrusive_javascript. If you are using svn:externals, you can edit your externals file manually:

$ svn propedit svn:externals vendor/plugins

Then add the following line to it:

unobtrusive_javascript http://opensource.agileevolved.com/svn/root/rails_plugins/unobtrusive_javascript/tags/rel-0.2

Future Plans

So what do we have planned for 0.3? More patches to Rails' more complicated built-in helpers, such as apply_behaviour how about some of this:

<% apply_behaviour "div.draggable", make_draggable %>
<% apply_behaviour "li.sortable", make_sortable %>
<% apply_behaviour "#searchbox", make_autocomplete %>

Comments open!

Rails Plugin Packs&trade; coming to RaPT

Posted over 7 years back at Luke Redpath - Home

Good news - Geoffrey has agreed to roll Rails Plugin Packs into RaPT. I've already integrated it into the RaPT source code and a patch is winging its way to Geoffrey's inbox as I write this.

For the adventurous who want to give it a try in the meantime (with all the usual caveats), you need to first check out the RaPT source:

$ svn co svn://rubyforge.org/var/svn/rapt/trunk rapt

Next, download the pluginpack integration patch. Change to the rapt directory you just checked the source out to and apply the patch.

Update: I've been added to the RaPT committers list; this patch has now been applied to the trunk. Once you've checked it out, you simply need to build and install the gem.

$ rake package
$ gem install pkg/rapt-0.1.0.gem

You'll find RaPT will now have three new commands: pack:install, pack:uninstall and pack:about. All three commands take one argument, the system path or URL to your pack file. Run rapt -h for more information.

Scott Barron - Ruby on Rails Podcast

Posted over 7 years back at Ruby on Rails Podcast

The founder of the Rails Podcast muses about acts_as_state_machine, running a business, and keeping up your Rails face.

Install your favorite rails plugins easily with Rails Plugin Packs&trade;

Posted over 7 years back at Luke Redpath - Home

After a brief brainwave on the way home from work, I came up with a simple solution to the problem, which I now present to you simply as: Rails Plugin Packsâ„¢.

The concept is incredibly simple; you write your own plugin pack - nothing more than a simple specification written in YAML - and publish it somewhere, either storing it somewhere on your harddrive, on your network or hosted on your website. You then use a series of simple Rake tasks to install/uninstall these packs by simply specifying the URL/path to the pack file.

I've initially implemented this as a Rails plugin, so install it to get going:

$ ./script/plugin install http://opensource.agileevolved.com/svn/root/rails_plugin_pack

This will give you three new Rake tasks - pluginpack:install, pluginpack:uninstall and pluginpack:about. What they do should be pretty self-explanatory. They all take a pack url/path as an argument, in the form PACK=url_or_path, for example:

$ rake pluginpack:install PACK=http://www.lukeredpath.co.uk/mygreatpack.pluginpack

Currently, Subversion is required to use the plugin as it installs each plugin by doing an svn co of each plugin. I plan to expand on the ways of installing the plugins soon, including support for svn export and svn:externals.

Writing your own pluginpacks is simple - the file extension can be whatever you like although I prefer to use the standard .pluginpack suffix. The files themselves are very simple and are written in YAML. Here's an example plugin pack file (which comes bundled with the rails_plugin_pack plugin itself):

about:
  name: Example Pack
  description: An example plugin pack
  author: Luke Redpath
  email: contact@lukeredpath.co.uk
  website: http://www.lukeredpath.co.uk
plugins:
  unobtrusive_javascript: http://opensource.agileevolved.com/..[truncated]
  navigation_mappings: http://opensource.agileevolved.com/..[truncated]

All of the meta-data is optional, although if you omit a name it will result in your plugin being called "Untitled Plugin" so I recommend giving every one of your packs a name, at least.

So what possible uses could this have? I've already discussed facilitating the installation of the same group of plugins on each new project - you could have your own personal or company-wide "standard" plugin pack that you use on each new project. You could write a blog post about your favorite Rails plugins and offer a plugin pack containing each plugin discussed in your article. You could use it to group related plugins. You could even use it as a basic dependency mechanism, by offering packs of plugins that depend on each other (although this is no substitute for a proper dependency mechanism).

The only downside to this at the moment of course, is that Rails Plugin Packs is implemented as a Rails plugin itself, meaning you still need to install at least one plugin manually before you can do anything else on a new project. This isn't ideal and I'm waiting to hear back from Geoffrey Grosenbach about the possibility of submitting a patch to RaPT and rolling plugin-pack functionality into the RaPT core.

Comments are open so as usual, all feedback welcome and appreciated; please file any bugs/issues in the Agile Evolved Trac.

Update: I've made a small change to the plugin pack format so if you've already checked out the plugin you'll need to run an update. I've updated the example above and you can view the actual changes with the trac changeset viewer.

Using Ruby hashes as keyword arguments, with easy defaults

Posted over 7 years back at Luke Redpath - Home

Similar to many Rails helpers/methods, a lot of the methods I write often use an optional hash of options, or sometimes just a hash only, to simulate keyword arguments (often using symbols).

The only downside to doing this is you lose out on easily setting default values using Ruby's default method argument values. You might use code something similar to the following to make up for this:

def some_method(opts={})
  my_foo =  opts[:foo] || 'mydefaultfoo'
end

However, as you have more and more keyword options, setting defaults in this way gets rather tedious. Fortunately, Ruby's Hash#merge comes to our rescue (almost) - it allows you to merge the contents of one hash with another. The only problem - any duplicate keys in the hash you are merging will overwrite your original hash values - when it comes to setting default values, we want this to work the other way around; we only want values in the defaults hash to be merged if they do not exist in the original hash. Again, Ruby comes to our rescue - Hash#merge takes a block as an argument and will pass any duplicate values that crop up into the block - we can use this block to decide which value to keep.

Using the simple monkey patch to the Hash class below, you will no longer have to set each default individually:

class Hash
  def with_defaults(defaults)
    self.merge(defaults) { |key, old, new| old.nil? ? new : old } 
  end

  def with_defaults!(defaults)
    self.merge!(defaults) { |key, old, new| old.nil? ? new : old }
  end
end

Of course, sticking with Ruby naming conventions, with_defaults() will return a new hash whilst with_defaults!() will change the original hash directly. Now all you have to do is something like this:

def my_funky_method(opts={})
  opts.with_defaults! {
    :arg_one => 'foo',
    :arg_two => 'bar',
    :arg_three => 'baz'
  }
end

Update: Dan Web just informed me of another way of doing this - instead of merging your defaults into your options, simply merge your options into your defaults et voila!

def my_method(opts={})
  {:arg_one => 'foo', :arg_two => 'two'}.merge!(opts)
end

If there is one thing that is annoying about Ruby, it's that just when you think you've come up with a cool little code snippet, somebody inevitably comes up with an even easier way of doing the same thing.

That said, I do still think there is something nice about the with_defaults() method - it's slightly more intention-revealing. Weigh that up with the need to monkey-patch. Choose what works best for you.

Update 2: Josh Susser now informs me (see comments) that this functionality is built-right into Rails courtesy of ReverseMerge. I still think with_defaults sounds better but I guess that pretty much makes this post redundant!

We're hiring: Rails developers needed

Posted almost 8 years back at Luke Redpath - Home

Things are getting busy here at Agile Evolved and we are looking for UK-based RubyOnRails developers to join our team.

We'e looking at two junior-level development positions. You don’t necessarily need to have RubyOnRails experience but if you do not you will need to be a fast learner and have excellent skills in another language.

You must fulfill the following requirements:

  • Should be able to learn very very quickly.
  • Should have excellent OO knowledge (be prepared to be tested on this).
  • Experience with a scripting language such as either Ruby (preferred), Python, PHP 5 or similar.
  • You must already have the the relevant UK work permits or be an EU resident.
  • Good knowledge of HTML/XHTML and CSS.
  • Basic knowledge of Javascript (You’ll be an expert by the time we'e through with you).
  • You must like or at least smile when using a Mac.

In addition, we'e also looking for a full-time Web Designer. Skills for this position are:

  • Excellent HTML/XHTML and CSS skills.
  • Good design skills.
  • Knowledge of Photoshop and Illustrator.
  • Good Javascript skills.

Of course if you'e one of those few people that can code and do design as well we’d love to hear from you too.

Salaries for these positions are in the £18k to £25k range. Please send your CV/Resume as a PDF (preferred), MS Word or text file to enquiries@agileevolved.com. Please also include a cover letter. No agencies please.

Adrian Holovaty - Ruby on Rails Podcast

Posted almost 8 years back at Ruby on Rails Podcast

The lead developer of the Django framework shares his perspectives on solving the problems of website development.