Skip to content

Instantly share code, notes, and snippets.

@jwo
Forked from johnnygoodman/gist:2772856
Created May 23, 2012 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwo/2775692 to your computer and use it in GitHub Desktop.
Save jwo/2775692 to your computer and use it in GitHub Desktop.
Vehicle Class, Make == Instance Variable Dynamic
#-------------------------------------
# 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
@jwo
Copy link
Author

jwo commented May 23, 2012

You can see my version here as a fork of this: https://gist.github.com/2775692/d4e7c9b678c19ac08c7c3fdbaf1e78f77b2f3a6e

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment