Class: Liquefied

Inherits:
BasicObject
Defined in:
lib/liquefied.rb,
lib/liquefied/version.rb

Constant Summary collapse

METHOD_ALIASES =
[
  [:to_s, :to_str]
]
CAST_PREFIX =
"to_".freeze
VERSION =
"0.7.0"

Instance Method Summary collapse

Constructor Details

#initialize(original, *default_args, method: :to_s, &default_block) ⇒ Liquefied

Public: Wrap an object with a default finalizer method

The object remains wrapped and responds to all its original methods until the finalizer method is called. The finalizer method can be set up with default arguments, which are passed if the method is called implicitly or with no options.

object - The original value to wrap

Examples:

Liquefied.new(12.333, method: [:to_s]) { |val| "%.2f" % val }
Liquefied.new(Date.new(2016,1,1), :to_s, :long)
#=> "January 1, 2016"


25
26
27
28
29
30
# File 'lib/liquefied.rb', line 25

def initialize(original, *default_args, method: :to_s, &default_block)
  @original = original
  @finalizer = ::Kernel::Array(method)
  @default_args = default_args
  @default_block = default_block
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object (private)



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/liquefied.rb', line 50

def method_missing(method, *args, &block)
  if (final_method = _get_finalizer(method))
    _finalize!(final_method, *args, &block)
  else
    result = @original.public_send(method, *args, &block)
    if result.class == @original.class
      ::Liquefied.new(result, *@default_args, method: @finalizer, &@default_block)
    else
      result
    end
  end
end

Instance Method Details

#==(other) ⇒ Object



40
41
42
# File 'lib/liquefied.rb', line 40

def ==(other)
  @original == other
end

#inspectObject



32
33
34
# File 'lib/liquefied.rb', line 32

def inspect
  "#<Liquefied(#{@original.class}):#{@original.object_id}>"
end

#itselfObject



36
37
38
# File 'lib/liquefied.rb', line 36

def itself
  @original
end

#respond_to?(meth, include_all = false) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/liquefied.rb', line 44

def respond_to?(meth, include_all=false)
  @original.respond_to?(meth, include_all)
end