Module: PowerStruct
- Defined in:
- lib/power_struct.rb,
lib/power_struct/version.rb
Defined Under Namespace
Classes: Base
Constant Summary collapse
- ArgumentError =
Class.new(::ArgumentError)
- VERSION =
"0.1.0"
Class Method Summary collapse
Class Method Details
.new(*mandatory_attributes, **defaults, &block) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/power_struct.rb', line 6 def self.new(*mandatory_attributes, **defaults, &block) raise ArgumentError, "pass attribute names as symbols" unless \ mandatory_attributes.all? { |attribute| attribute.is_a?(Symbol) } Class.new(Base) do class << self attr_reader :mandatory_attributes, :attribute_defaults end @mandatory_attributes = mandatory_attributes @attribute_defaults = defaults def initialize(*flat_arguments, **arguments) raise ArgumentError, "pass parameters as hash arguments" if flat_arguments.any? unless (self.class.mandatory_attributes - arguments.keys).empty? raise ArgumentError, "missing argument(s) " + (self.class.mandatory_attributes - arguments.keys).map(&:inspect).join(", ") end unless ( arguments.keys - self.class.mandatory_attributes - self.class.attribute_defaults.keys ).none? raise ArgumentError, "excess argument(s) " + (arguments.keys - self.class.mandatory_attributes - self.class.attribute_defaults.keys) .map(&:inspect).join(", ") end self.class.attribute_defaults.each do |attribute, default| self.public_send("#{attribute}=", default) end arguments.each do |attribute, value| self.public_send("#{attribute}=", value) end end attr_accessor(*mandatory_attributes, *defaults.keys) class_eval(&block) if block end end |