Class: CypressViewportUpdater::CypressConfigJsFile

Inherits:
ExistingGithubFile show all
Defined in:
app/sidekiq/cypress_viewport_updater/cypress_config_js_file.rb

Constant Summary collapse

VIEWPORT_TYPES =
{
  vaTopMobileViewports: 'mobile',
  vaTopTabletViewports: 'tablet',
  vaTopDesktopViewports: 'desktop'
}.freeze
VIEWPORT_PROPS =
%w[
  rank:
  devicesWithViewport:
  percentTraffic:
  percentTrafficPeriod:
  viewportPreset:
  width:
  height:
].freeze
WRAP_VALUE_IN_QUOTES =
%w[list: devicesWithViewport: percentTraffic: percentTrafficPeriod: viewportPreset:].freeze

Instance Attribute Summary

Attributes inherited from ExistingGithubFile

#github_path, #name, #raw_content, #sha, #updated_content

Instance Method Summary collapse

Constructor Details

#initializeCypressConfigJsFile

Returns a new instance of CypressConfigJsFile.



21
22
23
# File 'app/sidekiq/cypress_viewport_updater/cypress_config_js_file.rb', line 21

def initialize
  super(github_path: 'config/cypress.config.js', name: 'cypress.config.js')
end

Instance Method Details

#update(viewports:) ⇒ Object

rubocop:disable Metrics/MethodLength



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
53
54
55
56
57
58
59
60
61
62
63
# File 'app/sidekiq/cypress_viewport_updater/cypress_config_js_file.rb', line 26

def update(viewports:)
  viewport_type = nil
  viewport_idx = nil
  skip_next_line = false
  lines = raw_content.split("\n")

  self.updated_content = "#{lines.each_with_object([]).with_index do |(line, new_lines), idx|
    if skip_next_line
      skip_next_line = false
      next
    end

    if (type = VIEWPORT_TYPES.keys.select { |t| line.include?(t.to_s) }.first)
      viewport_type = VIEWPORT_TYPES[type]
      viewport_idx = 0
    end

    new_line = if line.include?('viewportWidth:')
                 rewrite_line(line:, new_value: viewports.desktop[0].width, prop: 'viewportWidth')
               elsif line.include?('viewportHeight:')
                 rewrite_line(line:, new_value: viewports.desktop[0].height, prop: 'viewportHeight')
               elsif (prop = VIEWPORT_PROPS.select { |p| line.include?(p.to_s) }.first)
                 viewport_idx += 1 if prop == 'height:'
                 if prop == 'devicesWithViewport:' && lines[idx + 1].exclude?('percentTraffic:')
                   skip_next_line = true
                 end
                 rewrite_line(line:,
                              new_value: viewports
                                           .send(viewport_type)[prop == 'height:' ? viewport_idx - 1 : viewport_idx]
                                           .send(prop.chomp(':')),
                              prop:)
               end

    new_lines.push(new_line.nil? ? line : new_line)
  end.flatten.join("\n")}\n"

  self
end