Skip to content

Commit

Permalink
if method_missing accepts some method name patterns, then respod_to? …
Browse files Browse the repository at this point in the history
…should return true for the same method names
  • Loading branch information
justinfrench committed Dec 31, 2008
1 parent 3720ce0 commit baff20e
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
10 changes: 9 additions & 1 deletion lib/active_time.rb
@@ -1,5 +1,7 @@
class ActiveTime class ActiveTime


COLLECTION_METHOD_NAMES_PATTERN = /[a-z_]+s$/

attr_accessor :starting, :ending attr_accessor :starting, :ending
alias_method :time, :starting alias_method :time, :starting


Expand Down Expand Up @@ -60,7 +62,7 @@ def range
# #
# TODO: memoize the results, to avoid multiple queries for the same method call. # TODO: memoize the results, to avoid multiple queries for the same method call.
def method_missing(method_name, *args) def method_missing(method_name, *args)
if method_name.to_s =~ /[a-z_]+s$/ if method_name.to_s =~ COLLECTION_METHOD_NAMES_PATTERN
args[0] ||= :created_at args[0] ||= :created_at
begin begin
klass_name = method_name.to_s.singularize.classify klass_name = method_name.to_s.singularize.classify
Expand All @@ -76,6 +78,12 @@ def method_missing(method_name, *args)
end end
end end


# If method_missing deals with these, respond_to should too.
def respond_to?(method_name)
return true if method_name.to_s =~ COLLECTION_METHOD_NAMES_PATTERN
super
end

# Provides a human friendly string description of the date or time range being used. Examples: # Provides a human friendly string description of the date or time range being used. Examples:
# #
# ActiveTime.new(2008) # => "in 2008" # ActiveTime.new(2008) # => "in 2008"
Expand Down
7 changes: 7 additions & 0 deletions test/active_time_test.rb
Expand Up @@ -208,6 +208,13 @@ def ending
assert_equal @object.starting, @object.time assert_equal @object.starting, @object.time
end end


should "respond to methods named after collections of ActiveRecord objects" do
assert @object.respond_to?(:posts)
assert @object.respond_to?(:activity_events)
assert @object.respond_to?(:users)
assert @object.respond_to?(:summaries)
end

end end


end end
Expand Down

0 comments on commit baff20e

Please sign in to comment.