I write lots of initialize
code that sets attrs to parameters, similar to this:
class SiteClient
attr_reader :login, :password, :domain
def initialize(login, password, domain='somedefaultsite.com')
@login = login
@password = password
@domain = domain
end
end
Is there a more Ruby way of doing this? I feel like I'm writing that same boilerplate setup code over and over.
You can use Ruby Struct
:
class MyClass < Struct.new(:login, :password, :domain)
end
Or you can try some gems for that, i.e. Virtus:
class MyClass
include Virtus.model
attribute :login, String
attribute :password, String
attribute :domain, String
end
And then (in both cases):
MyClass.new(login: 'a', password: 'b', domain: 'c')
You can do a bit better like this:
def initialize(login, password, site = 'somedefaultsite.com')
@login, @password, @domain = login, password, domain
end
and if you don't have an optional argument, then you can be a bit more lazy:
def initialize(*a)
@login, @password, @domain = a
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With