Module: Obfusk::ADT::ClassMethods
- Defined in:
- lib/obfusk/adt.rb
Instance Method Summary collapse
- #_new(ctor, data = {}, &b) ⇒ Object
-
#constructors ⇒ Object
the constructors.
-
#import_constructors(scope, const = true) ⇒ Object
import the constructors into another namespace.
-
#inherited(subclass) ⇒ Object
duplicate constructors for subclasses.
-
#match(x, opts) ⇒ Object
pattern matching.
-
#new(*a, &b) ⇒ Object
record constructor; call with name of constructor and hash of keys to values.
Instance Method Details
#_new(ctor, data = {}, &b) ⇒ Object
41 42 43 44 |
# File 'lib/obfusk/adt.rb', line 41 def _new(ctor, data = {}, &b) c = constructors[ctor] c[:method].call *data.values_at(*c[:keys]), &b end |
#constructors ⇒ Object
the constructors
106 107 108 |
# File 'lib/obfusk/adt.rb', line 106 def constructors @constructors ||= {} end |
#import_constructors(scope, const = true) ⇒ Object
import the constructors into another namespace
111 112 113 114 115 116 117 |
# File 'lib/obfusk/adt.rb', line 111 def import_constructors(scope, const = true) constructors.each_pair do |k,v| m = method k scope.define_singleton_method(k) { |*a,&b| m[*a,&b] } scope.const_set k, v[:ctor] if const end end |
#inherited(subclass) ⇒ Object
duplicate constructors for subclasses
47 48 49 50 51 52 53 54 55 |
# File 'lib/obfusk/adt.rb', line 47 def inherited(subclass) return if ::Obfusk::ADT_Meta__[:inheriting].last ctors = constructors subclass.class_eval do ctors.each_pair do |k,v| constructor v[:name], *v[:keys], &v[:block] end end end |
#match(x, opts) ⇒ Object
pattern matching
120 121 122 123 124 125 126 |
# File 'lib/obfusk/adt.rb', line 120 def match(x, opts) raise ArgumentError, 'not an ADT' unless x.is_a?(::Obfusk::ADT) raise ArgumentError, "types do not match (#{x.class.superclass} for #{self})" \ unless x.class.superclass == self x.match opts end |
#new(*a, &b) ⇒ Object
record constructor; call with name of constructor and hash of keys to values
37 38 39 |
# File 'lib/obfusk/adt.rb', line 37 def new(*a, &b) ancestors.include?(::Obfusk::ADT::Constructor) ? super : _new(*a, &b) end |