palkan / anyway_config

Configuration library for Ruby gems and applications
MIT License
778 stars 52 forks source link

Type coercion for configs #75

Closed corroded closed 3 years ago

corroded commented 3 years ago

Is your feature request related to a problem? Please describe.

It would be great to have type coercion so we don't have to do work-arounds for auto-casting. An example is when we had something like this:

# some_config.rb
class SomeConfig < ApplicationConfig
  attr_config :branch_code
end
# some_config.yml
some:
  branch_code: "123456"
$ SOME_BRANCH_CODE=123456 rails c
> SomeConfig.new.branch_code
> 123456

Describe the solution you'd like

I would suggest something like the describe_options but making it so it coerces the type when loading the data, instead of relying on a flag/workaround as suggested here: https://github.com/palkan/anyway_config/issues/68#issuecomment-697490113

Suggested DSL:

class SomeConfig < ApplicationConfig
  attr_config :branch_code, type: String
end

which will enforce:

$ SOME_BRANCH_CODE=123456 rails c
> SomeConfig.new.branch_code
> "123456"

This probably means type needs to become a reserved word and you might need to group similar attrs like so:

class SomeConfig < ApplicationConfig
  attr_config :branch_code, :name, type: String
  attr_config :some_count, :age, type: Integer
end

Describe alternatives you've considered

The alternative is the suggested turning off of the auto-casting: skip_auto_serialization but not sure how far along that feature is.

edit Another alternative (which I've implemented in our codebase) is to have a method to declare the types explicitly:

class SomeConfig < ApplicationConfig
  attr_config :branch_code, :name, :some_count, :age

  coerce_types(
    branch_code: :string,
    name: :string,
    some_count: :integer,
    age: :integer,
  )
end

P.S. I can volunteer to do this if this sounds like a good idea. Also welcome to shoot holes into this idea, potential bugs, gotchas etc. 🙏