Skip to content

Commit

Permalink
Added respond_to_missing? to Item
Browse files Browse the repository at this point in the history
If you try to call a getter of a key that is not in the data hash, you
will get a NoMethodError instead of a KeyError.

Item now responds correctly if asked if it respond_to?(:getter).  This
was breaking in Rails when you use Object#try
  • Loading branch information
willcosgrove committed Jun 13, 2014
1 parent 4cd6b48 commit f7874f3
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 8 additions & 2 deletions lib/cartman/item.rb
Expand Up @@ -46,16 +46,22 @@ def cache_key
end

def method_missing(method, *args, &block)
if method.to_s =~ /=\z/
if method.to_s.end_with?("=")
redis.hset _key, method[0..-2], args[0].to_s
@data.store(method[0..-2].to_sym, args[0].to_s)
version = touch
@data.store(:_version, version)
else
elsif @data.keys.include?(method)
@data.fetch(method)
else
super
end
end

def respond_to_missing?(method, include_private = false)
method.to_s.end_with?("=") || @data.keys.include?(method) || super
end

private

def redis
Expand Down
9 changes: 9 additions & 0 deletions spec/item_spec.rb
Expand Up @@ -28,6 +28,15 @@
it "should touch the item and cart" do
expect{item.quantity = 4}.to change{item._version}.by(1)
end

it "should raise NoMethodError if you use a getter that there isn't a key for" do
expect{ item.weight }.to raise_error(NoMethodError)
end

it "should respond_to the getters and setters" do
expect(item.respond_to?(:name)).to be true
expect(item.respond_to?(:name=)).to be true
end
end

describe "#cost" do
Expand Down

0 comments on commit f7874f3

Please sign in to comment.