Sha256: 735636f8da31d2509e8814b4e8f2ad67946b35dadc1d54752cfaa174a1423e0f

Contents?: true

Size: 1.41 KB

Versions: 1

Compression:

Stored size: 1.41 KB

Contents

module SmartInit
  def is_callable
    define_singleton_method :call do |*parameters|
      new(*parameters).call
    end
  end

  def initialize_with *attributes
    required_attrs = attributes.select { |attr| attr.is_a?(Symbol) }
    default_value_attrs = attributes.select { |attr| attr.is_a?(Hash) }.first || {}

    define_method :initialize do |*parameters|
      if required_attrs.count > parameters.first.count
        raise ArgumentError, "wrong number of arguments (given #{parameters.count}, expected at least #{required_attrs.count})"
      end

      (required_attrs + default_value_attrs.keys).each do |attribute|
        value = parameters.first[attribute] || default_value_attrs[attribute]
        instance_variable_set("@#{attribute}", value)
      end
    end

    instance_eval do
      private

      attr_reader *(required_attrs + default_value_attrs.keys)
    end
  end

  def initialize_with_v1 *attributes
    define_method :initialize do |*parameters|
      if attributes.count != parameters.count
        raise ArgumentError, "wrong number of arguments (given #{parameters.count}, expected #{attributes.count})"
      end

      attributes.zip(parameters).each do |pair|
        name = pair[0]
        value = pair[1]
        instance_variable_set("@#{name}", value)
      end
    end

    instance_eval do
      private

      attr_reader *attributes
    end
  end

end

class SmartInit::Base
  extend SmartInit
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
smart_init-3.0.0 lib/smart_init/main.rb