<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Karolina Redden on Medium]]></title>
        <description><![CDATA[Stories by Karolina Redden on Medium]]></description>
        <link>https://medium.com/@dubajkaro?source=rss-f8180de27d2a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*L9VNRE6GesUHxdpp1Wogug@2x.jpeg</url>
            <title>Stories by Karolina Redden on Medium</title>
            <link>https://medium.com/@dubajkaro?source=rss-f8180de27d2a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:27:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dubajkaro/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Metaprogramming in Ruby]]></title>
            <link>https://medium.com/@dubajkaro/metaprogramming-in-ruby-a9bec8257d34?source=rss-f8180de27d2a------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9bec8257d34</guid>
            <dc:creator><![CDATA[Karolina Redden]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 00:49:16 GMT</pubDate>
            <atom:updated>2022-07-13T14:29:09.091Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is metaprogramming?</h3><p>In a nutshell, think about it as “programming programming”. Yes, you got it right, metaprogramming is writing programs that can operate other programs.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F7pHTiZYbAoq40%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Finception-7pHTiZYbAoq40&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZDN3czM5amlkMTZ6ZHI2azRxbThyMndxb3c2czE4cHgzdXFsdXpxNCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F7pHTiZYbAoq40%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="300" frameborder="0" scrolling="no"><a href="https://medium.com/media/afca1469957bd6f11ca76406194e1290/href">https://medium.com/media/afca1469957bd6f11ca76406194e1290/href</a></iframe><p>This process is not new to the software development world, one of the first languages to leverage the concept of metaprogramming was a list processing language called LISP.</p><p>Nowadays metaprogramming is heavily utilized in many languages, but this article will be concentrating on Ruby and its framework. You will soon realize that all the shortcuts you took advantage of while working with Rails have their root in the concept of metaprogramming.</p><h3>Metaprogramming in action</h3><h4>Methods on the fly</h4><p>Starting off with a simple example taken from Rails framework. Assuming you have created a database table for <em>users </em>with columns: <em>name</em> and <em>email</em>. Without adding a method to your model, you can run the following query against your database, and somehow, it works! 🤯.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLsUsgpdL6V_Jb3iXXuLKA.png" /></figure><p>The good news is that it is not “magic” and there is an explanation. Rails is using metaprogramming to generate the method for you on the spot, just by looking at the column names you have defined. Neat!</p><h4>Ask code questions and the code shall answer</h4><p>A useful aspect of metaprogramming in Ruby is something called introspection. This means the ability to ask your code questions about itself during runtime. With .respond_to? method you can find out if any object can respond to a method call before making that call.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*G7HTD3N_nUShVbkc-Hu9KA.png" /><figcaption>respond_to? introspection</figcaption></figure><p>In case you wonder about the inheritance of your models or classes you can look up the ancestry chain with built-in methods such as .ancestors or .ancestors.size.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPnPSjyOzcl6tpHciO5T-w.png" /></figure><h4>The send method</h4><p>If you ever wanted to add some information to an instance you have probably created a new instance and then applied properties one by one. While this is a correct approach there is something easier. Let’s create a method within your class that can take care of inserting all the details for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*bBmgl9OW0AyHSeIO1tdw1w.png" /></figure><p>Alright, so what is happening here?</p><p>As you loop through user_info we call the send() method. The first argument is the method name (e.g. title = ), the second is an argument for that method (e.g. “Mr.).</p><pre>self.send(“#{k}=”, values[k])</pre><p>The first loop turn would look like:</p><pre>self.title = “Mr.”</pre><h4>define_method</h4><p>One of the powerful metaprogramming tools is define_method, its main purpose is creating methods dynamically on objects at application runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*QDZz-9ng2A1nWCYaiLpvVw.png" /><figcaption>define_method</figcaption></figure><p>In the example above we are dynamically creating a new method that is the evaluation of the occupation variable_details. If you need to have the view that renders all the occupation data for users, this allows you to build dynamic components that tap into the data set, rendering unique data on the fly.</p><h4>method_missing</h4><p>Whenever any method is called, Ruby searches for it by traversing up the ancestors tree. In the event the method cannot be found we are getting NoMethodErrorexception. Puts sad_face.</p><p>Here is where method_missing comes to the rescue. It is triggered when the method has not been defined. It lets you customize your own error messages with the <em>concept of method overriding</em> in the event when you wouldn’t want to get an exception.</p><p>The syntax of method_missing is defined in the basic object:</p><pre>def method_missing(m, *args, &amp;block)<br>   #return<br>end</pre><pre>m -&gt; name of the missing method, required parameter.<br>*args, &amp;block -&gt; both optional parameters to add remaining parameters and include blocks called within the method.</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1387219a677743ed7a8039e85f0e8b06/href">https://medium.com/media/1387219a677743ed7a8039e85f0e8b06/href</a></iframe><p>In the event you call a method that is not defined in your code and is not guarded by method_missing you will still get an exception. The else part of the code will take care of that.</p><pre>tom.girlfriend<br>#outputs `method_missing&#39;: undefined method `girlfriend&#39; for #&lt;User:XXXXXXXX&gt; (NoMethodError)<br></pre><p>Tom, what were you thinking? Devs don’t have gfs, duh!</p><h3>Conclusions</h3><p>Metaprogramming is an excellent concept. It allows developers to analyze their code, can help debug, avoid repetitions and create new methods quickly. It simplifies the code and generally allows to get more done in a shorter amount of time.</p><p>On that note, it is important to highlight that metaprogramming is not suitable for every project and every team of developers. Just because you were able to successfully apply metaprogramming to your project it does not mean it should be a permanent part of your code base. What is most important is whether your code is modular and easy to understand by others since the program requirements always change. The decision about using meta approaches should be well thought out after considering all the pros and cons.</p><h4>References</h4><p>¹ <a href="https://medium.com/swlh/metaprogramming-in-ruby-1b69b1b54202">https://medium.com/swlh/metaprogramming-in-ruby-1b69b1b54202</a></p><p>² <a href="https://www.crondose.com/2016/08/examples-metaprogramming-guide-beginners/">https://www.crondose.com/2016/08/examples-metaprogramming-guide-beginners/</a></p><p>³ <a href="https://medium.com/podiihq/method-missing-in-ruby-af4c6edd5130">https://medium.com/podiihq/method-missing-in-ruby-af4c6edd5130</a></p><p>⁴ <a href="https://www.easytechjunkie.com/what-is-metaprogramming.htm">https://www.easytechjunkie.com/what-is-metaprogramming.htm</a></p><p>⁵ <a href="https://www.cloudbees.com/blog/metaprogramming-in-ruby">https://www.cloudbees.com/blog/metaprogramming-in-ruby</a></p><p>⁶ <a href="https://levelup.gitconnected.com/metaprogramming-in-ruby-df797b2f784f">https://levelup.gitconnected.com/metaprogramming-in-ruby-df797b2f784f</a></p><p>⁷ <a href="https://www.cloudbees.com/blog/metaprogramming-in-ruby">https://www.cloudbees.com/blog/metaprogramming-in-ruby</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9bec8257d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>