<?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 Alican Sungur on Medium]]></title>
        <description><![CDATA[Stories by Alican Sungur on Medium]]></description>
        <link>https://medium.com/@asungur?source=rss-88200c98110e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PdO7t-Uk7nipI6FgHuDjyA.jpeg</url>
            <title>Stories by Alican Sungur on Medium</title>
            <link>https://medium.com/@asungur?source=rss-88200c98110e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 23:51:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@asungur/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[Add RabbitMQ and gocron to your DigitalOcean droplet [Part 3]]]></title>
            <link>https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-3-7eac34d84e4?source=rss-88200c98110e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eac34d84e4</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Alican Sungur]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 16:58:48 GMT</pubDate>
            <atom:updated>2022-04-21T16:58:48.933Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a simple message consumer with gocron</h4><p>(This is the last part of a 3 part series. You can read the previous part <a href="https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-2-a0c0fc445ec7">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6jzKrDGG8mo0uk_2" /><figcaption>Photo by <a href="https://unsplash.com/@arwinneil?utm_source=medium&amp;utm_medium=referral">Arwin Neil Baichoo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Summary of the previous chapter</h3><p>In the previous chapter, we’ve built our message producer function enqueue. The enqueue function is invoked when our application server receives traffic and publishes a message to RabbitMQ. Depending on your configuration you can call enqueue() function call elsewhere.</p><h3>Building the consumer</h3><p>Next, we will build our cron-job to run every hour/minute(depending on your preference) and dequeue messages in our queue. To keep things simple, when a message is consumed we will send a basic notification email using Mailgun’s go package.</p><p>(You can find the repo of the simple consumer from <a href="https://github.com/asungur/simple_consumer/blob/main/main.go">here</a>)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0b4629ae6911c042b23d9b39feffe8d/href">https://medium.com/media/e0b4629ae6911c042b23d9b39feffe8d/href</a></iframe><p>In this example, the worker will run in the background and every 2 minutes it will execute processMessages function. We will talk about setting up this worker to run as a systemdservice later.</p><p>Similar to the previous example where we create a Connection and a Channel to be able to execute tasks on our queue.</p><pre>amqpServerURL := os.Getenv(&quot;AMQP_SERVER_URL&quot;)<br>	<strong>connectRabbitMQ, err := amqp.Dial(amqpServerURL)</strong><br>	if err != nil {<br>		panic(err)<br>	}<br>	defer connectRabbitMQ.Close()<br>	<strong>channelRabbitMQ, err := connectRabbitMQ.Channel()</strong><br>	if err != nil {<br>		panic(err)<br>	}<br>	defer channelRabbitMQ.Close()</pre><p>We will be using Consume() function on our channel to retrieve the messages. You can see the comments for the options. To keep things simple we will automatically acknowledge the messages as we consume them.</p><pre>messages, err := <strong>channelRabbitMQ.Consume</strong>(<br><strong>		&quot;FallbackAPIQueue&quot;,</strong><br>		&quot;&quot;,<br>		true,                      // auto acknowledge<br>		false,                     // exclusive<br>		false,                     // no local<br>		false,                     // no wait<br>		nil,<br>	)<br>	if err != nil {<br>		log.Println(err)<br>	}<br>	log.Println(&quot;You&#39;ve connected to RabbitMQ&quot;)<br>	log.Println(&quot;Waiting for messages&quot;)<br><br>	if len(messages) == 0 {<br>		log.Println(&quot;You don&#39;t have any messages in the queue&quot;)<br>	}<br>	for message := range messages {<br>		if string(message.Body) == &quot;A request has been sent via fallback API&quot; {<br>			sendSimpleMessage()<br>		}<br>	}</pre><p>Lastly, for each message we consume, we will call sendSimpleMessage()</p><p>Using Mailgun’s go client library mailgun-go we can send simple emails. This will require you to have an account with Mailgun. You will need your Mailgun domain and your API key saved in your environment variables. There is a link in the resources section below if you don’t have a Mailgun account.</p><pre>func <strong>sendSimpleMessage()</strong> {<br>	api_key := os.Getenv(&quot;MAILGUN_API_KEY&quot;)<br>	sandbox_domain := os.Getenv(&quot;MAILGUN_DOMAIN&quot;)<br><br>	mg := mailgun.NewMailgun(sandbox_domain, api_key)<br>	sender := &quot;testingsomething@example.com&quot;<br>	subject := &quot;security warning&quot;<br>	body := &quot;Your fallback api is exposed&quot;<br>	recipient := &quot;&lt;YOUR_EMAIL&gt;&quot;<br>	message := mg.NewMessage(sender, subject, body, recipient)<br>	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)<br>	defer cancel()<br>	resp, id, err := mg.Send(ctx, message)<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	fmt.Printf(&quot;ID: %s Resp: %s\\n&quot;, id, resp)<br>}</pre><p>Now, let&#39;s configure systemd to run this application as a service.</p><p>systemd is an initialisation system and system manager that comes with most Linux distributions. It comes with its management tool systemctl</p><p>If you want to learn more about systemd or if you are new to it, you can find a tutorial link below in the resources. Let’s get back to creating our service.</p><p>First, we will create a service file:</p><pre>$ sudo vim /lib/systemd/system/simple_consumer.service</pre><p>Next, we will add the following configuration options in our simple_consumer.service:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5c524d2c3f8a8a8a07fed1c72c75654/href">https://medium.com/media/a5c524d2c3f8a8a8a07fed1c72c75654/href</a></iframe><p>Before we move on, let’s talk about some of these configuration steps:</p><ol><li>On line 3, ConditionPathExists is required to make sure that our application directory is present in our server before it starts running</li><li>After on line 6, tells systemd to wait until postgresql service is started. This is required because I’m integrating this into my simple API server. This might not be required depending on your configuration.</li><li>On line 12, we specify WorkingDirectory . This is important to retrieve our environment variables from our .env file.</li><li>Lastly, ExecStart specifies the location of our executable file</li></ol><p>Before we enable our system, we need to give relevant permissions to run our application:</p><pre>$ sudo chmod +x /opt/appDir/simple_consumer</pre><p>Now using systemctl we can first enable the service and start it. We can check the status of the application using the last command:</p><pre>$ sudo systemctl enable simple_consumer      # Enable the service<br>$ sudo systemctl start simple_consumer       # Start the service<br>$ sudo systemctl status simple_consumer      # Check service status</pre><p>Now lets trigger enqueue a couple of times and see our queue before and after the cron-job is run:</p><pre>$ sudo rabbitmqctl list_queues</pre><pre>Timeout: 60.0 seconds ...<br>Listing queues for vhost / ...<br>name messages<br>FallbackAPIQueue 3</pre><p>The number next to FallbackAPIQueue should go down to 0 and in our inbox, we should have an email for each message that is dequeued from our queue 🎊</p><h3>Resources</h3><ul><li><a href="https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units">How To Use Systemctl to Manage Systemd Services and Units</a></li><li><a href="https://pkg.go.dev/github.com/go-co-op/gocron">gocron package</a></li><li><a href="https://www.atpeaz.com/running-go-app-as-a-service-on-ubuntu/">Running Go app as a Service on Ubuntu</a></li><li><a href="https://pkg.go.dev/github.com/BoltApp/mailgun-go">Go mailgun package</a></li><li><a href="https://documentation.mailgun.com/en/latest/quickstart-sending.html">Configuring your Mailgun account</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eac34d84e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-3-7eac34d84e4">Add RabbitMQ and gocron to your DigitalOcean droplet [Part 3]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add RabbitMQ and gocron to your DigitalOcean droplet [Part 2]]]></title>
            <link>https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-2-a0c0fc445ec7?source=rss-88200c98110e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c0fc445ec7</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Alican Sungur]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 16:46:05 GMT</pubDate>
            <atom:updated>2022-04-21T16:46:05.209Z</atom:updated>
            <content:encoded><![CDATA[<h4>Configuring RabbitMQ</h4><p>(This is part 2 of a 3 part series. You can read the first part <a href="https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-1-a191856ae06f">here</a>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LwYAsw3RXHFmSe3t" /><figcaption>Photo by <a href="https://unsplash.com/@daryan?utm_source=medium&amp;utm_medium=referral">Daryan Shamkhali</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Before we start</h3><p>For working with your DigitalOcean droplet, you need to SSH into your server. I advise you to create a new admin user while doing this. Using the root user is fine if you know what you are doing. If you are unsure, you will find some useful links in the references section.</p><h3>Configuring RabbitMQ</h3><p>Let’s start configuring RabbitMQ on our server. RabbitMQ usually comes installed with your DO depending on how up-to-date your Linux distribution is.</p><p>You can confirm this by running the status command and checking for the output:</p><pre>$ sudo rabbitmqctl status | grep rabbit<br>.<br>.<br>.<br>{rabbit,&quot;RabbitMQ&quot;,....}</pre><p>If RabbitMQ is <strong>not</strong> installed, simply run:</p><pre>$ sudo apt-get install rabbitmq-server</pre><p>Now that RabbitMQ is installed, we need to <strong>create a user before establishing a connection</strong>. We will use RabbitMQ’s command line management tool rabbitmqctl for this:</p><pre>rabbitmqctl add_user &lt;USERNAME&gt; &lt;PASSWORD&gt;</pre><p>Using the same tool, give <strong>admin rights to your user</strong>:</p><pre>rabbitmqctl set_user_tags &lt;USERNAME&gt; administrator</pre><p>In this last step, we will give permissions to our admin user. RabbitMQ permissions are classified as <strong>configuration, read</strong> and <strong>write permissions.</strong> For this application, it is tolerable to grant all, but this is a security risk in a production application.</p><pre>rabbitmqctl set_permissions -p / &lt;USERNAME&gt; &quot;.*&quot; &quot;.*&quot; &quot;.*&quot;</pre><p>Now that we created our user, let’s save the connection string in our application&#39;s environment variables. We will be using .env file for this. Add the below line to your .env file in your application:</p><pre>AMQP_SERVER_URL=amqp://&lt;USERNAME&gt;:&lt;PASSWORD&gt;@localhost:5672/</pre><p>See the amqp prefix? It stands for <strong>“The Advanced Message Queuing Protocol”</strong>. This is the default protocol that is used by RabbitMQ. We will be using this with <a href="https://pkg.go.dev/github.com/streadway/amqp">amqp client library for go</a>.</p><p>Before we implement the enqueue functionality, let’s confirm if we can check our queues:</p><pre>$ sudo rabbitmqctl list_queues</pre><pre>Timeout: 60.0 seconds ...<br>Listing queues for vhost / ...<br>name	messages</pre><p>Since we have not created a queue yet, we are not expecting to see anything listed by this command.</p><h3>Enqueueing messages</h3><p>We will be creating an enqueue function that handles the message production. You can add enqueue() function call to one of your API controllers if you want to test this with your server. I am using POST /fallback endpoint to test this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67d6ca78818f7989a7043d543115d0f4/href">https://medium.com/media/67d6ca78818f7989a7043d543115d0f4/href</a></iframe><p>Let’s break down the key parts of the function that sends messages to &quot;FallbackAPIQueue&quot;.</p><p>On line 2, we retrieve our connection URL AMQP_SERVER_URL from environment variables.</p><p>Next, we establish a <strong>connection</strong> using amqp.Dial() . We are not done yet. With RabbitMQ, most of the operations are handled over channels. We can retrieve a <strong>channel</strong> using Channel() on our connection (on line 8)</p><p>Lastly, we can defer Close() functions on the <strong>connection</strong> and the <strong>channel</strong> to make sure the connection is closed properly after we submit our message to the queue.</p><p>On line 13, we declare the queue to which we want to submit messages. For this, we use AMQP’s <a href="https://github.com/streadway/amqp/blob/v1.0.0/channel.go#L751">func (*Channel)[QueueDeclare]</a> function.</p><pre>_, err = channelRabbitMQ.QueueDeclare(<br>		&quot;FallbackAPIQueue&quot;,<br>		true,           // durable<br>		false,          // auto delete<br>		false,          // exclusive(only declaring channel can access the queue)<br>		false,          // no wait<br>		nil,            // table<br>	) </pre><p>This function creates the queue with the given name if it is not already been created.</p><p>On line 24, we define our message using amqp.Publishing. We will be using a simple plain text message.</p><pre>message := amqp.Publishing{<br>		ContentType: &quot;text/plain&quot;,<br>		Body:        []byte(&quot;A request has been sent via fallback API&quot;),<br>	}</pre><p>Lastly, we can publish our message calling Publish on our <strong>channel</strong>.</p><pre>channelRabbitMQ.Publish(<br>		&quot;&quot;,                      // exchange<br>		&quot;FallbackAPIQueue&quot;,      // Queue<br>		false,                   // mandatory<br>		false,                   // immediate<br>		message,<br>);</pre><p>When the function is triggered the messages will be enqueued to our &quot;FallbackAPIQueue&quot;We can see the queue and the number of messages by using the same command:</p><pre>➜  ~ sudo rabbitmqctl list_queues<br>Password:<br>Timeout: 60.0 seconds ...<br>Listing queues for vhost / ...<br>name	messages<br>FallbackAPIQueue	3</pre><p>With this, we now completed the message publishing mechanism 🚀</p><p>In the next chapter, we will look into consuming these messages on a daily basis using gocron package.</p><h3>Resources</h3><ul><li><a href="https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04">DigitalOcean Blog: Initial Server Setup</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-install-and-manage-rabbitmq">How To Install and Manage RabbitMQ</a></li><li><a href="https://stackoverflow.com/questions/40436425/how-do-i-create-or-add-a-user-to-rabbitmq">Creating RabbitMQ users and providing permissions</a></li><li><a href="https://www.rabbitmq.com/install-debian.html">RabbitMQ installation</a></li><li><a href="https://pkg.go.dev/github.com/streadway/amqp">Go </a><a href="https://pkg.go.dev/github.com/streadway/amqp">amqp package</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c0fc445ec7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-2-a0c0fc445ec7">Add RabbitMQ and gocron to your DigitalOcean droplet [Part 2]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add RabbitMQ and gocron to your DigitalOcean droplet [Part 1]]]></title>
            <link>https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-1-a191856ae06f?source=rss-88200c98110e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a191856ae06f</guid>
            <category><![CDATA[digitalocean]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alican Sungur]]></dc:creator>
            <pubDate>Thu, 21 Apr 2022 16:28:41 GMT</pubDate>
            <atom:updated>2022-04-21T16:28:41.137Z</atom:updated>
            <content:encoded><![CDATA[<h4>Setup your own message queue and cron-job on your DigitalOcean droplet.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZCe8583-MeA5AgUn" /><figcaption>Photo by <a href="https://unsplash.com/@blackprince_in?utm_source=medium&amp;utm_medium=referral">Prince Patel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A modern web application in 2022 uses dozens of third party services. These services simplify application development so much that it makes web development almost too easy.</p><p>This is even more apparent for distributed systems. Using different services of your cloud provider allows you to focus on developing the core components that are more important for the business.</p><p>For example, instead of configuring message brokers on Linux servers, you can use a “Queue as a Service” solution. Do you want to run scheduled tasks? Don’t bother setting up cron workers on your servers, just use a “Function as a Service” solution.</p><p>If you are working in a high traffic environment where downtime can not be tolerated, using these third party solutions is totally reasonable. Instead of a DIY solution, just delegate the liability to a third party service.</p><h3>So why bother?</h3><p>In this article, I will walk through a VPS(virtual private server) configuration. The main focus of the article will be on queues(<strong>rabbitMQ</strong>) and cron-jobs(<strong>gocron</strong>).</p><p>I am writing this article for two main reasons. If you are here due to a similar curiosity, this article is for you regardless of your level.</p><ol><li>To be able to appreciate how things were done back in the day.</li><li>Develop a practical understanding of how queues and cron-workers can be implemented in a web server.</li></ol><p>You hear stories from the industry veterans. Imagine you started working at a new company. You’ve been assigned to set up or maintain an application that is deployed on an on-premises server. The configuration is massive. Maybe there are multiple RDBMSes running on the same machine. There are cron-workers run overnight to handle some tasks. Things can get too complicated very easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YtlOf3iohBc-j_jp" /><figcaption>Photo by <a href="https://unsplash.com/@cakirchoff?utm_source=medium&amp;utm_medium=referral">Chad Kirchoff</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Secondly, I think it is very difficult to operate in an environment where you do not possess an understanding of how different components operate at a lower level. This reminds me of the movie “Ford v Ferrari”. Legendary car designer/mechanic Ken Miles was also a great racing driver. You might hear that many other racing drivers were also good mechanics (i.e, Michael Schumacher).</p><h3>Why DigitalOcean?</h3><p>For this exercise, I decided to use a DigitalOcean droplet instead of the popular AWS EC2(or similar alternatives). DO droplets are really easy to set up. I also find DO Dashboard very intuitive.</p><p>You can use their most basic plan with an up-to-date Ubuntu distribution and deploy to the closest data centre. If you get stuck, you can find really good articles on their blog.</p><h3>Assumptions</h3><p>To make this exercise a bit more interactive, I decided to deploy a RESTful API that handles HTTP requests that trigger the enqueue process. The application runs as a systemd service in the background and restarts if the server reboots. You can find the repo of this application <a href="https://github.com/asungur/simple_api_postgres">here</a>. Note that this application uses <strong>Postgresql</strong> which requires additional configuration. If you want to use this application, you might want to simplify it or code up your own.</p><p>Building the RESTful API is <strong>not a compulsory step for this exercise</strong> and I will not be covering how to build it or how to deploy this application to our VPS.</p><p><a href="https://en.wikipedia.org/wiki/KISS_principle">We will keep things simple and stupid</a>. We will be using hard-coded values in our messages and emails. The purpose of this exercise is to replicate a workflow, not the outcome.</p><h3>Final VPS configuration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vLCf6QQVXhrhWO6WX83cbQ.png" /><figcaption>Final Workflow deployed on our virtual private server</figcaption></figure><p>In the next chapter, <strong>Part 1</strong> we will be setting up the RabbitMQ and adding <strong>enqueue</strong> functionality to our app.</p><p>After we confirm that our queue holds the messages that are enqueued by our app, we will move on to <strong>Part 2</strong>. Here we will build a Go application that <strong>dequeues</strong> the messages. We will keep the application running as a systemd service.</p><p>The consumer app will use clockwork functionality(using gocron library) and check the message queue every day(or hour depending on your choice) and send emails. For the email delivery, we will use Mailgun’s Go client library.</p><p>See you in chapter 2 👋</p><h3>Resources</h3><ul><li><a href="https://www.digitalocean.com/community/tutorials/initial-server-setup-with-ubuntu-20-04">DigitalOcean Blog: Initial Server Setup</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-install-postgresql-on-ubuntu-20-04-quickstart">How To Install PostgreSQL on Ubuntu</a></li><li><a href="https://www.imdb.com/title/tt1950186/">Ford v Ferrari (2019)</a></li><li><a href="http://adam.herokuapp.com/past/2010/4/13/rethinking_cron/">Rethinking Cron - Adam Wiggins</a></li><li><a href="http://adam.herokuapp.com/past/2010/6/30/replace_cron_with_clockwork/">Cron vs Clockwork - Adam Wiggins</a></li><li><a href="https://www.rabbitmq.com/tutorials/tutorial-one-go.html">RabbitMQ tutorial one</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a191856ae06f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/add-rabbitmq-and-gocron-to-your-digitalocean-droplet-part-1-a191856ae06f">Add RabbitMQ and gocron to your DigitalOcean droplet [Part 1]</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your own Domain-Specific Language with Ruby]]></title>
            <link>https://asungur.medium.com/build-your-own-domain-specific-language-with-ruby-dcdcefb17cfb?source=rss-88200c98110e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcdcefb17cfb</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alican Sungur]]></dc:creator>
            <pubDate>Wed, 06 Jan 2021 14:06:52 GMT</pubDate>
            <atom:updated>2021-01-11T10:31:54.588Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iychWs3Tw3h5tVgj" /><figcaption>Photo by <a href="https://unsplash.com/@randyfath?utm_source=medium&amp;utm_medium=referral">Randy Fath</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>“So, what is your favourite design pattern?” As odd as it sounds, it is a common question between fellow engineers and in job interviews.</p><p>But aren’t we supposed to weigh our options according to our application logic and pick a suitable one? Leaving that aside, my answer would probably be <strong>internal DSLs</strong>.</p><p>Arguably, one of the most famous books written on this subject is <em>Design Patterns: Elements of Reusable Object-Oriented Software</em> by the ”<strong>Gang of Four</strong>”. However, you won’t find DSLs in this book, and which is why exactly it is interesting. Most of the original design patterns described in this book were developed without Ruby in mind. By leveraging Ruby’s features, DSL provides a way to implement our own little language.</p><p>When writing Ruby code, we use internal DSLs quite often. <strong><em>Rake</em></strong>, <strong><em>RSpec</em></strong>, <strong><em>ActiveRecord</em></strong> and <strong><em>Sinatra</em></strong> come with their own internal DSL. Let’s examine two common testing libraries among Rubyists: <strong><em>minitest</em></strong> and <strong><em>RSpec</em></strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db60061e1f74146756cf6e45246c770c/href">https://medium.com/media/db60061e1f74146756cf6e45246c770c/href</a></iframe><p>The former <em>minitest</em> example uses pure Ruby, our PlaneTest<em> class</em> inherits from MiniTest::Test and we create instance methods for each test. On the <em>RSpec</em> example, we use the two methods describe and it for the same purposes. Under the hood, <em>RSpec</em> uses a DSL to allow this syntax that looks like plain English.</p><p>Simplistic DSL syntax is enabled by a couple of features in Ruby:</p><ul><li>Omitting parentheses on method invocations:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ca8d663f611c48bfb17388000dc7ce9/href">https://medium.com/media/3ca8d663f611c48bfb17388000dc7ce9/href</a></iframe><ul><li>eval method evaluates the argument and <strong>runs the content as Ruby program text.</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9edf24b57cb33a213afd28b5ec65acd/href">https://medium.com/media/d9edf24b57cb33a213afd28b5ec65acd/href</a></iframe><ul><li>instance_eval will go one step further and <strong>change the context(</strong><strong>self)</strong> to the object that instance_evalis being called on.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00281196c90d7bf6baa24c66481bfd59/href">https://medium.com/media/00281196c90d7bf6baa24c66481bfd59/href</a></iframe><p>Now that we have covered the basic principles, let’s implement our own little JSON parser that iterates over a collection of objects that have similar structure and extracts a Ruby array with the selected properties. It can be useful when dealing with large JSON files. The below example is from Yahoo’s <em>woeid</em> locations collection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f503b38d07ff81d05bc6efc9ff16254/href">https://medium.com/media/5f503b38d07ff81d05bc6efc9ff16254/href</a></iframe><p>Our JSONParser class with on_path and extract methods to setup the parser:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41c40393eac19bb98254d74b34e1dabf/href">https://medium.com/media/41c40393eac19bb98254d74b34e1dabf/href</a></iframe><p>We can pass in a block with the relevant method calls while creating a new JSONParser:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/801dfe4c565b8a453ecb75f770dc16bb/href">https://medium.com/media/801dfe4c565b8a453ecb75f770dc16bb/href</a></iframe><p>We can use instance_eval to get rid of the need of calling methods on our parser object by changing our initialize method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb99c26d999381cd07d1f9195b89c345/href">https://medium.com/media/cb99c26d999381cd07d1f9195b89c345/href</a></iframe><p>With our new initialize and by omitting parentheses our parser is much more DSL-like now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0791a007864ff9d699913769d00ae55/href">https://medium.com/media/f0791a007864ff9d699913769d00ae55/href</a></iframe><p>DSLs are great when dealing with an isolated problem repeatedly. Now that we’ve developed one of our own, we know what is going on in the background when we come across one.</p><p>For more on Ruby and DSLs:</p><ul><li><a href="http://eloquentruby.com/">Russ Olsen’s Eloquent Ruby</a></li><li><a href="https://martinfowler.com/books/dsl.html">Martin Fowler’s Domain-Specific Languages</a></li><li><a href="http://designpatternsinruby.com/">Russ Olsen’s Design Patterns in Ruby</a></li><li><a href="https://www.oreilly.com/library/view/design-patterns-elements/0201633612/">Design Patterns by GoF</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcdcefb17cfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Comparative Guide to JavaScript Object Creation Patterns]]></title>
            <link>https://medium.com/launch-school/a-comparative-guide-to-javascript-object-creation-patterns-31c9c3cfede1?source=rss-88200c98110e------2</link>
            <guid isPermaLink="false">https://medium.com/p/31c9c3cfede1</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[launch-school]]></category>
            <dc:creator><![CDATA[Alican Sungur]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 21:08:22 GMT</pubDate>
            <atom:updated>2020-08-13T15:05:10.745Z</atom:updated>
            <content:encoded><![CDATA[<p>Comparison and principles of the four most common patterns</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8VC0VHdc_I-VSxIA" /><figcaption>Photo by <a href="https://unsplash.com/@christopher__burns?utm_source=medium&amp;utm_medium=referral">Christopher Burns</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you started learning programming with a traditional class-based language, JavaScript’s Object Oriented Programming might look confusing at first. You will find a lot of articles on different object creation patterns which might be a bit overwhelming. In this article, we will analyze 4 common object creation patterns. I will start with a brief review of some of the underlying concepts/features. Then, I will examine some code samples and discuss how each pattern works using some visual aid.</p><p>If you are a Launch School student and studying OOP JavaScript as part of JS225 or JS120, and preparing towards the assessment, this article would be a good read for you. The aim of this article is to build up how each object creation pattern implements <strong>prototypal inheritance</strong> in steps and solidify your mental model. Let’s start with some background.</p><h3><strong>Inheritance in JavaScript</strong></h3><p>The term <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)"><strong>inheritance</strong></a> in OOP, commonly refers to class-based languages where there is a sub-class/super-class relationship, being sub-classes inherit behavior and data from super-classes.</p><p>JavaScript does not have true-inheritance as we know it from class-based languages. Instead, it uses something called <strong>prototypal inheritance</strong>. When we create an object, say child from another object called parent , child references it&#39;s properties and methods to parent object&#39;s <strong>prototype</strong>. This way it can <strong>delegate</strong> an access request up in the prototype chain which is why we call this <strong>behavior delegation</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QA8RBMpy-YnVnRbS" /><figcaption>Photo by <a href="https://unsplash.com/@jjying?utm_source=medium&amp;utm_medium=referral">JJ Ying</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Class Properties vs. Function Properties</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nde3N4OdUhwsR8zJJXX1Xg.jpeg" /><figcaption>Properties of functions and objects | Key on top-right demonstrates object types</figcaption></figure><ul><li>In JavaScript, prototype property only exists in Functions. It is basically an object that Function returns when invoked as a constructor with the new keyword.</li><li>[[Prototype]] is a property that all objects contain. This property points to prototype object that the initial object created from.</li></ul><p>Let’s look at the above diagram to see what happens when we create an empty function vs an empty object.</p><p>On the left, we have the Sample function. When we create a function, it initially inherits from Function.prototype which is referenced to it&#39;s [[Prototype]] property. Functions also contain a prototype property that contains a prototype object. This object contains a property called constructor that refers back to the function. We will make use of constructor later.</p><p>On the right, we have our object Sample with [[Prototype]] property. The value that [[Prototype]] points to depends on how the object is created. If it is created <strong>using the object literal syntax</strong> it will reference to Object.prototype . If the object is created <strong>by a constructor function</strong>, it will be referencing to prototype property of that function.</p><h3>Creating Objects From Functions</h3><p>Lastly, let’s remember what happens when we invoke a constructor function with new keyword. Let&#39;s say we have a construction function ConstFunc and we have a line of code like this: let newObj = new ConstFunc(arg1, arg2);</p><ol><li>When invoked, constructor function ConstFunc creates a new object</li><li>this (execution context) assigned to this new object as part of the function call.</li><li>ConstFunc is executed in this context with passed in arguments.</li><li>If there is no explicit return statement, the value of this will be returned.</li></ol><p>The created object will have the below relationship with the constructor function</p><ul><li>newObj.constructor === [ Function: ConstFunc ]</li><li>ConstFunc.prototype === ConstFunc {}</li><li>newObj.constructor.prototype === ConstFunc {}</li></ul><p>Now we covered all the basics, the rest will be quite straightforward.</p><h3>Constructor Functions</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d54744302dc9904dfdaa32a459c951/href">https://medium.com/media/63d54744302dc9904dfdaa32a459c951/href</a></iframe><p>Previously, we’ve discussed how constructor functions work while we explained how the new keyword works. The key takeaway from this pattern is Album.prototype. It is the prototype object for constructor function&#39;s return value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5p5DWcLZ8LCBb5XBRDCM9A.jpeg" /><figcaption>“Inheritance” mechanism of constructor functions</figcaption></figure><p>When we created the new objects using the constructor function Album , all shared methods are copied into instances of Album.prototype . Therefore, although [[Prototype]] property of the new objects point to Album.prototype , they will still use their own copy of the methods.</p><h3>Factory Pattern</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5856c6d8bf4c041c68c506c6ff6b046/href">https://medium.com/media/c5856c6d8bf4c041c68c506c6ff6b046/href</a></iframe><p>Factory pattern makes use of a function that returns an object when invoked. Above example makes use of the object literal syntax for object creation, but other ways such as new Object() can be also used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-pHwvyYFDoute7nhow0Tw.jpeg" /><figcaption>“Inheritance” mechanism of factory functions</figcaption></figure><p>Factory pattern is computationally inefficient since all the methods will be copied to every single object that is returned. <strong>Unlike constructor functions</strong> it is not possible to track down how these objects are created, or how they are related to makeAlbum function. Also, it is not possible to update the &quot;shared&quot; behavior once the objects are returned by the factory function.</p><h3>Pseudo-Classical Pattern</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b842221f7c1dc54b3559c2da6de02d2/href">https://medium.com/media/6b842221f7c1dc54b3559c2da6de02d2/href</a></iframe><p>Pseudo-classical pattern combines constructor function and prototype pattern. This popular pattern resolves the problem of inefficiencies that have been discussed on the previous two patterns and introduces <strong>prototypal inheritance</strong>. Pseudo-classical pattern achieves this by creating a distinction between <strong>private properties</strong> and <strong>shared properties/methods.</strong> These are separated into a <strong>constructor function</strong> and the <strong>constructor function’s prototype</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAjGTm0uI073TDXpOQ5MAQ.jpeg" /><figcaption>Prototypal Inheritance mechanism of Pseudo-Classical Pattern</figcaption></figure><p>JavaScript class is introduced with ES6. Essentially, this does the same thing as the pseudo-classical model, it is just a <strong>syntactic sugar</strong>. It improves the organization of the code and provides a constructor method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08c8455fa64968fe7dd2232ef32d71cb/href">https://medium.com/media/08c8455fa64968fe7dd2232ef32d71cb/href</a></iframe><p>Lastly, The Pseudo classical pattern can be combined in the constructor function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5daf8e86cfa3ca14e692b694ca5b02d7/href">https://medium.com/media/5daf8e86cfa3ca14e692b694ca5b02d7/href</a></iframe><p>The if statement checks if the &quot;to be created&quot; object has already a property called readTag or type . Since inAbsentia is the first object that has been created by Album constructor, this will evaluate true and the shared behavior will be defined on the object&#39;s prototype. When we create other objects with the same constructor function, this block of code will be skipped by the if statement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mqB6c36iMwffam7n" /><figcaption>Photo by <a href="https://unsplash.com/@stgu1610?utm_source=medium&amp;utm_medium=referral">Steffen Gundermann</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>OLOO(Object Linking to Other Object)</h3><p>OLOO, is an object creation pattern based on <strong>creating new objects with </strong><strong>Object.create method using prototype objects</strong>. It is a relatively simpler pattern since it is not dealing with constructors and prototype properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62d0a98ce45c7618f18bcc15b4684574/href">https://medium.com/media/62d0a98ce45c7618f18bcc15b4684574/href</a></iframe><p>With OLOO, <strong>object creation and initialization occur at different times.</strong> The latter can be done by using an optional init method as shown above.</p><p>Because OLOO Pattern does not use constructors, examining inheritance with methods like Object.prototype.constructor will not work as expected and simply return Object.prototype (the top element in the prototypal inheritance hierarchy). Instead, isPrototypeOf and Object.getPrototypeOf could be used for such purpose. Also, we can not use instanceof because the right-hand operand has to be a function.</p><p>Above inAbsentia and unknowAlbum have different properties, but they share the same methods as Album.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PHg_72_tkczHdVYgt0XO_A.jpeg" /><figcaption>Prototypal Inheritance mechanism of OLOO Pattern</figcaption></figure><p>This approach provides <strong>behavior delegation rather than copying of all methods at object creation time</strong>. Therefore, when we add a new method check into prototype object and call this method on the <em>already created</em> instance inAbsentia , this method call will be delegated to its prototype.</p><p><strong>TL;DR</strong></p><p>There are a lot of good articles on <a href="https://john-dugan.com/object-oriented-javascript-pattern-comparison/">object creation patterns</a> in JavaScript. In this article, I’ve tried to focus on the underlying principles first.</p><ul><li>[[Prototype]] is a hidden property contained in all objects. It is referenced to initial object&#39;s prototype object.</li><li>prototype is a functions prototype object that it returns when invoked with new keyword.</li><li>When an object is created invoking a constructor function the returned object has a constructor property that points to constructor function.</li></ul><p>At the second part I’ve discussed and compared 4 common object creation patterns with code samples and diagrams. Some key takeaways:</p><ul><li><strong>Factory Pattern</strong> gathers object creation functionality in a single function, prevents repetition (<a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself#:~:text=From%20Wikipedia%2C%20the%20free%20encyclopedia,data%20normalization%20to%20avoid%20redundancy.)">more on DRY</a>. Each function invocation creates a new object. It is inefficient, hard to trace the sources of the objects. Objects have a copy of their own methods.</li><li><strong>Constructor Function,</strong> takes one step further from factory pattern by introducing a fake prototypal inheritance. Created object <strong>will still have their own copy of methods</strong>, but their source can be traced by using constructor property on the instances.</li><li><strong>Pseudo-Classical Pattern</strong> is a combination of constructor function and prototype pattern. It resolves the above inefficiencies by introducing <strong>prototypal inheritance.</strong> It achieves this by separating private properties and shared properties into constructor function and it’s prototype.</li><li><strong>OLOO(Object Linking to Other Object),</strong> is a simpler solution that uses a prototype object instead of a constructor function. It relies of creating new object using Object.create with prototype object passed in as argument.</li></ul><p>We now know all these patterns but which is “<strong>the best”</strong>? My answer would be <strong>It depends…</strong> The latter two are better practices when it comes to building your code organization. However, the former two are also important to understand the <strong>principals behind prototypal inheritance</strong> and can save you some time when dealing with smaller problems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31c9c3cfede1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/launch-school/a-comparative-guide-to-javascript-object-creation-patterns-31c9c3cfede1">A Comparative Guide to JavaScript Object Creation Patterns</a> was originally published in <a href="https://medium.com/launch-school">Launch School</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>