Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby way to remove boilerplate code in initializers?

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.

like image 630
SharkLaser Avatar asked Feb 02 '15 21:02

SharkLaser


2 Answers

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')
like image 196
Hauleth Avatar answered Nov 02 '22 06:11

Hauleth


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
like image 40
sawa Avatar answered Nov 02 '22 07:11

sawa