Method: FlexColumns::Util::DynamicMethodsModule#initialize

Defined in:
lib/flex_columns/util/dynamic_methods_module.rb

#initialize(target_class, name, &block) ⇒ DynamicMethodsModule

Creates a new instance. target_class is the Class into which this module should include itself; name is the name to which it should bind itself. (This will be bound as a constant inside that class, not at top-level on Object; so, for example, if target_class is User and name is Foo, then this module will end up named User::Foo, not simply Foo.)

If passed a block, the block will be evaluated in the context of this module, just like Module#new. Note that you should not use this to define methods that you want #remove_all_methods!, below, to remove; it won’t work. Any methods you add in this block using normal def will persist, even through #remove_all_methods!.

Raises:

  • (ArgumentError)


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/flex_columns/util/dynamic_methods_module.rb', line 34

def initialize(target_class, name, &block)
  raise ArgumentError, "Target class must be a Class, not: #{target_class.inspect}" unless target_class.kind_of?(Class)
  raise ArgumentError, "Name must be a Symbol or String, not: #{name.inspect}" unless name.kind_of?(Symbol) || name.kind_of?(String)

  @target_class = target_class
  @name = name.to_sym

  # Unfortunately, there appears to be no way to "un-include" a Module in Ruby -- so we have no way of replacing
  # an existing DynamicMethodsModule on the target class, which is what we'd really like to do in this situation.
  if @target_class.const_defined?(@name)
    existing = @target_class.const_get(@name)

    if existing && existing != self
      raise NameError, %{You tried to define a #{self.class.name} named #{name.inspect} on class #{target_class.name},
but that class already has a constant named #{name.inspect}: #{existing.inspect}}
    end
  end

  @target_class.const_set(@name, self)
  @target_class.send(:include, self)

  @methods_defined = { }

  super(&block)
end