Jakub Kopyś
Jakub Kopyś

Reputation: 710

Ruby Rails attr_encrypted format encrypted attribute

I am using attr_encrypted and I want to get formatted attribute whenever I access encrypted attribute - is there any way of doing this?

The model:

class User < ApplicationRecord
  attr_encrypted :balance, key: 'some super secret key', marshal: true
end

And I want to be able to access balance and get Money object: Money.new(balance, currency)

Is there possibility to make user.balance return this stright away (without additional methods like user.balance_to_money?

I have tried to somehow "extend" attr_encrypted behaviour (defined attribute getters) but I am not sure how to achieve this.

I have tried using custom Marshal object, but It won't work since I have to access user's currency from the database (Marshaler won't have access to this)

  attr_encrypted :balance, key: 'some super secret key', marshal: true, marshaler: BalanceMarshaler
  module BalanceMarshaler
    extend self

    def dump(data) 
      data.to_s
    end

    def load(data)
      number = Marshal.load(data)
      Money.new(number, currency)
    end
  end

Upvotes: 1

Views: 524

Answers (1)

Joe
Joe

Reputation: 42666

If you need to maintain an accessor that treats balance as a Money constructor, you could sidestep the issue of overriding the behavior and just use a different column.

e.g. balance_new or whatever, and then create an accessor for .balance that creates a Money object from balance_new...

Upvotes: 1

Related Questions