Created
September 28, 2012 01:50
-
-
Save orend/3797536 to your computer and use it in GitHub Desktop.
structs and ostructs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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