Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FixedWidth Coercion #390

Open
endersonmaia opened this issue Jul 16, 2018 · 2 comments
Open

FixedWidth Coercion #390

endersonmaia opened this issue Jul 16, 2018 · 2 comments

Comments

@endersonmaia
Copy link

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
Copy link
Author

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

@my01caddi
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants