Class: CableReady::ChannelGenerator

Inherits:
Rails::Generators::NamedBase
  • Object
show all
Defined in:
lib/generators/cable_ready/channel_generator.rb

Instance Method Summary collapse

Instance Method Details

#check_optionsObject



17
18
19
20
21
22
# File 'lib/generators/cable_ready/channel_generator.rb', line 17

def check_options
  if options.key?(:stream_from) && options.key?(:stream_for)
    puts "Can't specify --stream-from and --stream-for at the same time"
    exit
  end
end

#create_channelObject



24
25
26
# File 'lib/generators/cable_ready/channel_generator.rb', line 24

def create_channel
  generate "channel", file_name, "--skip"
end

#destroy_not_supportedObject



10
11
12
13
14
15
# File 'lib/generators/cable_ready/channel_generator.rb', line 10

def destroy_not_supported
  if behavior == :revoke
    puts "Sorry, we don't support destroying generated channels.\nDelete the Action Cable channel class, as well as any corresponding JavaScript classes."
    exit
  end
end

#enhance_channelsObject



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
53
54
55
56
57
58
59
60
61
62
# File 'lib/generators/cable_ready/channel_generator.rb', line 28

def enhance_channels
  @entrypoint = [
    "app/javascript",
    "app/frontend"
  ].find { |path| File.exist?(Rails.root.join(path)) } || "app/javascript"
  puts "Where do JavaScript files live in your app? Our best guess is: \e[1m#{@entrypoint}\e[22m 🤔"
  puts "Press enter to accept this, or type a different path."
  print "> "
  input = Rails.env.test? ? "tmp/app/javascript" : $stdin.gets.chomp
  @entrypoint = input unless input.blank?
  @js_channel = "#{@entrypoint}/channels/#{file_name}_channel.js"

  if using_broadcast_to?
    if using_stimulus?
      template("#{@entrypoint}/controllers/%file_name%_controller.js")
      Rails.root.join(@js_channel).delete
    else
      gsub_file "app/channels/#{file_name}_channel.rb", /# stream_from.*\n/, "stream_for #{resource}.find(params[:id])\n", verbose: false
      gsub_file @js_channel, /"#{resource}Channel"/, verbose: false do
        <<-JS

{
  channel: "#{resource}Channel",
  id: 1
}
        JS
      end
      doctor_javascript_channel_class
      puts "\nDon't forget to update the id in the channel subscription: #{@js_channel}\nIt's currently set to 1; you'll want to change that to a dynamic value based on something in your DOM."
    end
  else
    gsub_file "app/channels/#{file_name}_channel.rb", /# stream_from.*\n/, "stream_from \"#{identifier}\"\n", verbose: false
    doctor_javascript_channel_class
  end
end