Last active
August 29, 2015 14:11
-
-
Save alex-fedorov/ef2c059c4cd3b0917707 to your computer and use it in GitHub Desktop.
BetterStruct
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 BetterStruct < Struct | |
class << self | |
def new(*required, **properties) | |
super(*(required + properties.keys)) do | |
define_singleton_method(:_default_values) do | |
properties | |
end | |
end | |
end | |
def default_value_for(key) | |
_default_values.fetch(key) do | |
raise ArgumentError, "#{key} is required argument" | |
end | |
end | |
end | |
def initialize(**options) | |
super(*(_get_struct_values_from(options))) | |
end | |
def _get_struct_values_from(options) | |
members.map { |key| | |
options.fetch(key) { | |
self.class.default_value_for(key) | |
} | |
} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment