class Typist::Func
This class defines the `func` DSL.
Attributes
block[R]
matches[R]
name[R]
Public Class Methods
new(name, &block)
click to toggle source
Create a new function with the given name (String/Symbol). If a block is given, it will be evaluated in the context of the new instance.
# File lib/typist/func.rb, line 7 def initialize(name, &block) @name = name @matches = {} @block = block end
Public Instance Methods
define!(context)
click to toggle source
Given a module define this function, plus the pattern matches for all of its subclasses.
# File lib/typist/func.rb, line 20 def define!(context) instance_eval(&block) unless block.nil? define_base(context) matches.each { |klass, block| define_match(context, klass, &block) } context end
match(klass, &block)
click to toggle source
Pattern match against the given class.
# File lib/typist/func.rb, line 14 def match(klass, &block) matches[klass] = block end
Private Instance Methods
define_base(context)
click to toggle source
# File lib/typist/func.rb, line 27 def define_base(context) method_name = name context.class_eval do define_method(method_name) do |*_, &_| raise Typist::Error::PatternError, "Patterns not exhaustive in #{context}##{method_name}" end end end
define_match(context, klass, &block)
click to toggle source
# File lib/typist/func.rb, line 39 def define_match(context, klass, &block) unless klass.ancestors.include?(context) raise Typist::Error::MatchError, "#{klass} is not a valid constructor for #{context}" end method_name = name klass.class_eval { define_method(method_name, &block) } end