virtus icon indicating copy to clipboard operation
virtus copied to clipboard

FixedWidth Coercion

Open endersonmaia opened this issue 7 years ago • 2 comments

It would be nice to have a coercion like FiexdWiththat you could inform parameters like :

  • width: Integer
  • alignment: {left, right}
  • padding : String

Example :

class Register
  include Virtua.model

  attribute :some_field, FixedWidth, width: 6, alignment: :right, padding: " "
end

my_register = Register:new()
my_register.some_field = "abc"

puts my_register.some_field
"   abc"

I tried to navigate through the classes to find where to make this via Custom Coercion, but couldn't come up with an simple implementation.

You someone could point me the direction, I can try to put some effort and code into this.

endersonmaia avatar Jul 16 '18 19:07 endersonmaia

I did something like this

require 'virtus'

class FixedWidth < Virtus::Attribute
    primitive String
    accept_options :width

    def coerce(value)
        if options.include?(:width)
            value.rjust(options[:width], ' ') unless value.nil?
        end
    end
  end

class Registro
    include Virtus.model
  
    attribute :versao, FixedWidth, width: 10
end

endersonmaia avatar Jul 16 '18 21:07 endersonmaia

require 'virtus'

class FixedWidth < Virtus::Attribute primitive String accept_options :width

def coerce(value)
    if options.include?(:width)
        value.rjust(options[:width], ' ') unless value.nil?
    end
end

end

class Registro include Virtus.model

attribute :versao, FixedWidth, width: 10

end

my01caddi avatar Aug 25 '18 10:08 my01caddi