Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active June 3, 2020 18:58
Show Gist options
  • Select an option

  • Save krisleech/3fe462bfbadfa93f4a33ebb219a50602 to your computer and use it in GitHub Desktop.

Select an option

Save krisleech/3fe462bfbadfa93f4a33ebb219a50602 to your computer and use it in GitHub Desktop.
Module builder in Ruby

plain #new method

module Foo  
  class Bar < Module
    def initialize(options = {})
      super()
      puts options
    end
  end
end

class Pub
  include Foo::Bar.new(a: :b)
  include Foo::Bar.new
  include Foo::Bar # <- does not work as Bar is a class of type Class
end


Pub.new

Uppercase method

Note: class methods can be called via . or ::.

module Foo 
  def self.Bar(*args)
    Bar.new(*args)
  end

  class Bar < Module
    def initialize(options = {})
      super()
      puts options
    end
  end
end

class Pub
  include Foo::Bar(a: :b)
  include Foo::Bar()  
  include Foo::Bar # <- does not work as Bar class, of type Class, is returned, the Foo#Bar method is not called
end


Pub.new

Square brackets

module Foo
  class Bar < Module
    def self.[](options = {})
      new(options)
    end

    def initialize(options = {})
      super()
      puts options
    end
  end
end

class Pub
  include Foo::Bar[a: :b]
  include Foo::Bar[]  
  include Foo::Bar # does not work, Bar is a class of type Class, the `[]` method is not called
end


Pub.new

Method

module Foo
  def self.bar(options = {})
    Bar.new(options)
  end

  class Bar < Module    
    def initialize(options = {})
      super()
      puts options
    end
  end
end

class Pub
  include Foo.bar
  include Foo.bar(a: :b)
end


Pub.new
@molfar
Copy link

molfar commented Jun 3, 2020

Is there any way to configure module with block?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment