Skip to content

Instantly share code, notes, and snippets.

@localhostdotdev
Created March 25, 2019 15:02
Show Gist options
  • Save localhostdotdev/daeb12e4af2bfedbb6f18f2c5c7b7a86 to your computer and use it in GitHub Desktop.
Save localhostdotdev/daeb12e4af2bfedbb6f18f2c5c7b7a86 to your computer and use it in GitHub Desktop.
Struct.from_hash: the best of Struct and OpenStruct combined :)
class Struct
def self.from_hash(attributes)
new(*attributes.keys).new(*attributes.values)
end
end
user = Struct.from_hash(id: 1, name: "?")
user.id # => 1
user.names # => NoMethodError (undefined method `names' for #<struct id=1, name="?">)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment