Class OpenStruct
In: lib/more/facets/ostruct.rb
Parent: Object

Methods

Public Class methods

Allows the initialization of an OpenStruct with a setter block:

  person = OpenStruct.new do |o|
    o.name    = 'John Smith'
    o.gender  = :M
    o.age     = 71
  end

You can still provide a hash for initialization purposes, and even combine the two approaches if you wish.

  person = OpenStruct.new(:name => 'John Smith', :age => 31) do |p|
    p.gender = :M
  end

Alternatively you can provide a default block:

  stuff = OpenStruct.new{ |o,k| o[k] = [] }
  stuff.place << :a
  stuff.place << :b
  stuff.place #=> [:a, :b]

A setter block versus a defualt block is determined by the arity of the block. You can not provide both at the same time.

CREDIT: Noah Gibbs, Gavin Sinclair

Public Instance methods

Access a value in the OpenStruct by key, like a Hash. This increases OpenStruct‘s "duckiness".

  o = OpenStruct.new
  o.t = 4
  o['t']  #=> 4

Set a value in the OpenStruct by key, like a Hash.

  o = OpenStruct.new
  o['t'] = 4
  o.t  #=> 4

Merge hash data creating a new OpenStruct object.

  o = OpenStruct.new
  o.ostruct_merge { :a => 2 }
  o.a  #=> 2

Insert/update hash data on the fly.

  o = OpenStruct.new
  o.ostruct_update { :a => 2 }
  o.a  #=> 2

Provides access to an OpenStruct‘s inner table.

  o = OpenStruct.new
  o.a = 1
  o.b = 2
  o.instance_delegate.each { |k, v| puts "#{k} #{v}" }

produces

  a 1
  b 2
ostruct_delegate()

Alias for instance_delegate

Merge hash data creating a new OpenStruct object.

  o = OpenStruct.new
  o.ostruct_merge { :a => 2 }
  o.a  #=> 2

Insert/update hash data on the fly.

  o = OpenStruct.new
  o.ostruct_update { :a => 2 }
  o.a  #=> 2

[Validate]