A-Brief-on-use-of-Reflection-in

<p>Reflection is the ability of a program to introspect itself, providing insight into its own structure and behavior at runtime. It enables inquiring about classes, methods, and attributes and also supports dynamic code manipulation.</p> <p>There are methods in Ruby classes and objects that allow inspection of specific areas of code. In Ruby on Rails, reflection is primarily achieved through methods provided by the ActiveRecord::Reflection module.</p> <p><img alt="" src="https://miro.medium.com/v2/resize:fit:700/0*GbW2M88HneH0j2YL" style="height:467px; width:700px" /></p> <p>Photo by&nbsp;<a href="https://unsplash.com/@marcojodoin?utm_source=medium&amp;utm_medium=referral" rel="noopener ugc nofollow" target="_blank">Marc-Olivier Jodoin</a>&nbsp;on&nbsp;<a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral" rel="noopener ugc nofollow" target="_blank">Unsplash</a></p> <p>Below are some of the methods provided in Ruby to explore more about the objects in runtime.</p> <pre> class Story end obj = Story.new obj.class # Story obj.is_a? Story # true</pre> <p><code>class</code>&nbsp;method tells you the class of any object in Ruby.&nbsp;<code>is_a?</code>&nbsp;method lets us know if the given object is the instance of the class in the argument. It returns true for any subclass of the Class passed. If you want to check the direct instance alone, use&nbsp;<code>instance_of?</code>.</p> <pre> obj = Story.new obj.methods obj.instance_variables SomeModule.constants Story.define_method(:clap) do |count| puts &quot;Successfully clapped #{count} times&quot; end</pre> <p><code>methods</code>&nbsp;return an array of symbols representing the available methods for an object or class and&nbsp;<code>instance_variables</code>&nbsp;returns an array of instance variable names for an object. Moreover, with Ruby&rsquo;s metaprogramming, you can create methods on the fly with&nbsp;<code>define_method</code>.</p> <p>Among the arsenal of reflective tools, the&nbsp;<code>source_location</code>&nbsp;method shines as a spotlight. It is part of the&nbsp;<code>Method</code>&nbsp;class and reveals the file path and line number where a method is defined.</p> <pre> obj = Story.new method = obj.method(:clap) method.source_location # returns path to file with the method clap</pre> <p>When debugging,&nbsp;<code>source_location</code>&nbsp;can be invaluable for tracking down the origin of methods. It helps you quickly identify where a particular method is defined (if you&rsquo;re not using an IDE like RubyMine), aiding in identifying issues and optimizing code.</p> <p><a href="https://levelup.gitconnected.com/rails-reflects-for-you-84dc507d4dee">Website:-</a></p>