Module: Tins::SymbolMaker

Defined in:
lib/tins/dslkit.rb

Overview

Note:

Tins::SymbolMaker is an alternative for Tins::Constant in this example. While both approaches can be used to create symbolic references, SymbolMaker makes method calls return symbols, whereas Constant creates only the required constants. SymbolMaker can make debugging more difficult because it’s less clear when a method call is returning a symbol versus being a real method call, typo, etc.

A module that provides method missing handler for symbolic method calls.

This module enables dynamic method resolution by converting missing method calls into symbols. When a method is called that doesn’t exist, instead of raising NoMethodError, the method name is returned as a symbol. This is particularly useful for creating DSLs, configuration systems, and symbolic interfaces.

Examples:

Combined with DSLAccessor for powerful configuration

class CoffeeMaker
  include Tins::SymbolMaker
  extend Tins::DSLAccessor

  dsl_accessor(:state) { :off }
  dsl_accessor :allowed_states, :on, :off

  def process
    allowed_states.include?(state) or fail "Explode!!!"
    if state == on
      puts "Make coffee."
    else
      puts "Idle..."
    end
  end
end

cm = CoffeeMaker.new
cm.instance_eval do
  state      # => :off
  state on   # Sets state to :on
  # state tnt # should be avoided
  state      # => :on
  process    # => outputs "Make coffee."
end

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(id, *args) ⇒ Symbol

Handles missing method calls by returning the method name as a symbol.

This method is called when Ruby cannot find a method in the current object. Instead of raising NoMethodError, it returns the method name as a symbol, enabling symbolic method handling throughout the application. Only methods with no arguments are converted to symbols; methods with arguments will raise the normal NoMethodError.

Parameters:

  • id (Symbol)

    The missing method name

  • args (Array)

    Arguments passed to the missing method

Returns:

  • (Symbol)

    The method name as a symbol (when no arguments)



530
531
532
533
534
535
536
# File 'lib/tins/dslkit.rb', line 530

def method_missing(id, *args)
  if args.empty?
    id
  else
    super
  end
end