Created
October 28, 2013 17:26
-
-
Save bestie/7200969 to your computer and use it in GitHub Desktop.
An HStruct that also contains type data,
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
require 'hstruct' | |
class TypedStruct < HStruct | |
def self.schema(schema = nil) | |
@__schema ||= schema | |
end | |
end | |
def TypedStruct(members_hash, &block) | |
member_names = members_hash.keys | |
TypedStruct.new(*member_names, &block).tap { |struct| | |
struct.schema(members_hash) | |
} | |
end | |
# Example | |
Condition = TypedStruct( | |
id: String, | |
concept_id: Fixnum, | |
started_at: Time, | |
finished_at: Time, | |
patient_id: String, | |
medications: Array, | |
procedures: Array, | |
professionals: Array, | |
) do | |
# ... | |
end | |
p Condition.schema | |
=> | |
{ | |
:id => String < Object, | |
:concept_id => Fixnum < Integer, | |
:started_at => Time < Object, | |
:finished_at => Time < Object, | |
:patient_id => String < Object, | |
:medications => Array < Object, | |
:procedures => Array < Object, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not sure if I like the uppercase method overloading but mimicking the way that Struct.new returns a class is a bit crazy.
If you're curious check out the rubinius implementation of Struct https://github.com/rubinius/rubinius/blob/f290f2a4f7c59894ea567f9cb05cbe00a31a6654/kernel/common/struct.rb