Skip to content

Instantly share code, notes, and snippets.

View njonsson's full-sized avatar
🤝
Working @amzn but open to new opportunities

Nils Jonsson njonsson

🤝
Working @amzn but open to new opportunities
View GitHub Profile

Keybase proof

I hereby claim:

  • I am njonsson on github.
  • I am njonsson (https://keybase.io/njonsson) on keybase.
  • I have a public key whose fingerprint is 546E EA0C B2D1 AFC7 D08B B11C 27D3 E4D0 BF33 68B4

To claim this, I am signing this object:

@njonsson
njonsson / specifying-default-values-with-rubys-module-attr-reader-and-attr-accessor.md
Last active May 29, 2021 12:33
Specifying default values with Ruby’s Module#attr_reader and #attr_accessor

[This is [a DZone Snippet I created in August 2007][dzone-snippet]. DZone Snippets is now a defunct site, so I’m reposting it here.]

Dependency injection in Ruby is as easy as falling off a log. As [Jamis Buck has pointed out][jamis-buck-net-ssh-revisited], DI is a good thing, but DI frameworks for Ruby are overkill. The language makes them unnecessary.

Here's how to enhance [Module#attr_reader][ruby-module-attr-reader] and [#attr_accessor][ruby-module-attr-accessor] so that they can receive an options hash for specifying the default value of an attribute.

module AttrWithDefaultExtension
  
  module ClassMethods