Created
January 28, 2022 22:00
-
-
Save ccyrille/a93fd4eda542662e2d7192616b3ffbc3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Service module | |
| # | |
| # Example usage : | |
| # ``` | |
| # class SayHello | |
| # include Service | |
| # | |
| # attr_accessor :name | |
| # | |
| # def call | |
| # puts "Hello #{name} !" | |
| # end | |
| # end | |
| # | |
| # SayHello.call(name: "toto") | |
| # ``` | |
| module Service | |
| def self.included(base) | |
| base.class_eval do | |
| # Proxy to #call instance method | |
| def self.call(*args) | |
| new(*args).call | |
| end | |
| # Service initializer | |
| def initialize(args={}) | |
| unless args.is_a?(Hash) | |
| raise ArgumentError, "provided 'args' should be a hash." | |
| end | |
| args.each { |k,v| send("#{k.to_s}=", v) } | |
| end | |
| end | |
| end | |
| end |
Author
Hon! Clever :)
Merci pour le détail du pourquoi.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bobmaerten l'avantage de "laisser passer" ce qui n'est pas un hash au niveau du
callpour s'en protéger par la suite (ArgumentErrorau niveau deinitialize) est qu'on renvoie une exception nettement plus explicite si autre chose qu'un hash est passé ;-)Version avec double splat :
Version proposée :