Sha256: bf1d18acac8f7ad96cfbd8cd5de0f947e99ae351fec94fa0e7fc0ab21e6d3f74

Contents?: true

Size: 974 Bytes

Versions: 5

Compression:

Stored size: 974 Bytes

Contents

# frozen_string_literal: true

module Configurable
  extend ActiveSupport::Concern

  included do
    cattr_accessor(:configurations) { Set.new }
  end

  class_methods do
    def configurable_value(name, &block)
      configurable(name, block)
      configurations << name.to_sym
    end

    def configurable_boolean(name, default: false)
      configurable(name, -> { default })
      alias_method :"#{name}?", name
      configurations << :"#{name}?"
    end

    private

    def configurable(name, default_callable)
      ivar = "@#{name}"

      define_method(name) do |*args|
        if args.empty?
          instance_variable_set(ivar, default_callable.call) unless instance_variable_defined?(ivar)
          instance_variable_get(ivar)
        elsif args.length == 1
          instance_variable_set(ivar, args.first)
        else
          raise ArgumentError, "wrong number of arguments (given #{args.length}, expected 1)"
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
demo_mode-1.4.0 lib/demo_mode/concerns/configurable.rb
demo_mode-1.3.0 lib/demo_mode/concerns/configurable.rb
demo_mode-1.2.3 lib/demo_mode/concerns/configurable.rb
demo_mode-1.2.2 lib/demo_mode/concerns/configurable.rb
demo_mode-1.2.1 lib/demo_mode/concerns/configurable.rb