Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including Rails classes in a rake task?

I'm pretty new to Rails, so I apologize if my question doesn't make the most sense.

I have a class called PaymentGatewayCipher that looks like:

require 'openssl'

# Encapsulates payment gateway encryption / decryption utility functions
class PaymentGatewayCipher
  class << self
    def encrypt(file, options = {})
      cipher = create_cipher
      cipher.encrypt(cipher_key)
      data = cipher.update(File.read(file))
      data << cipher.final

      if to_file = options[:to]
        # Write it out to a different file
        File.open(to_file, 'wb') do |f|
          f << data
        end
      end

      data
    end

    # Decrypts the given file
    def decrypt(file)
      cipher = create_cipher
      cipher.decrypt(cipher_key)
      encrypted_data = File.open(file, 'rb') {|io| io.read}
      data = cipher.update(encrypted_data)
      data << cipher.final
    end

    # Generates the cipher to be used for encryption/decryption
    def create_cipher
      OpenSSL::Cipher::Cipher.new('aes-256-cbc')
    end

    # Loads the cipher key used for the symmetric algorithm
    def cipher_key
      File.open(File.join(Rails.root, 'config/mystuff/live/cipher.key'), 'rb') {|io| io.read}
    end
  end
end

I want to write a rake task to run it to decrypt a file. I've tried putting a file in tasks/Rakefile that looks like:

directory "tasks"

task :decrypt_test do
  puts "Decypting"
  pay_pal_config = PaymentGatewayCipher.decrypt('hpa1')
end

When I run it, however, it says cannot find Class::Rails

Help?

like image 785
Shamoon Avatar asked Dec 06 '25 04:12

Shamoon


1 Answers

Use lib/tasks folder and dont forget to include rails environment on your tasks:

directory "tasks"

task :decrypt_test => :environment do
  puts "Decypting"
  pay_pal_config = PaymentGatewayCipher.decrypt('hpa1')
end
like image 56
daniloisr Avatar answered Dec 07 '25 18:12

daniloisr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!