Class: Liquidscript::Compiler::Base::Callable

Inherits:
Object
  • Object
show all
Defined in:
lib/liquidscript/compiler/base/callable.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bind, block, prefix = "compile_") ⇒ Callable

Initialize the callable.

Parameters:

  • bind (Object)

    the object that holds the method (if this represents a method call).

  • block (Symbol, Block)

    if it’s a Symbol, it represents a method on bind; otherwise, it’s a pure block.



14
15
16
17
18
19
20
21
# File 'lib/liquidscript/compiler/base/callable.rb', line 14

def initialize(bind, block, prefix = "compile_")
  @bind = bind
  @block = if block.is_a? Symbol
    :"#{prefix}#{block}"
  else
    block
  end
end

Instance Attribute Details

#bindObject

Returns the value of attribute bind.



6
7
8
# File 'lib/liquidscript/compiler/base/callable.rb', line 6

def bind
  @bind
end

Instance Method Details

#apply(*args) ⇒ Object

This applies only as many arguments as the block or function needs. This is just so that calling a method is easier, so the developer doesn’t have to worry about arity and such.

Parameters:

  • args (Object)

    passed to the call.

Returns:

  • (Object)

    the result of the call.



44
45
46
47
48
49
50
51
52
# File 'lib/liquidscript/compiler/base/callable.rb', line 44

def apply(*args)
  return call if arity == 0

  if block_given?
    call(*yield[0..arity])
  else
    call(*args[0..arity])
  end
end

#arityNumeric

How many arguments the call can take. If this represents a block that has tricks enabled, then this isn’t an issue; if it’s a method call, however, it becomes important.

Returns:

  • (Numeric)

    the number of arguments it can take.



59
60
61
62
63
64
65
# File 'lib/liquidscript/compiler/base/callable.rb', line 59

def arity
  if @block.is_a? Symbol
    @bind.method(@block).arity
  else
    @block.arity
  end
end

#call(*args) ⇒ Object

Calls the thing that this represents. If this represents a method call, it calls the method with the given arguments; otherwise, it calls #call on the block.

Parameters:

  • args (Object)

    passed to the call.

Returns:

  • (Object)

    the result of the call.



29
30
31
32
33
34
35
# File 'lib/liquidscript/compiler/base/callable.rb', line 29

def call(*args)
  if @block.is_a? Symbol
    @bind.public_send(@block, *args)
  elsif @block.respond_to?(:call)
    @block.call(*args)
  end
end