-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
adding struct initializer for reuse later
- Loading branch information
Dean Brundage
committed
Nov 18, 2016
1 parent
6515a1b
commit 339d88e
Showing
4 changed files
with
56 additions
and
17 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
class Thermostat | ||
module StructInitializer | ||
|
||
def initialize(*args) | ||
opts = args.last.is_a?(Hash) ? args.pop : Hash.new | ||
super | ||
members.each do |k| | ||
next if self.send(k) | ||
self.send "#{k}=", (opts[k] || default_value_for(k)) | ||
end | ||
end | ||
|
||
private | ||
|
||
def default_value_for(key) | ||
m = "default_#{key}".intern | ||
self.class.respond_to?(m) ? self.class.send(m) : nil | ||
end | ||
|
||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
class Llama < Struct.new(:length) | ||
include Thermostat::StructInitializer | ||
def self.default_length; 1; end | ||
end | ||
describe Thermostat::StructInitializer do | ||
|
||
let(:default_length) { Llama.default_length } | ||
let(:subject) { Llama.new length } | ||
|
||
context 'when not initialized' do | ||
let(:length) { nil } | ||
it 'has a default length' do | ||
expect( subject.length ).to eq(default_length) | ||
end | ||
end | ||
|
||
|
||
context 'when initialized' do | ||
let(:length) { 2 } | ||
it 'overrides the default length' do | ||
expect( subject.length ).to eq(length) | ||
end | ||
end | ||
|
||
end |