Skip to content

Instantly share code, notes, and snippets.

@orlando
Created December 4, 2011 17:43
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 orlando/1430798 to your computer and use it in GitHub Desktop.
Save orlando/1430798 to your computer and use it in GitHub Desktop.
method missing override
# this give us activerecord like commands for events, also extend the object with the respective methods
#
# example
#
# @cachedevent.reservations return all reservations in a hash
# {"15"=>#<BSON::OrderedHash:0x-2581ca5a {values}}
#
# also extends the object with
#
# @cachedevent.reservations.extend(ReportAgregator::Reservations)
#
def method_missing(sym, *args, &block)
if self.class.eql?(BSON::OrderedHash) and self.keys.include?(sym.to_s)
object = {}
self[sym.to_s].each do |obj|
object[obj.keys.first] = obj.values.first
end
begin
object.extend("ReportAgregator::#{sym.to_s.capitalize}".constantize)
rescue
end
end
return object unless object.nil?
super(sym, *args, &block)
end
module Reservations
def total_reservations_sat
self.reject {|key,value| t['checked_in'] != true }.size
end
def method_missing(sym, *args, &block)
if self.class.eql?(BSON::OrderedHash || Hash) and self.keys.include?(sym.to_s)
object = {}
self[sym.to_s].each do |obj|
object[obj.keys.first] = obj.values.first
end
end
super(sym, *args, &block)
end
end
require File.dirname(__FILE__) + '/../test_helper'
module ReportAgregator
module Reservations
def test_method
end
end
end
class CachedEventWithModule < Test::Unit::TestCase
def setup
CachedEvent.destroy_all
@account = Factory.create(:account)
@venue = Factory.create(:venue, :accounts => [@account])
@event = Factory.create(:event, :venues => [@venue], :open => Date.today + 7.days)
@reservation = Factory.create(:reservation, :event => @event)
@cached_event = CachedEvent.last
end
def test_return_values_if_key_exists_and_extend_with_module_if_exists
@cached_event.extend(ReportAgregator)
reservations = @cached_event.reservations
assert_equal 1, reservations.count
assert_equal true, reservations.respond_to?('test_method')
end
def test_returns_values_if_key_exists_and_dont_extend_with_module
@cached_event.extend(ReportAgregator)
guests = @cached_event.guests
assert_equal 0, guests.count
assert_equal false, guests.respond_to?('test_method')
end
def test_return_nomethoderror_if_key_dont_exists
@cached_event.extend(ReportAgregator)
exception = assert_raise(NoMethodError) do
@cached_event.nomethod
end
assert_match(/undefined method `nomethod'/, exception.message)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment