[LRUG] Dumb question: keyword arg parsing / Struct

Tom Stuart tom at experthuman.com
Tue Aug 17 03:09:20 PDT 2010


On 10 Aug 2010, at 13:08, Daniel Barlow wrote:
> Is there a gem or a standard idiom for creating Struct-like classes whose #new method accepts named parameters (corresponding to the accessor names) instead of arguments by order?

For those situations where you want something a bit less open than OpenStruct, I quite like doing this:

class Book < Struct.new(:isbn, :author, :title, :review_rating)
  def initialize(attributes = {})
    attributes.stringify_keys!.assert_valid_keys(*members)
    super *attributes.values_at(*members)
  end
end

This does depend upon using ActiveSupport to stringify the hash's keys so that you can use Struct#members to index it.

Cheers,
-Tom


More information about the Chat mailing list