Class: DiscourseDev::Post

Inherits:
Record
  • Object
show all
Defined in:
lib/discourse_dev/post.rb

Constant Summary

Constants inherited from Record

Record::DEFAULT_COUNT

Instance Attribute Summary collapse

Attributes inherited from Record

#model, #type

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Record

#current_count, #index, populate!, random

Constructor Details

#initialize(topic, count = DEFAULT_COUNT) ⇒ Post

Returns a new instance of Post.



11
12
13
14
15
16
17
18
19
20
21
# File 'lib/discourse_dev/post.rb', line 11

def initialize(topic, count = DEFAULT_COUNT)
  super(::Post, count)
  @topic = topic

  category = topic.category
  unless category.groups.blank?
    group_ids = category.groups.pluck(:id)
    @user_ids = ::GroupUser.where(group_id: group_ids).pluck(:user_id)
    @user_count = @user_ids.count
  end
end

Instance Attribute Details

#topicObject (readonly)

Returns the value of attribute topic.



9
10
11
# File 'lib/discourse_dev/post.rb', line 9

def topic
  @topic
end

Class Method Details

.add_replies!(args) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/discourse_dev/post.rb', line 54

def self.add_replies!(args)
  if !args[:topic_id]
    puts "Topic ID is required. Aborting."
    return
  end

  if !::Topic.find_by_id(args[:topic_id])
    puts "Topic ID does not match topic in DB, aborting."
    return
  end

  topic = ::Topic.find_by_id(args[:topic_id])
  count = args[:count] ? args[:count].to_i : 50

  puts "Creating #{count} replies in '#{topic.title}'"

  count.times do |i|
    @index = i
    begin
      reply = {
        topic_id: topic.id,
        raw: Faker::Markdown.sandwich(sentences: 5),
        skip_validations: true
      }
      PostCreator.new(User.random, reply).create!
    rescue ActiveRecord::RecordNotSaved => e
      puts e
    end
  end

  puts "Done!"
end

Instance Method Details

#create!Object



31
32
33
34
35
36
37
# File 'lib/discourse_dev/post.rb', line 31

def create!
  begin
    PostCreator.new(user, data).create!
  rescue ActiveRecord::RecordNotSaved => e
    puts e
  end
end

#dataObject



23
24
25
26
27
28
29
# File 'lib/discourse_dev/post.rb', line 23

def data
  {
    topic_id: topic.id,
    raw: Faker::Markdown.sandwich(sentences: 5),
    skip_validations: true
  }
end

#populate!Object



47
48
49
50
51
52
# File 'lib/discourse_dev/post.rb', line 47

def populate!
  @count.times do |i|
    @index = i
    create!
  end
end

#userObject



39
40
41
42
43
44
45
# File 'lib/discourse_dev/post.rb', line 39

def user
  return User.random if topic.category.groups.blank?
  return Discourse.system_user if @user_ids.blank?

  position = Faker::Number.between(from: 0, to: @user_count - 1)
  ::User.find(@user_ids[position])
end