Module: Tins::BlankSlate

Defined in:
lib/tins/dslkit.rb

Overview

A module that provides blank slate class creation functionality.

This module enables the creation of anonymous classes with restricted method sets, allowing for precise control over object interfaces. Blank slates are useful for security, DSL construction, testing, and creating clean API surfaces.

Examples:

Basic usage with method whitelisting

# Create a class that only responds to :length and :upcase methods
RestrictedClass = Tins::BlankSlate.with(:length, :upcase, superclass: String)

obj = RestrictedClass.new('foo')
obj.length         # => 3
obj.upcase         # => 'FOO'
obj.strip          # NoMethodError

Class Method Summary collapse

Class Method Details

.with(*ids) ⇒ Class

Creates an anonymous blank slate class with restricted method set.

This method generates a new class that inherits from the specified superclass (or Object by default) and removes all methods except those explicitly allowed. The allowed methods can be specified as symbols, strings, or regular expressions.

Parameters:

  • ids (Array<Symbol,String,Regexp>)

    Method names or patterns to allow

  • opts (Hash)

    a customizable set of options

Returns:

  • (Class)

    A new anonymous class with only the specified methods available



593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/tins/dslkit.rb', line 593

def self.with(*ids)
  opts = Hash === ids.last ? ids.pop : {}
  ids = ids.map { |id| Regexp === id ? id : id.to_s }
  klass = opts[:superclass] ? Class.new(opts[:superclass]) : Class.new
  klass.instance_eval do
    instance_methods.each do |m|
      m = m.to_s
      undef_method m unless m =~ /^(__|object_id)/ or ids.any? { |i| i === m }
    end
  end
  klass
end