-
-
Save jwo/2775692 to your computer and use it in GitHub Desktop.
Vehicle Class, Make == Instance Variable Dynamic
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 part just to run the specs | |
# | |
# | |
require 'rspec' | |
class Vehicle; end | |
# end | |
#------------------------------------- | |
#require_relative './vehicle' | |
class Automobile < Vehicle | |
COMPARABLE_ATTRIBUTES = [:color, :make, :model, :year] | |
COMPARABLE_ATTRIBUTES.each do |attr| | |
attr_accessor attr | |
end | |
def initialize(hash) | |
hash.each do |key, value| | |
send("#{key}=", value) if self.respond_to?("#{key}=") | |
end | |
end | |
def self.wheels | |
4 | |
end | |
def attribute_hash | |
COMPARABLE_ATTRIBUTES.inject({}) {|hash, attr| hash[attr] = send(attr); hash} | |
# I left the below commented out since "inject" is a complex method... it's basically doing the same as below | |
#hash = {} | |
#COMPARABLE_ATTRIBUTES.each {|attr| hash[attr] = send(attr)} | |
#hash | |
end | |
#this is brittle. It'll break as soon as other instance variables are added to the Automobile class. | |
def ==(other) | |
self.attribute_hash == other.attribute_hash | |
end | |
end | |
describe Automobile do | |
let(:color) { "Red" } | |
let(:make) { "Toyota" } | |
let(:model) { "Camry" } | |
let(:year) { 2012 } | |
describe ":new" do | |
subject { Automobile.new(color: color, make: make, model: model, year: year) } | |
its(:color) {should eq(color) } | |
its(:make) {should eq(make) } | |
its(:model) {should eq(model) } | |
its(:year) {should eq(year) } | |
it "should not throw up if I send in something unexpected" do | |
expect { | |
Automobile.new(paint_job: color) | |
}.to_not raise_error | |
end | |
end | |
describe "#attribute_hash" do | |
subject { Automobile.new(color: color, make: make, model: model, year: year) } | |
it "should include all the attributes" do | |
subject.attribute_hash.should eq ( {color: color, make: make, model: model, year: year} ) | |
end | |
end | |
describe "#==" do | |
let(:auto_one){ Automobile.new(color: color, make: make, model: model, year: year) } | |
let(:auto_two){ Automobile.new(color: color, make: make, model: model, year: year) } | |
it "should be equal if color/make/model/year are the same" do | |
auto_one.should eq(auto_two) | |
end | |
it "should not be equal if one differs" do | |
auto_two.year = 2015 | |
auto_one.should_not eq(auto_two) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can see my version here as a fork of this: https://gist.github.com/2775692/d4e7c9b678c19ac08c7c3fdbaf1e78f77b2f3a6e