Skip to content

Instantly share code, notes, and snippets.

@orend
Created September 28, 2012 01:50
Show Gist options
  • Save orend/3797536 to your computer and use it in GitHub Desktop.
Save orend/3797536 to your computer and use it in GitHub Desktop.
structs and ostructs
Point = Struct.new(:x, :y)
origin = Point(0,0)
# OStructs are particularly good for configuration objects. Since any method works to set data in an OStruct, you don't have to
# worry about enumerating every single option that you need:
require 'ostruct'
def set_options
opts = OpenStruct.new
yield opts
opts
end
options = set_options do |o|
o.set_foo = true
o.load_path = "whatever:something"
end
options #=> #<OpenStruct set_foo=true, load_path="whatever:something">
# structs for domain concepts:
class Person
attr_accessor :name, :birthday
Birthday = Struct.new(:day, :month, :year)
def initialize(opts = {})
@name = opts[:name]
@birthday = Birthday.new(opts[:day], opts[:month], opts[:year])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment