Skip to content

Instantly share code, notes, and snippets.

@dmytrotkk
Created November 14, 2017 13:07
Show Gist options
  • Save dmytrotkk/9d8cdd18b8cd5f283ff5538f11775c07 to your computer and use it in GitHub Desktop.
Save dmytrotkk/9d8cdd18b8cd5f283ff5538f11775c07 to your computer and use it in GitHub Desktop.
Rails app: Organizing `lib` directory with static services

Organizing lib directory with static services

base_service.rb
    module Core end

    module Core::BaseService
      extend self
    
      def bar
        puts 'bar'
      end
    end
service.rb
    require_relative './base_service.rb'
    
    module Core::Payments
    	module Service 
    	    extend self, Core::BaseService
    	    
			def fuu
				puts 'fuuu'
			end
    	end
    end
    
    Core::Payments::Service.bar # => 'bar'
    Core::Payments::Service.fuu # => 'fuuu'
Folders structure example
lib
|
|---core
    |
    |---base_service.rb
    |---payments
        |
        |---service.rb
        |---confing_or_something.rb


Comparison: module_function vs extend self

module_function makes the given instance methods private, then duplicates and puts them into the module's metaclass as public methods.
extend self adds all instance methods to the module's singleton, leaving their visibilities unchanged.

extend self

    module Mathematics
      extend self
    
      def calc
        42
      end
    end

module_function

  module Mathematics
    module_function

    def calc
      42
    end
  end

See more: https://idiosyncratic-ruby.com/8-self-improvement.html

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