Skip to content

Instantly share code, notes, and snippets.

@blaix
Created September 3, 2011 13:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blaix/1191188 to your computer and use it in GitHub Desktop.
Save blaix/1191188 to your computer and use it in GitHub Desktop.
Struct with an OpenStruct-style initializer
class Struct
def self.create(params = {})
self.new.tap do |obj|
params.each do |key, val|
obj.send("#{key}=", val)
end
end
end
end
class Page < Struct.new(:title, :body); end
p1 = Page.new("title1", "body1")
p2 = Page.create(:body => "body2", :title => "title2")
puts p1.inspect # => <struct Page title="title1", body="body1">
puts p2.inspect # => <struct Page title="title2", body="body2">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment