lib/config_default/struct.rb in config_default-0.1.2 vs lib/config_default/struct.rb in config_default-0.2.0

- old
+ new

@@ -1,36 +1,28 @@ # frozen_string_literal: true class ConfigDefault::Struct RESERVED_METHODS = %i[method_missing respond_to_missing? to_hash].freeze - def initialize(attributes = {}, recursive: false, allow_nil: false) + def initialize(attributes:, recursive: false, allow_nil: false) @attributes = ActiveSupport::HashWithIndifferentAccess.new(attributes) @allow_nil = allow_nil @recursive = recursive - if @recursive - @attributes.each do |key, value| - next unless value.is_a?(Hash) - @attributes[key] = self.class.new(value, recursive: @recursive, allow_nil: @allow_nil) - end - end + make_recursive! + define_methods! - @attributes.each do |key, value| - next if RESERVED_METHODS.include?(key.to_sym) - define_singleton_method(key) { value } - end - @attributes.freeze end def [](key) @attributes[key] end def method_missing(method, *_args) - raise StandardError.new("There is no option :#{method} in configuration.") unless @allow_nil + return if @allow_nil + raise StandardError.new("There is no option :#{method} in configuration.") end def respond_to_missing?(*_args) true end @@ -44,7 +36,29 @@ dup[key] = value.to_hash end end dup + end + + private + + def make_recursive! + return unless @recursive + + @attributes.each do |key, value| + next unless value.is_a?(Hash) + @attributes[key] = self.class.new( + attributes: value, + recursive: @recursive, + allow_nil: @allow_nil, + ) + end + end + + def define_methods! + @attributes.each do |key, value| + next if RESERVED_METHODS.include?(key.to_sym) + define_singleton_method(key) { value } + end end end