Module: ModalSupport::BracketConstructor
- Defined in:
- lib/modalsupport/mixins/bracket_constructor.rb
Overview
Mixin that adds a [] operator constructor to a class, which is a not-so-ugly alternative to the new
method.
class A
include BracketConstructor
def initialize(a)
puts "A.new(#{a.inspect})"
end
end
A[100] # => A.new(100)
In Rails, this kind of constructor has an advantage over a function such as:
def A(*args)
A.new(*args)
end
With the A[] notation we’ve referenced the class name via the constant A, which in Rails brings in the declaration for A automatically, whereas the method A() won’t be found unless the file which declares it is explicitely required.
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Class Method Details
.included(base) ⇒ Object
26 27 28 |
# File 'lib/modalsupport/mixins/bracket_constructor.rb', line 26 def self.included(base) base.extend ClassMethods end |