Class: Blankity::Blank

Inherits:
BasicObject
Defined in:
lib/blankity/blank.rb

Overview

An “emptier” class than BasicObject, which undefines nearly all instance methods.

Not all methods are undefined (see Top for a class which does):

  • Methods which match /\A__.*__\z/ are not removed. Traditionally, these methods are expected to always be present (and undefing them warns you!). Ruby has two of these: __send__ and __id__

  • Private methods are not undefined, as each one of them is expected to be present (most of them are hooks, eg singleton_method_added), and aren’t easily accessible from external classes.

To make using Blank easier, its constructor allows you to pass a with: keyword argument, which will define singleton methods based on Object.

Direct Known Subclasses

Range, Value

Instance Method Summary collapse

Constructor Details

#initialize(vars: {}, with: [], hash: false) { ... } ⇒ Blank

Creates a new BlankValue, and defining singleton methods depending on the parameters

Example

# Make a empty instance
Blankity::Blank.new

# Include `Object#inspect`, so we can print with `p`
p Blankity::Blank.new(with: %i[inspect])

# Define a singleton method
p Blankity::Blank.new{ def cool?(other) = other == 3 }.cool?(3) #=> true

Parameters:

  • vars (Hash[interned, untyped]) (defaults to: {})

    an array of instance variables to define on self.

  • with (Array[interned]) (defaults to: [])

    a list of Object methods to define on self.

  • hash (bool) (defaults to: false)

    convenience argument, adds hash and eql? to with so the resulting type can be used as a key in Hashes

Yields:

  • if a block is given, runs it via instance_exec.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/blankity/blank.rb', line 58

def initialize(vars: {}, with: [], hash: false, &block)
  # If `hash` is supplied, then add `hash` and `eql?` to the list of methods to define
  with |= %i[hash eql?] if hash

  # Define any object methods requested by the end-user
  with.each do |method|
    __define_singleton_method__(method, ::Object.instance_method(method).bind(self))
  end

  # Assign all instance variables
  vars.each do |key, value|
    key = defined?(key.to_sym) ? key.to_sym : key.to_str
    key = "@#{key}" unless key.start_with? '@'

    ::Kernel.instance_method(:instance_variable_set).bind_call(self, key, value)
  end

  # If a block's provided, then `instance_exec`
  __instance_exec__(&__any__ = block) if block
end