There is a gem of fattr that you can include in your Ruby or gem application to do just that.
require 'fattr' class SiteClient fattr :login fattr :password fattr :domain => 'somedefaultsite.com' def initialize(**attributes) attributes.each do |k, v| public_send k, v end end end client = SiteClient.new client.username = 'susan' client.password = 'anything' another_client = SiteClient.new username: 'bob', password: ' p@ssword1 '
In this example, the fattr method fattr define read and write methods for each attribute. In addition, it can assign a default value to each attribute. The initializer is configured to accept a hash of the key pairs that it will iterate over to fill in the attributes by calling the attribute method with the value to be assigned.
Something to be aware of is an example that generates both read and write methods for your attributes. In your question you are only using attr_reader , so this may not be exactly what you need if you want your class data to be immutable. There may be a way to configure fattr , but I haven't played with that yet, that's not all.
Special thanks to Avdi Grimm and episode 276 of RubyTapas , in which I learned about this.
source share