Class: SearchUI::Wrapper

Inherits:
BasicObject
Defined in:
lib/search_ui/wrapper.rb

Overview

Wrapper around an arbitrary value that:

  • Exposes the wrapped object via value.

  • Allows you to supply a custom string representation (display).

  • Delegates all other method calls straight through to the wrapped value.

This is handy when you want to keep your objects printable in a particular colour or format (e.g. with Term::ANSIColor) while still behaving like the original object for comparisons, length checks, etc.

Examples:

Basic usage

wrapper = SearchUI::Wrapper.new('foo', display: '🟢 foo')
puts wrapper          # => "🟢 foo"
wrapper.length        # => 3 (delegated to the string)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, display: value.to_s) ⇒ Wrapper

Initializes a new wrapper.

Parameters:

  • value (Object)

    The object you want to wrap.

  • options (Hash)

    a customizable set of options



22
23
24
25
# File 'lib/search_ui/wrapper.rb', line 22

def initialize(value, display: value.to_s)
  @value   = value
  @display = display
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*a, **o) { ... } ⇒ Object

Delegates any unknown method call to the wrapped value.

This makes the wrapper behave like a transparent proxy for most operations (e.g. length, upcase, etc.).

Parameters:

  • a (Array)

    Method name and arguments.

  • o (Hash)

    Keyword arguments.

Yields:

  • b Optional block passed to the underlying method.



64
65
66
# File 'lib/search_ui/wrapper.rb', line 64

def method_missing(*a, **o, &b)
  @value.__send__(*a, **o, &b)
end

Instance Attribute Details

#valueObject (readonly)

Returns the wrapped object.

Returns:

  • (Object)


30
31
32
# File 'lib/search_ui/wrapper.rb', line 30

def value
  @value
end

Instance Method Details

#==(other) ⇒ Boolean Also known as: eql?

Equality comparison.

Two wrappers are equal if their underlying values compare equal to the other argument.

Parameters:

  • other (Object)

    The value or another wrapper to compare against.

Returns:

  • (Boolean)


38
39
40
# File 'lib/search_ui/wrapper.rb', line 38

def ==(other)
  @value == other
end

#to_sString Also known as: to_str

String representation of the wrapped object.

If a custom display was supplied, that string is returned; otherwise, it falls back to value.to_s.

Returns:

  • (String)


50
51
52
# File 'lib/search_ui/wrapper.rb', line 50

def to_s
  @display.to_s
end