lib/imap_guard/guard.rb in imap_guard-1.2.0 vs lib/imap_guard/guard.rb in imap_guard-2.0.0

- old
+ new

@@ -3,27 +3,29 @@ require "net/imap" require "ostruct" require "mail" require "term/ansicolor" -String.send(:include, Term::ANSIColor) -Term::ANSIColor.coloring = STDOUT.isatty +String.include Term::ANSIColor +Term::ANSIColor.coloring = $stdout.isatty module ImapGuard # Guard allows you to process your mailboxes. class Guard # List of required settings REQUIRED_SETTINGS = %i[host port username password].freeze # List of optional settings OPTIONAL_SETTINGS = %i[read_only verbose].freeze + Settings = Struct.new("Settings", *(REQUIRED_SETTINGS + OPTIONAL_SETTINGS)) + # @return [Proc, nil] Matched emails are passed to this debug lambda if present attr_accessor :debug # @note The settings are frozen - # @return [OpenStruct] ImapGuard settings + # @return [Struct::Settings] ImapGuard settings attr_reader :settings # @return [String, nil] Currently selected mailbox attr_reader :mailbox @@ -84,11 +86,11 @@ # Runs operation on messages matching the query # @param query IMAP query # @param opration Lambda to call on each message # @return [void] def each(query) - operation = ->(message_id) { yield message_id } + operation = ->(message_id) { yield message_id } # rubocop:disable Style/ExplicitBlockArgument process query, operation end # Fetches a message from its UID # @return [Mail] @@ -135,11 +137,11 @@ result = true if block_given? || debug mail = fetch_mail message_id - debug.call(mail) if debug + debug.call(mail) if debug # rubocop:disable Style/SafeNavigation if block_given? result = yield(mail) verbose.print "(given filter result: #{result.inspect}) " end @@ -150,11 +152,13 @@ ensure expunge end def search(query) - raise TypeError, "Query must be either a string holding the entire search string, or a single-dimension array of search keywords and arguments." unless [Array, String].any? { |type| query.is_a? type } + unless [Array, String].any? { |type| query.is_a? type } + raise TypeError, "Query must be either a string holding the entire search string, or a single-dimension array of search keywords and arguments." + end messages = @imap.search query puts "Query on #{mailbox}: #{query.inspect}: #{messages.count} results".cyan messages @@ -176,10 +180,11 @@ raise ArgumentError, "Missing settings: #{missing}" unless missing.empty? unknown = settings.keys - REQUIRED_SETTINGS - OPTIONAL_SETTINGS raise ArgumentError, "Unknown settings: #{unknown}" unless unknown.empty? - @settings = OpenStruct.new(settings).freeze + struct = Settings.members.map { |member| settings.fetch(member, false) } + @settings = Settings.new(*struct).freeze puts "DRY-RUN MODE ENABLED".yellow.bold.negative if @settings.read_only end end end