Module: NeetoCommonsBackend::Initializers

Defined in:
lib/neeto_commons_backend/initializers/cors.rb,
lib/neeto_commons_backend/initializers/assets.rb,
lib/neeto_commons_backend/initializers/bullet.rb,
lib/neeto_commons_backend/initializers/sidekiq.rb,
lib/neeto_commons_backend/initializers/datetime.rb,
lib/neeto_commons_backend/initializers/mime_types.rb,
lib/neeto_commons_backend/initializers/cache_store.rb,
lib/neeto_commons_backend/initializers/email_setup.rb,
lib/neeto_commons_backend/initializers/honeybadger.rb,
lib/neeto_commons_backend/initializers/rack_attack.rb,
lib/neeto_commons_backend/initializers/rack_timeout.rb,
lib/neeto_commons_backend/initializers/mini_profiler.rb,
lib/neeto_commons_backend/initializers/rack_deflater.rb,
lib/neeto_commons_backend/initializers/session_store.rb,
lib/neeto_commons_backend/initializers/kaminari_config.rb,
lib/neeto_commons_backend/initializers/wrap_parameters.rb,
lib/neeto_commons_backend/initializers/database_cleaner.rb,
lib/neeto_commons_backend/initializers/post_compilation.rb,
lib/neeto_commons_backend/initializers/strong_migrations.rb,
lib/neeto_commons_backend/initializers/cookies_serializer.rb,
lib/neeto_commons_backend/initializers/redis_client_patch.rb,
lib/neeto_commons_backend/initializers/rails_email_preview.rb,
lib/neeto_commons_backend/initializers/neeto_email_prefixer.rb,
lib/neeto_commons_backend/initializers/_enable_extension_hack.rb,
lib/neeto_commons_backend/initializers/neeto_mail_interceptor.rb,
lib/neeto_commons_backend/initializers/filter_parameter_logging.rb,
lib/neeto_commons_backend/initializers/remove_backtrace_silencers.rb

Defined Under Namespace

Modules: EnableExtensionHerokuMonkeypatch, PostCompilation

Class Method Summary collapse

Class Method Details

.assetsObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/assets.rb', line 6

def assets
  Rails.application.config.assets.version = "1.0"
end

.bulletObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/neeto_commons_backend/initializers/bullet.rb', line 6

def bullet
  if Rails.env.development? || Rails.env.test?
    Bullet.enable = true
    Bullet.bullet_logger = true
    Bullet.rails_logger = true
    Bullet.raise = true if Rails.env.test?

    # Detect N+1 queries
    Bullet.n_plus_one_query_enable = true

    # Detect eager-loaded associations which are not used
    Bullet.unused_eager_loading_enable = false

    # Detect unnecessary COUNT queries which could be avoided
    # with a counter_cache
    Bullet.counter_cache_enable = true
  end
end

.cache_store(config) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/neeto_commons_backend/initializers/cache_store.rb', line 6

def cache_store(config)
  if Rails.application.secrets.redis_cache_url.present?
    config.cache_store = :redis_cache_store, {
      url: ENV[Rails.application.secrets.redis_cache_url],
      connect_timeout: 30, # Defaults to 20 seconds
      read_timeout: 0.4, # Defaults to 1 second
      write_timeout: 0.4, # Defaults to 1 second
      reconnect_attempts: 1, # Defaults to 0
      ssl_params: {
        verify_mode: OpenSSL::SSL::VERIFY_NONE
      },

      error_handler: lambda { |method:, returning:, exception:|
        # Report errors to Honeybadger
        Honeybadger.notify(exception, context: { method:, returning: })
      }
    }
  end
end

.cookies_serializerObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/cookies_serializer.rb', line 6

def cookies_serializer
  Rails.application.config.action_dispatch.cookies_serializer = :json
end

.corsObject



6
7
8
9
10
11
12
13
# File 'lib/neeto_commons_backend/initializers/cors.rb', line 6

def cors
  Rails.application.config.middleware.insert_before 0, Rack::Cors do
    allow do
      origins "*"
      resource "*", headers: :any, methods: %i[get post put patch delete options head]
    end
  end
end

.database_cleanerObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/database_cleaner.rb', line 6

def database_cleaner
  DatabaseCleaner.allow_remote_database_url = true unless Rails.env.production?
end

.datetimeObject



6
7
8
9
10
11
# File 'lib/neeto_commons_backend/initializers/datetime.rb', line 6

def datetime
  # Ruby uses local time in .to_time conversions.
  # Force local time to be UTC always in any environment.
  # Ref: https://bugs.ruby-lang.org/issues/14850
  ENV["TZ"] = "UTC"
end

.email_setupObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/neeto_commons_backend/initializers/email_setup.rb', line 6

def email_setup
  Premailer::Rails.config.merge!(preserve_styles: true, remove_ids: true)

  ActionMailer::Base.default_url_options[:host] = Rails.application.secrets.host

  ActionMailer::Base.delivery_method = Rails.application.config.action_mailer.delivery_method

  ActionMailer::Base.asset_host = Rails.application.secrets.host

  if ActionMailer::Base.delivery_method == :smtp
    ActionMailer::Base.smtp_settings = Rails.application.secrets.mailer[:smtp_settings].symbolize_keys
  end

  if Rails.env.production? && ENV["APP_URL"].blank?
    raise "URLs in email use APP_URL. This is not set. Please fix it by adding APP_URL env in the format app.neetoappname.com"
  end
end

.filter_parameter_loggingObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/filter_parameter_logging.rb', line 6

def filter_parameter_logging
  Rails.application.config.filter_parameters += [:password]
end

.honeybadgerObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/neeto_commons_backend/initializers/honeybadger.rb', line 6

def honeybadger
  Honeybadger.configure do |config|
    # Disable logging
    config.logging.path = "/dev/null"
    config.logging.level = "WARN"
    config.exceptions.notify_at_exit = false
    config.before_notify do |notice|
      break if notice.component != "errors"

      params = Rails.application.routes.recognize_path(notice.url)
      notice.component = params[:controller]
      notice.action = params[:action]
    end
  end
end

.kaminari_configObject



6
7
8
9
10
# File 'lib/neeto_commons_backend/initializers/kaminari_config.rb', line 6

def kaminari_config
  Kaminari.configure do |config|
    config.default_per_page = 25
  end
end

.mime_typesObject



6
7
8
9
# File 'lib/neeto_commons_backend/initializers/mime_types.rb', line 6

def mime_types
  Mime::Type.register "application/pdf", :pdf
  Mime::Type.register "application/xlsx", :xlsx
end

.mini_profilerObject



6
7
8
9
10
11
# File 'lib/neeto_commons_backend/initializers/mini_profiler.rb', line 6

def mini_profiler
  if Rails.env.development?
    Rack::MiniProfiler.config.pre_authorize_cb = ->(_env) { ENV["MINI_PROFILER"].present? }
    Rack::MiniProfiler.config.auto_inject = ENV["MINI_PROFILER"].present?
  end
end

.neeto_email_prefixerObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/neeto_commons_backend/initializers/neeto_email_prefixer.rb', line 8

def neeto_email_prefixer
  NeetoEmailPrefixer.configure do |config|
    config.application_name = ((Rails.application.secrets.mailer || {})[:default_from_name]) || ""
    config.stage_name = Rails.env
  end

  ActiveSupport.on_load(:action_mailer) do
    ActionMailer::Base.class_eval do
      default custom_prefix_override: -> { organization_name }

      private
      def organization_name
        if params.nil? || params[:organization_name].nil?
          raise ArgumentError, <<~MSG
            Missing organization_name parameter in mailer. Please add it to the mailer params.

            Suppose the name of the mailer is UserMailer, and you are trying to send a mail via
            UserMailer, you need to add the following parameter like so:

            UserMailer.with(organization_name: organization_name).send_email.deliver

            Please pass the appropriate organization name to the mailer.
          MSG
        else
          params[:organization_name]
        end
      end
    end
  end
end

.neeto_mail_interceptorObject



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/neeto_commons_backend/initializers/neeto_mail_interceptor.rb', line 8

def neeto_mail_interceptor
  intercept_secrets = Rails.application.secrets.mail_interceptor

  if Rails.env.staging?
    cleanup = proc { |n| n.split(",").map(&:strip) }

    interceptor = NeetoMailInterceptor::Interceptor.new(
      forward_emails_to: cleanup.call(intercept_secrets[:forward_emails_to] || ""),
      deliver_emails_to: cleanup.call(intercept_secrets[:whitelisted_emails] || "")
    )
    ActionMailer::Base.register_interceptor(interceptor)
  elsif Rails.env.production?
    interceptor = NeetoMailInterceptor::Interceptor.new(
      env: OpenStruct.new(name: Rails.env, intercept?: true),
      only_intercept: ["@example.com", "@example.net", "@neetoauth.com", "nitrohelp.com"]
    )
    ActionMailer::Base.register_interceptor(interceptor)
  end

  if Rails.application.secrets.zerobounce_api_key.present?
    NeetoMailInterceptor.configure do |config|
      config.enable_zerobounce_validation = true
    end
  end
end

.rack_attackObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/neeto_commons_backend/initializers/rack_attack.rb', line 20

def rack_attack
  # IP Blacklist - comma separated
  blocked_ips = ENV["RACK_ATTACK_BLOCKED_IPS"].to_s.split(",")
  blocked_ips.each do |ip|
    Rack::Attack.blocklist_ip(ip)
  end

  if ENV["ENABLE_RACK_ATTACK"] == "true"
    (3..5).each do |level|
      Rack::Attack.throttle(
        "req/ip/#{level}",
        limit: (30 * (2**level)),
        period: (0.9 * (8**level)).to_i.seconds, &:remote_ip)
    end
  end
end

.rack_deflaterObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/rack_deflater.rb', line 6

def rack_deflater
  Rails.application.config.middleware.insert_after ActionDispatch::Static, Rack::Deflater
end

.rack_timeoutObject



6
7
8
9
10
11
12
# File 'lib/neeto_commons_backend/initializers/rack_timeout.rb', line 6

def rack_timeout
  # service_timeout = 0 or false disables rack-timeout
  # service_timeout = 30 is the maximum timeout supported by Heroku
  service_timeout = ["development", "test"].include?(Rails.env.to_s) ? 0 : 30

  Rails.application.config.middleware.use Rack::Timeout, service_timeout:
end

.rails_email_previewObject



8
9
10
11
12
13
14
15
16
17
18
# File 'lib/neeto_commons_backend/initializers/rails_email_preview.rb', line 8

def rails_email_preview
  RailsEmailPreview.setup do |config|
    config.before_render do |message, _preview_class_name, _mailer_action|
      Premailer::Rails::Hook.delivering_email(message)
    end
  end

  Rails.application.config.to_prepare do
    RailsEmailPreview.preview_classes = RailsEmailPreview.find_preview_classes("app/mailer_previews")
  end
end

.redis_client_patchObject



7
8
9
10
11
12
13
14
15
16
# File 'lib/neeto_commons_backend/initializers/redis_client_patch.rb', line 7

def self.redis_client_patch
  ::Redis.class_eval do
    alias_method :old_initialize, :initialize

    def initialize(my_options = {})
      options = my_options.merge({ ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE } })
      old_initialize(options)
    end
  end
end

.remove_backtrace_silencersObject



6
7
8
# File 'lib/neeto_commons_backend/initializers/remove_backtrace_silencers.rb', line 6

def remove_backtrace_silencers
  Rails.backtrace_cleaner.remove_silencers!
end

.session_store(expire_after = 1.days.to_i) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/neeto_commons_backend/initializers/session_store.rb', line 6

def session_store(expire_after = 1.days.to_i)
  Rails.application.config.session_store(
    :active_record_store,
    key: Rails.application.secrets.session_cookie_name, expire_after:)

  ActiveRecord::SessionStore::Session.table_name = "server_side_sessions"
  ActiveRecord::SessionStore::Session.primary_key = "session_id"
  ActiveRecord::SessionStore::Session.serializer = :json

  Rails.application.config.after_initialize do
    ActionDispatch::Session::ActiveRecordStore.session_class = ServerSideSession
  end
end

.sidekiqObject



9
10
11
12
13
14
15
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
# File 'lib/neeto_commons_backend/initializers/sidekiq.rb', line 9

def sidekiq
  if Rails.env.test? || Rails.env.heroku?
    require "sidekiq/testing"
    Sidekiq::Testing.inline!
  end

  Sidekiq.logger.level = Logger::WARN if Rails.env.test?

  Sidekiq.configure_server do |config|
    # Reference:
    # 1. https://github.com/mperham/sidekiq/wiki/Using-Redis#complete-control
    # 2. https://elements.heroku.com/addons/heroku-redis Max connection 20
    config.redis = {
      url: Rails.application.secrets.redis_url,
      size: 18,
      reconnect_attempts: 2,
      network_timeout: 10
    }

    unless Rails.env.test? || Rails.env.production? || Rails.env.staging?
      schedule_file = "config/scheduled_jobs.yml"
      if File.exist?(schedule_file)
        Sidekiq::Cron::Job.load_from_hash! YAML.load_file(schedule_file, aliases: true)[Rails.env] ||
          YAML.load_file(schedule_file, aliases: true)
      end
    end
  end

  Sidekiq.configure_client do |config|
    config.redis = {
      url: Rails.application.secrets.redis_url,
      size: 2,
      reconnect_attempts: 2,
      network_timeout: 10
    }
  end
end

.strong_migrationsObject



6
7
8
9
10
# File 'lib/neeto_commons_backend/initializers/strong_migrations.rb', line 6

def strong_migrations
  StrongMigrations.lock_timeout = 10.seconds
  StrongMigrations.statement_timeout = 1.hour
  StrongMigrations.auto_analyze = true
end

.wrap_parametersObject



6
7
8
9
10
# File 'lib/neeto_commons_backend/initializers/wrap_parameters.rb', line 6

def wrap_parameters
  ActiveSupport.on_load(:action_controller) do
    wrap_parameters format: [:json]
  end
end