Class: Array
- Inherits:
-
Object
- Object
- Array
- Defined in:
- lib/activerecord_plurals.rb
Overview
This monkey-patches the array class to catch plural method calls. It assumes we’re running in a rails environment that provides us with String#singularize. The limitation that this method imposes on rails applications is that you cannot have a column with a name that collides with methods defined on Array (or on its ancestor). i.e. if you have a model named “Diary” with the column “entry”, calling Diary.entries will invoke the underlying Object#entries method. This is undesired behavior and it is up to the developer to wisely avoid these cases.
Instance Method Summary collapse
- #method_missing(method_id, *args, &block) ⇒ Object
-
#respond_to?(symbol, include_private = false) ⇒ Boolean
Respond also to methods on arrays of ActiveRecord instances.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_id, *args, &block) ⇒ Object
42 43 44 45 46 47 48 |
# File 'lib/activerecord_plurals.rb', line 42 def method_missing(method_id, *args, &block) singular_method_id = method_id.to_s.singularize.to_sym if method_id != singular_method_id return self.map(&singular_method_id) end super end |
Instance Method Details
#respond_to?(symbol, include_private = false) ⇒ Boolean
Respond also to methods on arrays of ActiveRecord instances. Note: There is intentionally no restriction on the uniformity of instances in the array, i.e. they don’t have to all be of the same class. This is useful when you have a mixed array with objects that share the same attributes (Dog, Labrador < Dog for example) and follows ruby’s duck-typing conventions.
55 56 57 |
# File 'lib/activerecord_plurals.rb', line 55 def respond_to?(symbol, include_private=false) super or all?{|e| e.is_a?(ActiveRecord::Base) && e.class.respond_to?(symbol)} end |