Skip to main content

Setup in a Rails project

  • As always, add a new entry to your Gemfile as the first step.

    gem "convenient_service", "~> 0.19.1"
  • Then run bundle to install the gem.

    bundle install
  • To mimic the classic Rails folder structure, you may consider creating app/services directory like so:

    mkdir -p app/services

    But feel free to select other directory if you like.

    app/services is chosen for a demonstration since it is autoloaded by Rails.

  • Place a configuration file into it.

    A common name may be application_service/config.rb.

    mkdir -p app/services/application_service && touch app/services/application_service/config.rb

    This example utilizes Standard or Rails configs, but you can also pick any other predefined configuration, create customization, or even have multiple configs.

    app/services/application_service/config.rb
    module ApplicationService
    module Config
    include ConvenientService::Config

    included do
    include ConvenientService::Standard::Config
    end
    end
    end
  • Now you have everything ready to create fancy services for your application.

    (Do not forget to include config into them 🙂)

    app/services/print_what_cow_says.rb
    class PrintWhatCowSays
    include ApplicationService::Config

    attr_reader :text

    def initialize(text: "Hello World!")
    @text = text
    end

    def result
    puts template(text)

    success
    end

    private

    ##
    # Copied with ❤️ from https://github.com/gaborbata/rosetta-cow
    #
    def template(text)
    cloud =
    <<~HEREDOC
    #{border(text, "_")}
    < #{text} >
    #{border(text, "-")}
    HEREDOC

    cow =
    <<~'HEREDOC'.split("\n").map { |line| " " * 10 + line }.join("\n")
    \ ^__^
    \ (oo)\_______
    (__)\ )\/\
    ||----w |
    || ||
    HEREDOC

    cloud + cow
    end

    def border(text, char)
    char * (text.length + 2)
    end
    end
  • That's it. Happy coding!