DRY Ruby Initialization with Hash Argument

后端 未结 6 2105

I find myself using hash arguments to constructors quite a bit, especially when writing DSLs for configuration or other bits of API that the end user will be exposed to. Wha

6条回答
  •  感情败类
    2020-11-29 17:52

    Please take a look at my gem, Valuable:

    class PhoneNumber < Valuable
      has_value :description
      has_value :number
    end
    
    class Person < Valuable
      has_value :name
      has_value :favorite_color, :default => 'red'
      has_value :age, :klass => :integer
      has_collection :phone_numbers, :klass => PhoneNumber
    end
    
    jackson = Person.new(name: 'Michael Jackson', age: '50', phone_numbers: [{description: 'home', number: '800-867-5309'}, {description: 'cell', number: '123-456-7890'})
    
    > jackson.name
    => "Michael Jackson"
    > jackson.age
    => 50
    > jackson.favorite_color
    => "red"
    >> jackson.phone_numbers.first
    => #"home", :number=>"800-867-5309"}>
    

    I use it for everything from search classes (EmployeeSearch, TimeEntrySearch) to reporting ( EmployeesWhoDidNotClockOutReport, ExecutiveSummaryReport) to presenters to API endpoints. If you add some ActiveModel bits you can easily hook these classes up to forms for gathering criteria. I hope you find it useful.

提交回复
热议问题