Created
September 3, 2011 13:34
-
-
Save blaix/1191188 to your computer and use it in GitHub Desktop.
Struct with an OpenStruct-style initializer
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
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