Class: DiscourseTheme::Watcher

Inherits:
Object
  • Object
show all
Defined in:
lib/discourse_theme/watcher.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dir:, uploader:) ⇒ Watcher

Returns a new instance of Watcher.



11
12
13
14
# File 'lib/discourse_theme/watcher.rb', line 11

def initialize(dir:, uploader:)
  @dir = dir
  @uploader = uploader
end

Class Method Details

.return_immediately!Object



3
4
5
# File 'lib/discourse_theme/watcher.rb', line 3

def self.return_immediately!
  @return_immediately = true
end

.return_immediately?Boolean

Returns:

  • (Boolean)


7
8
9
# File 'lib/discourse_theme/watcher.rb', line 7

def self.return_immediately?
  !!@return_immediately
end

Instance Method Details

#watchObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/discourse_theme/watcher.rb', line 16

def watch
  listener = Listen.to(@dir) do |modified, added, removed|
    begin
      if modified.length == 1 &&
          added.length == 0 &&
          removed.length == 0 &&
          (resolved = resolve_file(modified[0]))

        target, name, type_id = resolved
        Cli.progress "Fast updating #{target}.scss"

        @uploader.upload_theme_field(
          target: target,
          name: name,
          value: File.read(modified[0]),
          type_id: type_id
        )
      else
        count = modified.length + added.length + removed.length
        if count > 1
          Cli.progress "Detected changes in #{count} files, uploading theme"
        else
          filename = modified[0] || added[0] || removed[0]
          Cli.progress "Detected changes in #{filename.gsub(@dir, '')}, uploading theme"
        end
        @uploader.upload_full_theme
      end
      Cli.success "Done! Watching for changes..."
    rescue DiscourseTheme::ThemeError => e
      Cli.error "#{e.message}"
      Cli.progress "Watching for changes..."
    end
  end

  listener.start
  sleep unless self.class.return_immediately?
end