teleren/devto huggingface dataset:
Automated tests prevent you from adding regressions
Published: 2024-02-09 22:41:01

---
title: Automated tests prevent you from adding regressions
published: true
date: 2024-02-02 00:00:00 UTC
tags: 
canonical_url: https://www.oliverdavies.uk/archive/2024/02/02/automated-tests-prevent-you-from-adding-regressions
---

Continuing from [my last few emails](https://www.oliverdavies.uk/archive/2024/01/30/tdd-doesnt-mean-you-know-everything-upfront), as well as adding the new use case more easily and quicker, having automated tests also saved me from adding a regression into the code I was changing.

I'd written a condition in the query to ensure only results that started with the search term.

Initially, I removed it, but then the tests failed.

This reminded me why I'd written the condition that way, and I was able to re-add my fix differently.

Without the tests, I'd likely have removed it and introduced a regression.

Whilst fixing a bug, I'd have introduced a different bug.

My tests saved me from doing that and I was able to rectify it quickly before pushing to CI or the staging environment.

 P.S. Are you still using Drupal 7 and don’t know what’s involved to upgrade to Drupal 10? [Book a Drupal 7 upgrade consultation call](https://www.oliverdavies.uk/call) or [an upgrade roadmap](https://www.oliverdavies.uk/drupal-upgrade).
Sitecore Search SDK - Breaking Change
Tags: sitecore, sitecoresearch
Published: 2024-02-27 21:44:09

---
title: Sitecore Search SDK - Breaking Change
published: true
date: 2024-02-02 00:00:00 UTC
tags: sitecore, sitecoresearch
canonical_url: https://robearlam.com/blog/sitecore-search-sdk-breaking-change
---

## Updating packages in Sitecore’s Developer Portal

Recently my colleague [Mark van Aalst](https://twitter.com/markvanaalst) was updating the package versions for the [Sitecore Developer Portal](https://developers.sitecore.com/). This also included updating the version of the Sitecore Search React SDK from `v2.0.0` to `v2.2.2`, among other packages that were updated at the same time. Once this had been deployed, we got reports that faceting was no longer working on the search results page. We quickly rolled back and started to look into what had happened.

## Breaking changes in the Faceting UI component

I reached out to the team that owns the SDK and apparently there was a breaking change introduced in a previous version and we needed to update how we were leveraging the UI components being used to render the Search Results page.

Previously we were wrapping out Facets in the `AccordionFacets.Root` component, like so

```
<AccordionFacets.Root defaultFacetTypesExpandedList={facets.map((x) => x.name)} onFacetValueClick={onFacetClick}>
	….
</AccordionFacets.Root>

```

However, this approach is no longer valid, we should now be using ` SearchResultsAccordionFacets` component instead. As follows:

```
<SearchResultsAccordionFacets defaultFacetTypesExpandedList={facets.map((x) => x.name)} onFacetValueClick={onFacetClick}>
	…
</SearchResultsAccordionFacets>

```

This was a fairly straightforward change, which meant we could bump the Developer Portal up to be running on the latest version of the Search SDK 🎉.

To see the complete set of changes we had to make for the Developer Portal, you can view the PR that was opened for this fix [here](https://github.com/Sitecore/developer-portal/pull/641).
Next.js Codebase Analysis <> create-next-app <> index.ts explained - Part 1.11
Tags: opensource, webdev, javascript, nextjs
Published: 2024-02-01 23:31:26

In the previous article, I wrote about project.example option. In this article, let’s look at more code from [index.ts](https://github.com/vercel/next.js/blob/canary/packages/create-next-app/index.ts)

```
/**
   * Verify the project dir is empty or doesn't exist
   */
  const root = path.resolve(resolvedProjectPath)
  const appName = path.basename(root)
  const folderExists = fs.existsSync(root)

  if (folderExists && !isFolderEmpty(root, appName)) {
    process.exit(1)
  }
```
Looking at the above code, the comment already was there. I did not add it. It just checks if the project directory and does not exist, otherwise processs exits. 

I am surprised there is no console.log before process.exit.

I logged the root, appName, folderExists and built the project and ran the command `npx create-my-app` and the following were found.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eebjqb0g15pik8mnn8dy.jpeg)

Looks like these will be logged after the first prompt to provide your project name.

## Experiment:

Let’s create a project with name my-app and then run the npx create-my-app again to see what will be logged.

Here are the results below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0t1klvoa2gvbbir37mfi.jpeg)

Wait a minute? where did this log come from?

Well, it is from isFolderEmpty. How I found it? searched with the words “The directory”

## Conclusion:

As we are progressing in understanding how create-next-app is written, this article explains another safe guarding technique against providing an existing folder or project name. 

I shall write more about isFolderEmpty in the next article. I try not to overdo these analysis, my goal is to get better at programming everyday by reading some unknown code from opensource and take notes so I could apply these later in the future.

I am building a platform that explains best practices used in open source by elite programmers. [Join the waitlist](https://docs.google.com/forms/d/e/1FAIpQLSe2JCZAaIB5oXzNHLTrYJR4LMZ5SEwrGPgmG5DeFWdDhu8-Gw/viewform) and I will send you the link to the tutorials once they are ready.

If you have any questions, feel free to reach out to me at ramu.narasinga@gmail.com
How Do We Structure Our Admin Pages in WordPress
Tags: wordpress, webdev, react, plugindevelopment
Published: 2024-02-01 23:26:07

Over the years, I've built lots of plugins, and every time, I had to code the structure of the administration pages from the WordPress dashboard.

Most of the time, the plugins were _'client plugins'_, meaning I was _hired_ to build them based on a brief.

In that case, I didn't really have the freedom to design them how I see fit.

But since I started publishing my own plugins through [Tadamus](https://tadamus.com) **I'm finally free to design and structure the pages as I see fit**. It all started with [WP Fusion Slack](https://tadamus.com/products/wp-fusion-slack).

_And here comes the problem that I want to discuss here_. How do I prevent the repetitive task of implementing the same design structure for all the pages?

## First steps

The thought that came to mind was to use a front-end framework or library like [React](https://react.dev/) or [Svelte](https://svelte.dev/).

And since the block editor is based on React, I went for React. Although, my geek spirit still thinks I should have used Svelte 😅.

At some point, I'll write a follow-up article on how I configured React, Babel, and Webpack to be able to create and render pages in the dashboard.

## Introducing the WP UI

Now, after choosing React, I had to refactor the components I created for the first admin page into a small library, which eventually got turned into an NPM package called [WP UI](https://www.npmjs.com/package/@tadamus/wpui).

It can also be found in the [Github repo](https://github.com/tadamuscom/wpui).

In it, I added everything I used on the first page, and since then, I have kept adding components that I thought I'd be using going forward.

I did my best to keep the components as extendable as possible, so please feel free to check them out and let me know if you have any suggestions.

## Suggestions

Currently, the package is in an initial phase. So, I'm open to any kind of feedback from you guys. So please let me know in the comments section or [our contact form](https://tadamus.com/contact). 

Also, if any of you guys think it would help you if I document the process of creating this library, please let me know. 🙂
Day 907 : First of the Month
Tags: hiphop, code, coding, lifelongdev
Published: 2024-02-01 23:19:14

_liner notes_:
- Professional : Had a couple of meetings to start off the day. Responded to some pretty deep community questions. Had to do some research. haha When I reply to questions, ask follow up questions so I can make sure I understand. Then I go and find links that I can post as a reference for the person so they can not only see my reply, but know where they can go for more info just in case something similar happens. Had a few like that. I did get a bunch done on a demo for an upcoming conference. Basically, I'm piecing together other applications I made. haha

- Personal : Last night, I'm 99% sold on a piece of land I've been looking at. I even found a video on YouTube of a person walking and driving around the town. They actually drove right by the lot, haha. Found another video about how the town is investing in itself for the future. I sent an email to the realtor. Not sure if they responded yet. I went through Bandcamp and selected the tracks that I'll pick up and post about on Friday and put them in a document. I'm waiting till then because on the first Friday of the month, artists make more money off each sale. I did a quick test to see if something would work for my current side project and it worked! I thought I solved another issue I had, but one app took over the microphone from another app I was using. I was soooo close! haha Pretty satisfied with my output and ended the night watching "Rurouni Kenshin".

![A photo of pink, orange, and purple clouds over a mountain range. The clouds are backlit by the sun, which is setting behind the mountains. In the foreground, there is a dark mountain peak. The sky is clear and there are no visible stars. The location is Above Žalý, Czechia](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bhhk911k76qos6uxjr48.jpg)

Going to finish up the Bandcamp posts for tomorrow by getting the social media accounts of the artists I found. I want to put together the radio show playlist for Saturday. Going to start taking the layouts I made for my side project's admin section a reality. It's the 1st of the month so time to pay my bills. End the night watching "Rurouni Kenshin". Going to eat dinner and get started.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 4j_cOsgRY7w %}
El Arte del Networking en Kubernetes: Conexiones que Importan
Published: 2024-02-01 23:06:09

¡Saludos, navegantes del código! Hoy nos sumergimos en el vital mundo del networking en Kubernetes. No te preocupes, lo mantendremos simple y directo.

En Kubernetes, los contenedores dentro de un pod pueden comunicarse entre sí sin problemas, pero ¿qué pasa cuando queremos que se comuniquen con el mundo exterior o con otros pods? Aquí es donde el networking juega un papel crucial.

**Services:**  Los servicios en Kubernetes son como puentes que conectan tus pods con el mundo exterior. Funcionan como un punto fijo de acceso a un conjunto de pods, asegurando que tus aplicaciones sean accesibles y estables.

**Ingress:** Mientras que un Service expone tus pods a la red interna del cluster, un Ingress los expone a la red externa. Es como la puerta principal de tu casa que da a la calle.

**Ejemplo Sencillo:** Imagina que tu aplicación es una fiesta con varios invitados (pods). El "Service" es como un teléfono que permite a otros invitados (otros servicios) llamar a tu fiesta. El "Ingress" es como la dirección de tu casa, permitiendo que gente de fuera (usuarios de internet) se unan a la fiesta.

Dominar estos conceptos te ayudará a asegurar que tus aplicaciones en Kubernetes no solo funcionen bien internamente, sino que también sean accesibles y eficientes para el mundo exterior.

En nuestro próximo encuentro, nos adentraremos en el emocionante mundo de Kubefirst. ¡Hasta entonces!
Magia de Datos: Manejando Volumes y Datos Persistentes en Kubernetes
Published: 2024-02-01 23:03:43

¡Hola, amigos de los datos! Hoy toca hablar de un tema esencial en Kubernetes: cómo manejar volumes y datos persistentes. Aunque suene a hechizo complicado, ¡verás que es más sencillo de lo que parece!

En el mundo de Kubernetes, **los contenedores son efímeros**, lo que significa que cuando desaparecen, todo dentro de ellos se esfuma. Pero, ¿qué pasa con los datos que necesitamos conservar? Ahí entran en juego los volumes.

**Volumes en Kubernetes:** Piensa en los volumes como discos duros externos que puedes conectar a tus contenedores. Aunque el contenedor se vaya, el volume permanece, guardando tus datos seguros.

**PersistentVolume (PV) y PersistentVolumeClaim (PVC)**: Kubernetes usa estos dos conceptos para manejar el almacenamiento de datos a largo plazo. El PV es como un estacionamiento de discos duros disponibles, y el PVC sería tu ticket para reservar uno de esos espacios.

**Ejemplo Práctico:** Imagina que tienes una aplicación que almacena imágenes. Al usar un PVC, aseguras que las imágenes se guarden en un PV, así que si el contenedor de tu aplicación se reinicia, tus imágenes siguen estando allí, intactas y seguras.

Dominar el manejo de volumes y datos persistentes es clave para asegurar que tu aplicación en Kubernetes sea robusta y confiable.

En el próximo post, nos adentraremos en el fascinante mundo del networking en Kubernetes. ¡Prepárate para conectar todos los puntos!
Kubernetes: Trucos y Consejos para Desarrolladores ¡A Jugar!
Published: 2024-02-01 23:01:17

¡Hola de nuevo, amigos del código! Hoy vamos a zambullirnos en algunos trucos y consejos prácticos para trabajar con Kubernetes. Si eres desarrollador, te prometo que esto te va a encantar.

**Kubernetes puede parecer un laberinto al principi**o, pero una vez que conoces los atajos, todo se vuelve mucho más sencillo. Aquí te van unos consejitos para navegar en este fascinante mundo:

**k3d, Minikube o Kind para Desarrollo Local:** Antes de lanzarte al mar abierto, ¿qué tal practicar en una piscina? Minikube y Kind te permiten tener tu propio Kubernetes local para experimentar sin miedo a romper nada.

**YAMLs Son Tus Amigos:** Sí, esos archivos YAML pueden ser un poco intimidantes, pero son la clave para comunicarte con Kubernetes. Piénsalos como recetas de cocina que le dicen a Kubernetes cómo quieres que se comporten tus aplicaciones.

**Uso de Namespaces para Organizar:** Los namespaces son como tener diferentes cajones en tu armario, ayudándote a mantener tus aplicaciones y recursos ordenados y separados.

**Helm para Gestionar Paquetes:** Imagina que Helm es como tu tienda de aplicaciones favorita, pero para Kubernetes. Te ayuda a instalar y manejar aplicaciones en Kubernetes con mucha facilidad.

Recuerda, la práctica hace al maestro. Experimenta con estos consejos y verás cómo Kubernetes se convierte en tu parque de juegos.

En nuestro próximo encuentro, exploraremos cómo manejar datos persistentes y volumes en Kubernetes. ¡Va a ser genial, así que no te lo pierdas!
GitOps: Dando Ritmo a Nuestro CI/CD
Published: 2024-02-01 22:59:59

Hoy vamos a sumergirnos en el mundo de GitOps, un concepto que está poniendo patas arriba el tradicional CI/CD.

Imagina que Git, nuestro buen amigo para el control de versiones, se pone un sombrero de mago y transforma la forma en que desplegamos nuestras aplicaciones. Eso es, en esencia, GitOps. Utiliza Git como el centro de control para manejar tanto la infraestructura como las aplicaciones. Piensa en GitOps como el director de orquesta de tu proceso de desarrollo, asegurando que cada instrumento (código, configuración, infraestructura) esté en perfecta armonía.

¿Y por qué nos encanta GitOps? Porque hace que todo sea más sencillo y transparente. Un 'push' a Git, y voilà, tus cambios están listos para ser desplegados automáticamente. Es como tener un asistente personal que se asegura de que todo en producción sea exactamente como lo tienes en tu repositorio.

Por ejemplo, imagina que estás trabajando en una aplicación web. Haces un cambio en el código y lo subes a Git. Con GitOps, este simple acto desencadena automáticamente una serie de eventos que terminan con tu cambio vivo y en directo en el servidor de producción. ¡Magia pura!

En los próximos posts, desglosaremos cómo podemos hacer que esta magia suceda con la ayuda de herramientas como Kubefirst.

¡Manténganse sintonizados para más trucos de GitOps!
¡Embarcándonos en la Aventura de Kubernetes!
Published: 2024-02-01 22:50:40

¡Bienvenidos, aventureros del código! Hoy comenzamos un viaje apasionante por el mundo de Kubernetes, esa maravillosa herramienta que está revolucionando la forma en que desplegamos y gestionamos aplicaciones.

Kubernetes, o como a muchos les gusta llamarlo, K8s, no es solo una tendencia pasajera en el mundo de la tecnología; es un gigante que está definiendo el futuro del desarrollo de software. Imagina tener un ejército de robots trabajando para ti, asegurándose de que tus aplicaciones estén siempre disponibles, escalables y eficientes. Eso es, en esencia, lo que Kubernetes hace.

Pero, ¿por qué es tan crucial para nosotros, los desarrolladores? Bueno, K8s nos libera de las pesadas cargas de la gestión de infraestructura, permitiéndonos centrarnos en lo que mejor sabemos hacer: ¡crear aplicaciones asombrosas!

En esta serie de posts, no solo descubriremos los secretos de Kubernetes sino que también veremos cómo, con la ayuda de GitOps y Kubefirst, podemos hacer que nuestros despliegues sean tan fluidos como el agua de un río montañoso.

Así que, ajusta tu cinturón, prepárate para despegar y acompáñame en este emocionante viaje. En nuestro próximo post, nos sumergiremos en el vibrante mundo de GitOps. ¡No querrás perdértelo!

¡Hasta la próxima, intrépidos desarrolladores!
Kubernetes para devs
Tags: kubernetes, beginners
Published: 2024-02-01 22:49:35

Creo que hay una especie de muro entre las cosas de infraestructura y el desarrollo, y una de ellas es el mundo de Kubernetes (k8s para los perezosos 😁).

El objetivo es poder entenderlo y desplegar una aplicación por nuestra cuenta usando esta tecnología, entendiendo mejor a esos seres de luz que son los SSR, magos de la infra 🧙‍♂️!

Aquí nuestro plan:

1. **¡Embarcándonos en la Aventura de Kubernetes!**

2. **GitOps**: Dando Ritmo a Nuestro CI/CD

3. **Kubernetes**: Trucos y Consejos para Desarrolladores ¡A Jugar!

4. **Magia de Datos**: Manejando Volumes y Datos Persistentes en Kubernetes

5. **El Arte del Networking en Kubernetes**: Conexiones que Importan

6. **Kubefirst**: Tu Primer Paso hacia la Maestría en GitOps

7. **Dominando GitOps con Kubefirst**: ¡Conviértete en un Héroe de Despliegues!

8. **Historias de Éxito**: Kubernetes y GitOps en el Mundo Real
9. **Consejos Pro de Kubernetes y GitOps**: Sé un Ninja del Despliegue

10. **¡Hasta el Infinito y Más Allá con Kubernetes y GitOps!**
Loading.... Suspense
Tags: nextjs, webdev, javascript, react
Published: 2024-02-01 22:24:27

If you use React, you may have heard of 'Suspense' or even used it before. What exactly is it used for, though?

An element to a lot of popular dynamic web applications like Instagram, X - formerly Twitter, Facebook, and etc. is that while a component to the app is loading there is typically a skeleton UI that will render in its place.
![Skeleton UI preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5ctclq1d7nse2gvyqeb.jpg)
One of the main benefits to using React is the ability to build with components. Especially with a dynamic web app, a component fetching some data can slow down a chunk of the web app. React created Suspense boundaries for these components, in order to create a fallback UI for the web app to display until all of the nodes have finished rendering for the dynamic element. While the dynamic elements are fetching data, a loading UI will be shown alongside the static UI on the web app. This also helps with keeping navigation interruptible, meaning one does not need to wait for the content of the route to fully load before navigating to another route.

![React code for a Suspense boundary](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oc19noxxevfsjio5labg.png)

Next.js v14 introduces a new way to implement this same Suspense, with partial pre rendering. For the dynamic web applications, the static components of will be served rapidly and the asynchronous content is served in parallel as it is fetched. The Next team believes that this method will be the future default rendering model of web applications. (You can check it out on chapter 10 of the [learn Next.js 14](https://nextjs.org/learn) course)

#### It helped me with Next Meal

I found out about Suspense while creating Next Meal, as the performance of my application was seemingly degraded due to the dynamic nature. I used Suspense boundaries as a solution to implement loading UI to the dynamic elements of the dashboard - this way users know that the screen is loading, not frozen. 

I even got a little creative with it, since I know that some users don't have blazing internet speeds and might be waiting for the data fetches. I created an array of dad jokes (all food centric) which get selected at random on each instance of a loading element. 

![Dad joke loading screen from Next Meal](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8jj0pxl30e2jpowh1ogr.png)

#### Check out my GitHub:
https://github.com/bealecs

#### Check out Next Meal:
https://next-meal-cookbook.vercel.app

#### Resources for post:
[React Docs](https://react.dev/reference/react/Suspense)
[Next.js learn 14](https://nextjs.org/learn)
Flutter - Uma introdução ao Gerenciamento de Estado
Tags: beginners, programming, flutter, frontend
Published: 2024-02-01 21:40:55

Olá pessoal, tudo certo? Neste artigo, compartilharei meu ponto de vista sobre o gerenciamento de estado no Flutter, explorando técnicas essenciais para controlar e manter o estado de uma tela do nosso aplicativo.

O gerenciamento de estado no Flutter refere-se às técnicas empregadas no front-end para controlar e manter o estado de uma tela do aplicativo. Isso inclui a representação visual de dados, como uma lista de ToDos em um estado de sucesso ou um alerta vermelho indicando um estado de erro.

Para fazer esse gerenciamento do estado o Flutter fornece algumas ferramentas nativas: ChangeNotifier, ValueNotifier e setState. Além disso, existem pacotes populares como BLoC, MobX, GetX e Asp, cada um com suas implementações específicas.

Princípios do Gerenciamento de Estado:

---

## Representação do estado
**Como o estado é representado?**

No caso do BLoC, por exemplo, o estado é representado por classes que contêm propriedades utilizadas pela visualização, geralmente denominadas estados, como SuccessState e LoadingState.

## Armazenamento do estado
**Onde o estado é armazenado?**

Na maioria dos pacotes, o estado é mantido dentro da própria classe de gerenciamento, com exceção do setState, que armazena o estado no próprio widget.

## Propagação do estado
**Como o estado se propaga na aplicação?**

Usando o ChangeNotifier como exemplo, a propagação do estado ocorre por padrão de observação. O estado é armazenado dentro da própria classe ChangeNotifier, e os ouvintes são notificados por meio do método notifyListeners(), que alerta todos os widgets que estão ouvindo essa instância do ChangeNotifier sobre as atualizações.

---

Esses princípios fundamentais podem ser aplicados a qualquer ferramenta de gerenciamento de estado. Compreendendo-os, você estará apto a utilizar eficientemente outras ferramentas que possam surgir no futuro.

Em resumo, o gerenciamento de estado é crucial para criar aplicativos Flutter eficientes e responsivos. Ao entender os princípios fundamentais e as ferramentas disponíveis, você estará preparado para enfrentar os desafios que surgem ao lidar com estados em suas aplicações.

No meu próximo artigo pretendo trazer o conteúdo de forma prática, quando estiver disponível anexarei o link no post.

Espero ter te ajudado. Sinta-se à vontade para deixar seu comentário, dúvida ou crítica abaixo.