Last active
November 18, 2020 18:44
-
-
Save serradura/8a8c410c86246538f6bcc6c191581dd7 to your computer and use it in GitHub Desktop.
Example of how to use the u-observers `#on()` and `#once()` methods to handle events and their custom scopes.
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
require 'bundler/inline' | |
require 'securerandom' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'u-observers', '~> 2.2.1' | |
end | |
class DoSomethingWithFiles | |
include Micro::Observers | |
RemoveFile = -> file { File.delete(file) } | |
PrintFilename = -> file { puts File.basename(file) } | |
def initialize(content1:, content2:) | |
@content1, @content2 = content1, content2 | |
end | |
def call | |
write_content_in_a_file(@content1) | |
write_content_in_a_file(@content2) | |
observers.notify!(:print_filename, :remove_file) | |
end | |
private | |
def write_content_in_a_file(content) | |
File.open("./#{SecureRandom.hex}.txt", 'w') { |f| f.puts(content); f }.tap do |file| | |
observers.once(event: :remove_file, call: RemoveFile, with: file) | |
observers.once(event: :print_filename, call: PrintFilename, with: file) | |
end | |
end | |
end | |
DoSomethingWithFiles.new(content1: 'foo', content2: 'bar').call |
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
require 'securerandom' | |
class DoSomethingWithFiles | |
def initialize(content1:, content2:) | |
@content1, @content2 = content1, content2 | |
end | |
def call | |
file1 = write_content_in_a_file(@content1) | |
file2 = write_content_in_a_file(@content2) | |
[file1, file2].each { |file| puts File.basename(file) } | |
[file1, file2].each { |file| File.delete(file.path) } | |
end | |
private | |
def write_content_in_a_file(content) | |
File.open("./#{SecureRandom.hex}.txt", 'w') { |f| f.puts(content); f } | |
end | |
end | |
DoSomethingWithFiles.new(content1: 'foo', content2: 'bar').call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment