Reputation: 3422
I have a class Product in my rails project, I am trying to retrieve a list of instance methods of my class that are defined in my file (not inherited method or included via mixin). Here's a small sample of my class :
class Product
include Mongoid::Document
include Mongoid::Paperclip
include Mongoid::Search
include Mongoid::Slug
include Mongoid::Timestamps
extend Enumerize
def product_image
image.url(:small) unless image.nil?
end
def product_school_level
self.school_levels.join ' | '
end
def product_grades
self.grades.where(degree_ids: nil).pluck(:name).uniq.join ' | '
end
end
I tried to use Product.instance_methods(false)
. However this still returns a lot of methods I dont need, here's a little sample :
:_run_post_process_callbacks,
:aliased_fields,
:_post_process_callbacks,
:_run_image_post_process_callbacks,
:_image_post_process_callbacks,
:_validation_callbacks,
:nested_attributes?,
:_run_touch_callbacks,
:readonly_attributes?,
:_run_save_callbacks,
:aliased_fields?,
:_save_callbacks,
:localized_fields?,
:readonly_attributes,
:fields?,
:pre_processed_defaults?,
:_update_callbacks,
:post_processed_defaults?,
:fields,
:_id_default
I ran Product.new.method(:_run_post_process_callbacks).source_location
on a few of these methods to try to check where they come from. It seems they all come from active_support.
I never included active_support in my class, so I guess classes in a rails project automatically include active_supports methods ? How is that possible without any inheritance syntax (<<) or include syntax ?
How can I then achieve what I want to do and get rid of these methods I dont need in my list ?
Upvotes: 1
Views: 807
Reputation: 998
Many (most? all?) of those extra methods you are seeing are being created using Module#define_method
. If you dig deep in the source for active_support
, you'll see that. (You aren't directly including active_support
, but it's being pulled in by one or more of the Mongoid
modules.)
So these are in fact valid instance methods of your model class, which is why they are included in instance_methods(false)
. Other methods that are defined "conventionally" in the mixins, such as #freeze
, are reported by instance_methods(true)
, but not by instance_methods(false)
.
I think you may have to do something to filter the list based on the source location. Something along these lines:
my_methods = Product.instance_methods(false).select do |m|
Product.instance_method(m).source_location.first.ends_with? '/product.rb'
end
Upvotes: 2