#StackBounty: #ruby SocketError: sockaddr resolved to multiple nodename

Bounty: 50

ruby build is failing with error make spec failing, Any input on this will be useful

I am using

Build language: c
Build dist: bionic
Build id: 764199404
Job id: 764199405
Runtime kernel version: 5.4.0-1032-gcp
travis-build version: 091d532a
Build image provisioning date and time
Mon Dec 28 15:53:02 UTC 2020
Operating System Details
Distributor ID: Ubuntu
Description: Ubuntu 18.04.5 LTS
Release: 18.04
Codename: bionic

Part source where issue is observed

platform_is_not :windows do
        describe 'using NI_NUMERICHOST as the flag' do
          it 'returns an Array containing the numeric hostname and service name' do
            Socket.getnameinfo(@addr, Socket::NI_NUMERICHOST).should == [ip_address, 'ftp']
          end
        end
      end
Socket.getnameinfo using IPv4 using a 3 element Array as the first argument using NI_NUMERICHOST as the flag returns an Array containing the numeric hostname and service name ERROR
SocketError: sockaddr resolved to multiple nodename
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:111:in `getnameinfo'
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:111:in `block (6 levels) in <top (required)>'
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:65:in `<top (required)>'


Get this bounty!!!

#StackBounty: #ruby make -s test-spec MSPECOPT=-ff failure

Bounty: 50

ruby build is failing with error make spec failing, Any input on this will be useful

I am using

Build language: c
Build dist: bionic
Build id: 764199404
Job id: 764199405
Runtime kernel version: 5.4.0-1032-gcp
travis-build version: 091d532a
Build image provisioning date and time
Mon Dec 28 15:53:02 UTC 2020
Operating System Details
Distributor ID: Ubuntu
Description: Ubuntu 18.04.5 LTS
Release: 18.04
Codename: bionic
Socket.getnameinfo using IPv4 using a 3 element Array as the first argument using NI_NUMERICHOST as the flag returns an Array containing the numeric hostname and service name ERROR
SocketError: sockaddr resolved to multiple nodename
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:111:in `getnameinfo'
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:111:in `block (6 levels) in <top (required)>'
/home/travis/build/alpha/ruby/spec/ruby/library/socket/socket/getnameinfo_spec.rb:65:in `<top (required)>'


Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #ruby-on-rails-6 #paper-trail-gem #ruby-2.6 Papertrail: records with nil whodunnit values and object…

Bounty: 50

I’ve set papertrail to only record changes containing a whodunnit value/when an admin makes a change by using the below condition in my model:

has_paper_trail if: proc { |model| PaperTrail.request.whodunnit.present? }

However I’ve noticed there are still a decent amount of records being stored with empty whodunnit values. From having a look at the records, these seem to be mostly ‘update’ actions all having empty object changes for some reason. I am unsure as to why the value is empty, or how it would get saved at all considering the above condition.

I am getting whodunnit values from warden in my application controller using:

def user_for_paper_trail
  request.env['warden']&.user(:admin)&.id
end

Has anyone come across similar behaviour before?


Get this bounty!!!

#StackBounty: #ruby #garbage-collection #temporary-files Ruby TempFile behaviour among different classes

Bounty: 50

Our processing server works mainly with TempFiles as it makes things easier on our side: no need to take care of deleting them as they get garbage collected or handle name collisions, etc.

Lately, we are having problems with TempFiles getting GCed too early in the process. Specially with one of our services that will convert a Foo file from a url to some Bar file and upload it to our servers.

For sake of clarity I added bellow a case scenario in order to make discussion easier and have an example at hand.

This workflow does the following:

  1. Get a url as parameter
  2. Download the Foo file as a TempFile
  3. Duplicate it to a new TempFile
  4. Download the related assets to TempFiles
  5. Link the related assets into the local dup TempFile
  6. Convert the Foo to Bar format
  7. Upload it to our server

At times the conversion fail and everything points to the fact that our local Foo file is pointing to related assets that have been created and GCed before the conversion.

My two questions:

  1. Is it possible that my TempFiles get GCed too early? I read about Ruby GCed system it was very conservative to avoid those scenarios.
  2. How can I avoid this from happening? I could try to save all related assets from download_and_replace_uri(node) and passing them as a return to keep it alive while the instance of ConvertFooService is still existing. But I’m not sure if this would solve it.

ConvertFooService

class ConvertFooService < ApplicationService
  def initialize(url)
    @url = url
  end

  def call
    import_foo
    generate_bar
    upload_bar
    @bar_url
  end

  private

  def import_foo
    @foo_file = Helper::ImportFooService.call(url) # <- TempFile
  end

  def generate_glb_from_pipeline
    `create-bar "#{foo_file.path}" "#{bar_file.path}"`
  end

  def upload_bar
    @bar_url = Helper::UploadBarService.call(bar_file)
  end

  def bar_file
    @bar_file ||= Tempfile.new(['new-file-', '.bar']) # <- TempFile
  end
end

ImportFooService

module Helper
  class ImportFooService < ApplicationHelperService
    def initialize(url)
      @url = url
    end

    def call
      download_if_needed
      duplicate_remote_file
      download_and_replace_embedded_assets
      edited_file
    end

    private

    def download_if_needed
      @original =
        if http?(@url) 
          DownloadRemoteFileService.call(@url) # <- TempFile
        else
          File.open(@url)
        end
    end

    def duplicate_remote_file
      FileUtils.cp(@original.path, edited_file.path)
    end

    def download_and_replace_uri_embedded_assets
      file = File.read(edited_file.path)
      json = JSON.parse(file, symbolize_names: true)
      json[:buffers]&.each { |node| download_and_replace_uri(node) }
      json[:images]&.each { |node| download_and_replace_uri(node) }
      write_to_disk(edited_file.path, json.to_json)
    end

    def download_and_replace_uri(node)
      return unless http?(node[:uri])

      node[:uri] = DownloadRemoteFileService.call(node[:uri]).path # <- TempFile
    end

    def edited_file
      @edited_file ||= Tempfile.new(['edited-', '.foo'])
    end

    def http?(url)
      url.starts_with?('http://') || url.starts_with?('https://')
    end
  end
end

DownloadRemoteFileService

module Helper
  class DownloadRemoteFileService < ApplicationHelperService
    def initialize(url)
      @url = url
    end

    def call
      create_file
      download_file
      @file # <- Tempfile
    end

    private

    def create_file
      @file = Tempfile.new(['new-file-', File.extname(uri.path)])
    end

    def download_file
      use_ssl = uri.scheme == 'https'
      Net::HTTP.start(uri.host, uri.port, use_ssl: use_ssl) do |http|
        url_path = Net::HTTP::Get.new(uri.path)
        response = http.request(url_path)
        write_file(response)
      end
    end

    def write_file(response)
      @file.binmode
      @file.write(response.body)
      @file.flush
    end

    def uri
      @uri ||= URI.parse(url)
    end
  end
end

UploadBarService

module Helper
  class UploadBarService < ApplicationHelperService
    def initialize(file)
      @file = file
      @s3_presigned_url_payload = s3_presigned_url_payload
    end

    def call
      upload # NOTE: Returns the url for the uploaded file
    end

    private

    def upload
      HTTParty.post(ENV['upload_url'], body: { file: @file })
    end
  end
end


Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #google-sheets #google-drive-api Iterating Through Rows when importing Gsheet Worksheets Via Ruby Ge…

Bounty: 100

I’m using the "google_drive" gem to access a Google Sheet worksheet and I’ve been able to access and print the worksheet, so the API connection is fine.

However, I’m trying to build a method that iterates through every row and find or creates a user based on that. I’ve tried these two options:


def import
      session = GoogleDrive::Session.from_service_account_key("credspath")
      spreadsheet  = session.spreadsheet_by_title("My Worksheet Title")
      worksheet  = spreadsheet.worksheets.first
      worksheet.rows.each do |row|
        customer = Customer.find_by(email: row['email'])
        if customer.blank?
           customer = Customer.new(email: row['email'] )
           puts "New Customer #{customer.email} "
        end
      end
    end

and this


def import
      session = GoogleDrive::Session.from_service_account_key("credspath")
      spreadsheet  = session.spreadsheet_by_title("My Worksheet Title")
      worksheet  = spreadsheet.worksheets.first
      CSV.foreach(worksheet, headers: true, encoding:"iso-8859-1:utf-8") do |row|
        customer = Customer.find_by(email: row['email'])
        if customer.blank?
           customer = Customer.new(email: row['email'] )
           puts "New Customer #{customer.email} "
        end
      end
    end

I’m getting the error: "no implicit conversion of String into Integer" for the line that the iteration starts on…

How can I create from this API connection WITHOUT exporting to CSV?


Get this bounty!!!

#StackBounty: #ruby Ruby simple interactive interpreter

Bounty: 200

This is my first Ruby code and a solution to this problem https://www.codewars.com/kata/53005a7b26d12be55c000243/train/ruby The task is to make a simple interpreter that will take expressions and calculate the results. I’m just looking for general feedback on following Ruby standard practices and ways I could shorten the code by omitting parentheses for example


  def input expr
    if expr.strip == ""
      return ""
    end
    # puts expr
    tokens = tokenize(expr).map{ |a| a[0] }    
    parsedTokens = parseTokens tokens
    if parsedTokens.length == 1
      if !@variables.key? parsedTokens[0].name
        raise 'unitialized variable'
      end
      return @variables[parsedTokens[0].name]
    end
    # todo can the user enter just a number?
    leastPrecedentNode = partition parsedTokens
    rootOfBuiltTree = buildTree leastPrecedentNode
    result = calculateRecursive rootOfBuiltTree
    result
  end

  private

  class OperatorInfo
      @@operators = { '=' => 0, '+' => 1, '-' => 1, '*' => 2, '/' => 2, '%' => 2 }
      @@assignmentOperator = '='

      def self.operators
        @@operators
      end

      def self.assignmentOperator
        @@assignmentOperator
      end
  end

  class ParseUnit
    attr_reader :overallIndex
    attr_reader :nestLevel
    attr_reader :indexInLevel

    def initialize(overallIndex, nestLevelArg, indexInLevelArg)
      @overallIndex = overallIndex
      @nestLevel = nestLevelArg
      @indexInLevel = indexInLevelArg
    end
  end

  class ConstantParse < ParseUnit
    attr_reader :value

    def initialize(value, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @value = value
    end
  end

  class OperatorParse < ParseUnit
    attr_reader :operator
    attr_reader :priority

    def initialize(operator, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @operator = operator
      @priority = OperatorInfo.operators[operator]
    end
  end

  class VariableParse < ParseUnit
    attr_reader :name

    def initialize(name, overallIndex, nestLevel, indexInLevel)
      super(overallIndex, nestLevel, indexInLevel)
      @name = name
    end
  end

  def parseTokens (tokens)
    ret = []
    nestLevel = 0
    indexes = [0]
    overallIndex = 0
    tokens.each do | t | 
      # can be operator, constant number, paren, variable 
      # puts "curToken is #{t}"

      case t       
      #operator
      when OperatorInfo.operators.keys.include?(t).to_s == 'true' ? t : ''
        ret.push OperatorParse.new t, overallIndex, nestLevel, indexes[nestLevel]
          overallIndex += 1
          indexes[nestLevel] += 1 
      # is a constant number
      when /Ad+z/        
        ret.push ConstantParse.new t.to_i, overallIndex, nestLevel, indexes[nestLevel]
        overallIndex += 1
        indexes[nestLevel] += 1
      when '('
        nestLevel += 1
        if indexes.length <= nestLevel
          indexes.push(0)
        end
      when ')'
        nestLevel -= 1
      #variable
      when String
        ret.push VariableParse.new t, overallIndex, nestLevel, indexes[nestLevel]
        overallIndex += 1
        indexes[nestLevel] += 1
      else
        puts "error in parse tokens with token #{t}"
      end
    end
    ret
  end

  class OperatorNode
    attr_reader :operator
    attr_reader :left
    attr_reader :right

    def initialize(operator, left, right)
      @left = left
      @right = right
      @operator = operator
      @priority = OperatorInfo.operators[operator] 
    end
  end

  def partition(parsedTokens)
    opTokens = parsedTokens.select { |token| token.is_a?(OperatorParse) }
    op = leastPrecedentOp opTokens
    left = parsedTokens.select { |x| x.overallIndex < op.overallIndex }
    right = parsedTokens.select { |x| x.overallIndex > op.overallIndex }
    OperatorNode.new op, left, right
  end

  def leastPrecedentOp opTokens
    if opTokens.length == 1 
      return opTokens[0]
    end
    # todo dry out this sort with the next one
    sortedByNestLevel = opTokens.sort_by { |x| x.nestLevel }
    nestLevelTies = sortedByNestLevel.select { |x| x.nestLevel == sortedByNestLevel[0].nestLevel }
    if nestLevelTies.length == 1
      return nestLevelTies[0]
    end
    sortedByPriority = nestLevelTies.sort_by { |x| x.priority }
    priorityTies = sortedByPriority.select { |x| x.priority == sortedByPriority[0].priority }
    if priorityTies.length == 1
      return priorityTies[0]
    end
    sortedByIndexInLevel = priorityTies.sort_by { |x| x.indexInLevel * -1 }
    sortedByIndexInLevel[0]
  end

  def buildTree(opNode)
    # puts opNode
    # base case
    leftIsSingle = opNode.left.length == 1
    rightIsSingle = opNode.right.length == 1
    if leftIsSingle && rightIsSingle
      return OperatorNode.new opNode.operator.operator, opNode.left, opNode.right   
    end
    # recursive call
    leftRet = nil
    if leftIsSingle
      leftRet = opNode.left[0]
    else
      leftPart = partition opNode.left
      leftRet = buildTree leftPart
    end

    rightRet = nil
    if rightIsSingle
      rightRet = opNode.right[0]
    else
      rightPart = partition opNode.right
      rightRet = buildTree rightPart
    end

    # combine and return
    OperatorNode.new opNode.operator.operator, leftRet, rightRet
  end

  def calculateRecursive node
    # base case
    if isLeaf? node, nil
      return getValue node
    end    
    leftIsLeaf = isLeaf? node, node.left
    rightIsLeaf = isLeaf? node, node.right
    if leftIsLeaf && rightIsLeaf
      if node.operator == OperatorInfo.assignmentOperator
        return calculateImpl node.operator, node.left[0].name, (getValue node.right)
      end
      leftVal = getValue node.left
      rightVal = getValue node.right
      return calculateImpl node.operator, leftVal, rightVal
    end
    # recursive call
    leftResult = nil
    if leftIsLeaf && node.operator != OperatorInfo.assignmentOperator
      leftResult = getValue node.left
    elsif leftIsLeaf && node.operator
      leftResult = node.left.name
    else
      leftResult = calculateRecursive node.left
    end
    rightResult = nil
    if rightIsLeaf
      rightResult = getValue node.right
    else
      rightResult = calculateRecursive node.right
    end
    # combine and return
    result = calculateImpl node.operator, leftResult, rightResult
    result
  end

  def isLeaf?(parent, node)
    # if parent
    isConstant = node.is_a? ConstantParse 
    if node.is_a? Array 
      isConstant = node[0].is_a? ConstantParse
    end
    isVariable = node.is_a? VariableParse
    if node.is_a? Array 
      isVariable = node[0].is_a? VariableParse
    end
    return isConstant || isVariable
  end

  def getValue node
    nodeVal = nil
    if node.is_a? Array
      nodeVal = node[0]
    else
      nodeVal = node
    end
    if nodeVal.is_a? ConstantParse
      return nodeVal.value
    end
    if nodeVal.is_a? VariableParse
      if @variables.key? nodeVal.name
        return @variables[nodeVal.name]
      end
      return nodeVal.name
    end
  end

  def calculateImpl(operator, left, right)
    #puts "#{left} #{operator} #{right}"
    case operator
    when '+'
      return left + right
    when '-'
      return left - right
    when '/'
      return left.to_f / right
    when '*'
      return left * right
    when '%'
      return left % right
    when '='
      @variables[left] = right
      return right
    end
  end

  def initialize
    @variables = {}
  end  

  def tokenize program
    return [] if program == ''
    regex = /s*([-+*/%=()]|[A-Za-z_][A-Za-z0-9_]*|[0-9]*.?[0-9]+)s*/
    program.scan(regex).select { |s| !(s =~ /^s*$/) }
  end
end


Get this bounty!!!

#StackBounty: #ruby-on-rails #regex #ruby #validation #bcrypt BCrypt-3.1.11 hashed passwords suddenly have endless stream of xoo chara…

Bounty: 50

I recently started getting BCrypt “invalid hash” errors when I tried to save a record with a password, so I looked into the BCrypt code, and found the following method for validating passwords:

  def valid_hash?(h)
    h =~ /^$[0-9a-z]{2}$[0-9]{2}$[A-Za-z0-9./]{53}$/
  end

which is called by the initialize method:

def initialize(raw_hash)
  if valid_hash?(raw_hash)
    self.replace(raw_hash)
    @version, @cost, @salt, @checksum = split_hash(self)
  else
    raise Errors::InvalidHash.new("invalid hash")
  end
end

The following passwords:

"PassiveForbearenceFox"
"VindictivePurpleAlligator12345"
"LostBlueLizard!@#$1234" 

all return Invalid Hash errors.

UPDATE:

I dug deeper, and found that the regex is checking the hashed password, but the hash that is getting passed for some reason has an endless stream of /x00s after it. For example, if I type in the password “LostBlueLizard!@#1234”, the hash that is passed to challenge the regex is

"$2a$11$NcmldbbyCDfumGYALgYhfuIQt2FZ8gpbVCQfuiVlwjhCtkD2ndDFyx00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00x00..... and so on, for farther than I could scroll.

If I remove the x00s and just pass in $2a$11$NcmldbbyCDfumGYALgYhfuIQt2FZ8gpbVCQfuiVlwjhCtkD2ndDFy, it passes the regex.

Does anyone have any idea why the hash has those characters? I can’t prove they weren’t there before, but my passwords always were accepted until recently.

UPDATE 2:

Also, it’s actually the raw_hash that’s getting input into the initialize method that’s the hash with all the x00s. So somewhere there’s code that generates the faulty hash and passes it to initialize, but I searched the entire gem’s codebase for the term “initialize” and there were no results like that, so I can’t find where the hash is actually generated.

UPDATE 3:

Okay I tracked the issue further, to the BCrypt::Engine.create method, which calls the __bc_crypt method, which is what returns the faulty hash. But __bc_crypt is actually from a file called “ext/mri/bcrypt_ext.c” and is written in C, which I think is beyond my ability to investigate.

I simply updated BCrypt from 3.1.11 to 3.1.13, and now it works fine. I’m not sure whether it was a bug or not, but the point is it works now.


Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #rmagick Display a converted PDF to a rails page

Bounty: 50

So I was checking on how to display PDF thumbnails in Rails since for some reason creating a thumbnail version of my file in my uploader doesn’t work, and it lead me to this:
Convert a .doc or .pdf to an image and display a thumbnail in Ruby?

So I got up to this:

def show_thumbnail
    require 'rmagick'
    pdf = Magick::ImageList.new(self.pdf_file.file.path)
    first_page = pdf.first
    scaled_page = first_page.scale(300, 450)
end 

But how do I display scaled_page to a webpage?

I added this function in the decorator so I can do something like this:

= image_tag(pdf.pdf_file.show_thumbnail)

But it results in this error:

Can't resolve image into URL: undefined method `to_model' for #<Magick::Image:0x0000000122c4b300>


Get this bounty!!!

#StackBounty: #ruby-on-rails #ruby #rspec #minitest Error when migrating for MiniTest to RSpec

Bounty: 100

I’m trying to migrate my rails application to RSpec. But I’m getting the error uninitialized constant ActiveRecord::Relation when running the specs. It says it’s on line 10 of application.rb which is Bundler.require(:default, Rails.env) if defined?(Bundler)

error message

An error occurred while loading ./spec/requests/teams_spec.rb.
Failure/Error: require File.expand_path('../config/environment', __dir__)

NameError:
  uninitialized constant ActiveRecord::Relation
# ./config/application.rb:10:in `<top (required)>'
# ./config/environment.rb:2:in `require'
# ./config/environment.rb:2:in `<top (required)>'
# ./spec/rails_helper.rb:5:in `require'
# ./spec/rails_helper.rb:5:in `<top (required)>'
# ./spec/swagger_helper.rb:2:in `require'
# ./spec/swagger_helper.rb:2:in `<top (required)>'
# ./spec/requests/teams_spec.rb:1:in `require'
# ./spec/requests/teams_spec.rb:1:in `<top (required)>'
# ------------------
# --- Caused by: ---
# NameError:
#   uninitialized constant ActiveRecord::Relation
#   ./config/application.rb:10:in `<top (required)>'

Spec

require 'rails_helper'

RSpec.describe Api::V1::CertificateRequestsController, type: :controller do
  describe '#create_v1_4' do
    it 'worked' do
        expect(true).to eq(true)
    end
  end
end

spec_helper.rb

# frozen_string_literal: true

RSpec.configure do |config|
  config.expect_with :rspec do |expectations|
    expectations.include_chain_clauses_in_custom_matcher_descriptions = true
  end

  # rspec-mocks config goes here. You can use an alternate test double
  # library (such as bogus or mocha) by changing the `mock_with` option here.
  config.mock_with :rspec do |mocks|
    # Prevents you from mocking or stubbing a method that does not exist on
    # a real object. This is generally recommended, and will default to
    # `true` in RSpec 4.
    mocks.verify_partial_doubles = true
  end

  # This option will default to `:apply_to_host_groups` in RSpec 4 (and will
  # have no way to turn it off -- the option exists only for backwards
  # compatibility in RSpec 3). It causes shared context metadata to be
  # inherited by the metadata hash of host groups and examples, rather than
  # triggering implicit auto-inclusion in groups with matching metadata.
  config.shared_context_metadata_behavior = :apply_to_host_groups
end

rails_helper.rb

# frozen_string_literal: true

# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'

ENV['RAILS_ENV'] ||= 'test'

require File.expand_path('../config/environment', __dir__)

# Prevent database truncation if the environment is production
if Rails.env.production?
  abort('The Rails environment is running in production mode!')
end
require 'rspec/rails'
require 'database_cleaner'
require 'factory_bot_rails'

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories.
Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }

# Checks for pending migrations and applies them before tests are run.
# If you are not using ActiveRecord, you can remove these lines.
begin
  ActiveRecord::Migration.maintain_test_schema!
rescue ActiveRecord::PendingMigrationError => e
  puts e.to_s.strip
  exit 1
end
RSpec.configure do |config|
  # If you're not using ActiveRecord, or you'd prefer not to run each of your
  # examples within a transaction, remove the following line or assign false
  # instead of true.
  config.use_transactional_fixtures = true

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  config.infer_spec_type_from_file_location!

  # Filter lines from Rails gems in backtraces.
  config.filter_rails_from_backtrace!
  # arbitrary gems may also be filtered via:
  # config.filter_gems_from_backtrace("gem name")

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.around(:each) do |example|
    DatabaseCleaner.cleaning do
      example.run
    end
  end
end

test.rb

SslCom::Application.configure do
  MIGRATING_FROM_LEGACY = false
  # Settings specified here will take precedence over those in config/environment.rb

  # The test environment is used exclusively to run your application's
  # test suite.  You never need to work with it otherwise.  Remember that
  # your test database is "scratch space" for the test suite and is wiped
  # and recreated between test runs.  Don't rely on the data there!
  config.cache_classes = true

  # Log error messages when you accidentally call methods on nil.
  config.whiny_nils = true

  # Show full error reports and disable caching
  config.consider_all_requests_local       = true
  config.action_controller.perform_caching = false

  # Raise exceptions instead of rendering exception templates
  config.action_dispatch.show_exceptions = false

  # Disable request forgery protection in test environment
  config.action_controller.allow_forgery_protection    = false

  # Tell Action Mailer not to deliver emails to the real world.
  # The :test delivery method accumulates sent emails in the
  # ActionMailer::Base.deliveries array.
  config.action_mailer.delivery_method = :test
  config.action_mailer.perform_deliveries = true
  config.action_mailer.default_url_options = {host: 'localhost:3000'}

  config.after_initialize do
    Rails.application.routes.default_url_options = {host: 'localhost:3000'}
  end

  config.force_ssl = false

  # Use SQL instead of Active Record's schema dumper when creating the test database.
  # This is necessary if your schema can't be completely dumped by the schema dumper,
  # like if you have constraints or database-specific column types
  # config.active_record.schema_format = :sql

  # Sort the order test cases are executed.
  config.active_support.test_order = :sorted

  # Print deprecation notices to the stderr
  config.active_support.deprecation = :stderr

  ActiveMerchant::Billing::Base.mode = :test

  config.eager_load=false

  config.serve_static_assets = true
  config.static_cache_control = "public, max-age=3600"

  #config.log_level = Logger::INFO

  GATEWAY_TEST_CODE=1.0
  # END ActiveMerchant configuration
end

#require "#{Rails.root}/lib/firewatir_url.rb"

application.rb

# frozen_string_literal: true

require File.expand_path('boot', __dir__)
require 'oauth/rack/oauth_filter'
require 'rack/ssl-enforcer'
require 'rails/all'
require './lib/middleware/catch_json_parse_errors'

Bundler.setup
# If you have a Gemfile, require the gems listed there, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

CLIENT_OPTIONS = ['aswesome.com', 'aswementer'].freeze
DEPLOYMENT_CLIENT = CLIENT_OPTIONS[0]

Struct.new('Expiring', :before, :after, :cert)
Struct.new('Notification', :before, :after, :domain, :expire, :reminder_type, :scanned_certificate_id)
Struct.new('Reminding', :year, :cert)

module AwesomeApp
  class Application < Rails::Application
    # set environment variables
    config.before_configuration do
      env_file = File.join(Rails.root, 'config', 'local_env.yml')
      YAML.safe_load(File.open(env_file)).each do |key, value|
        ENV[key.to_s] = value
      end
    end

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Custom directories with classes and modules you want to be autoloadable.
    config.autoload_paths += %W[#{config.root}/lib]

    Bundler.require(*Rails.groups)
    # Config::Integration::Rails::Railtie.preload

    # Add additional load paths for your own custom dirs
    %w[observers mailers middleware serializers].each do |dir|
      config.autoload_paths << "#{config.root}/app/#{dir}"
    end

    # Only load the plugins named here, in the order given (default is alphabetical).
    # :all can be used as a placeholder for all plugins not explicitly named.
    # config.plugins = [ :exception_notification, :ssl_requirement, :all ]

    # Activate observers that should always be running.
    # config.active_record.observers = :cacher, :garbage_collector, :forum_observer

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de

    # Configure the default encoding used in templates for Ruby 1.9.
    config.encoding = 'utf-8'

    # Configure sensitive parameters which will be filtered from the log file.
    config.filter_parameters += %i[password password_confirmation]
    # config.action_mailer.default_url_options = { :host => Settings.actionmailer_host }

    # machinist generator
    # config.generators do |g|
    #   g.fixture_replacement :machinist
    # end

    # Rails Api
    config.api_only = false

    # turn off strong parameters
    config.action_controller.permit_all_parameters = true

    config.generators do |g|
      g.test_framework :minitest, spec: true, fixture: false
      g.jbuilder false
    end

    # config.middleware.use OAuth::Rack::OAuthFilter
    config.middleware.insert_before ActionDispatch::ParamsParser, 'CatchJsonParseErrors'

    # Delayed Job
    config.active_job.queue_adapter = :delayed_job

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '/certificate/*',
                 headers: :any,
                 methods: %i[get post delete put options head],
                 max_age: 0
      end
    end

    # Enable the asset pipeline
    config.assets.enabled = true

    config.sass.preferred_syntax = :sass
    config.sass.line_comments = false
    config.sass.cache = false
    config.action_mailer.default_url_options = { host: 'secure.ssl.com', protocol: 'https' }
    if DEPLOYMENT_CLIENT =~ /certassure/i && Rails.root.to_s =~ /Development/
      paths['config/database'] = 'config/client/certassure/database.yml'
    end
  end
end

require "#{Rails.root}/lib/base.rb"
require "#{Rails.root}/lib/asset_tag_helper.rb"
require "#{Rails.root}/lib/array.rb"
require "#{Rails.root}/lib/range.rb"
require "#{Rails.root}/lib/in_words.rb"
require "#{Rails.root}/lib/kernel.rb"
require "#{Rails.root}/lib/money.rb"
# require "#{Rails.root}/lib/subdomain-fu.rb"
require "#{Rails.root}/lib/domain_constraint.rb"
require "#{Rails.root}/lib/preferences.rb"
require "#{Rails.root}/lib/active_record.rb"
require "#{Rails.root}/lib/active_record_base.rb"
require "#{Rails.root}/lib/hash.rb"
require 'will_paginate'

# try to figure this out for heroku and rails 3
# class Fixnum; include InWords; end
# class Bignum; include InWords; end
DB_STRING_MAX_LENGTH = 255
DB_TEXT_MAX_LENGTH = 40_000
HTML_TEXT_FIELD_SIZE = 20
AMOUNT_FIELD_SIZE = 10
ADDRESS_FIELD_SIZE = 30
SERVER_SIDE_CART = false
# SQL_LIKE = Rails.configuration.database_configuration[Rails.env]['adapter'].
#   downcase=='postgresql' ? 'ilike' : 'like'
db_env = Rails.configuration.database_configuration[Rails.env]
db_adapter = db_env['adapter'].downcase if db_env.present?
SQL_LIKE = db_adapter == 'postgresql' ? 'ilike' : 'like'

# uncomment to track down bugs on heroku production
# ApplicationRecord.logger.level = 0 # at any time
ActiveMerchant::Billing::CreditCard.require_verification_value = false
PublicSuffix::List.default =
  PublicSuffix::List.parse(File.read(PublicSuffix::List::DEFAULT_LIST_PATH), private_domains: false)


Get this bounty!!!