class Typist::Constructor
This class represents a data-type contstructor.
Attributes
name[R]
vars[R]
Public Class Methods
new(name, *vars)
click to toggle source
Create a new constructor with the given name and instance variable(s).
# File lib/typist/constructor.rb, line 6 def initialize(name, *vars) @name = name @vars = vars end
Public Instance Methods
define!(context)
click to toggle source
Turn the constructor into a class definition, then define a convenience method in the given module.
# File lib/typist/constructor.rb, line 18 def define!(context) get_class.tap do |klass| define_class(context, klass) define_initializer(context, klass) end end
get_class()
click to toggle source
Get the Class that this Constructor
defines.
# File lib/typist/constructor.rb, line 12 def get_class @class ||= Class.new end
Private Instance Methods
define_class(context, klass)
click to toggle source
# File lib/typist/constructor.rb, line 25 def define_class(context, klass) attrs = vars klass.instance_eval do include context attr_accessor(*attrs) define_method(:initialize) do |hash = {}| hash.each { |key, val| instance_variable_set(:"@#{key}", val) } end end context.const_set(name, klass) end
define_initializer(context, klass)
click to toggle source
# File lib/typist/constructor.rb, line 39 def define_initializer(context, klass) method_name = Typist::Util.snakeify(name) context.module_eval do define_method(method_name) { |*args| klass.new(*args) } module_function method_name end end