Class: OpenStruct

Inherits:
Object show all
Defined in:
lib/standard/facets/ostruct/initialize.rb,
lib/standard/facets/ostruct/to_ostruct.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, &block) ⇒ OpenStruct

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

CREDIT: Noah Gibbs, Gavin Sinclair



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/standard/facets/ostruct/initialize.rb', line 21

def initialize(hash=nil, &block)
  @table = {}
  if hash
    hash.each_pair do |k, v|
      self[k.to_sym] = v
    end
  end
  if block && block.arity == 1
    yield self
  end
end

Instance Method Details

#to_ostructObject



5
6
7
# File 'lib/standard/facets/ostruct/to_ostruct.rb', line 5

def to_ostruct
  self
end