Class: Hikkmemo::Worker

Inherits:
Object
  • Object
show all
Defined in:
lib/hikkmemo/worker.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(db, reader) ⇒ Worker

Returns a new instance of Worker.



6
7
8
9
10
11
# File 'lib/hikkmemo/worker.rb', line 6

def initialize(db, reader)
  @db, @reader = db, reader
  @on_add_thread = []
  @on_add_post   = []
  @timeout       = 30
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



3
4
5
# File 'lib/hikkmemo/worker.rb', line 3

def db
  @db
end

#threadObject

Returns the value of attribute thread.



4
5
6
# File 'lib/hikkmemo/worker.rb', line 4

def thread
  @thread
end

#timeoutObject

Returns the value of attribute timeout.



4
5
6
# File 'lib/hikkmemo/worker.rb', line 4

def timeout
  @timeout
end

Instance Method Details

#add_post(post_node, thread_id) ⇒ Object



13
14
15
16
17
18
19
# File 'lib/hikkmemo/worker.rb', line 13

def add_post(post_node, thread_id)
  data = @reader.post_data(post_node, thread_id)
  unless @db[:posts][:id => data[:id]]
    @db[:posts].insert(data)
    @on_add_post.each {|p| p.(data) }
  end
end

#on_add_post(&p) ⇒ Object



21
# File 'lib/hikkmemo/worker.rb', line 21

def on_add_post  (&p) @on_add_post   += [p] end

#on_add_thread(&p) ⇒ Object



22
# File 'lib/hikkmemo/worker.rb', line 22

def on_add_thread(&p) @on_add_thread += [p] end

#runObject



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/hikkmemo/worker.rb', line 24

def run
  @thread ||= Thread.new do
    loop do
      @reader.fringe.each do |tid,pid|
        thread = @db[:threads][:id => tid]
        if thread
          if thread[:last_post] != pid
            @reader.thread_posts(tid, after: thread[:last_post])
              .each {|p| add_post(p, tid) }
            @db[:threads][:id => tid] = { :last_post => pid }
          end
        else
          posts = @reader.thread_posts(tid)
          date  = @reader.post_data(posts[0], tid)[:date]
          data  = { :id => tid, :last_post => pid, :date => date }
          @db[:threads].insert(data)
          @on_add_thread.each {|p| p.(data) }
          posts.each {|p| add_post(p, tid) }
        end
      end
      sleep @timeout
    end
  end
end