teleren/devto huggingface dataset:
pass a block to parent Controller in Rails
Tags: rails
Published: 2020-02-10 21:51:55

## Overview
I have 3 classes. They are the STI structured classes.
( I believe this way is useful even if you don't use STI. The following explains is just an example of using block. )

```ruby
class Medium < ApplicationRecord; end
class Photo < Medium; end
class Video < Medium; end
```

And then, I've got 3 classes of the controllers.

```ruby
class MediaController < ApplicationController; end
class PhotosController < MediaController; end
class VideoController < MediaController; end
```

## The code could be like this.(but I don't like it.)
```ruby
class MediaController < ApplicationController; end

class PhotosController < MediaController
  def update
    @photo = Photo.find(photo_params[:id])
    if @photo.update(name: photo_params[:name])
      render json: @photo, status: :ok
    else
      render json: @photo.errors, status: :unprocessable_entity
    end
  end

  private
  def photo_params
    params.require(:photo).permit(:id, :name, :album_id, :file)
  end
end

class VideoController < MediaController
  # 😭 There should be ALMOST SAME code with PhotosController in here 😓
end

```


## We have the block and it's enabled in Controllers👍
So, We can write it, like this.
Thanks, Gods(Rails committers) It's Useful!!

```ruby
class MediaController < ApplicationController
  def update
    @medium, medium_params = yield
    if @medium.update(name: medium_params[:name])
      render json: @medium, status: :ok
    else
      render json: @medium.errors, status: :unprocessable_entity
    end
  end
end

class PhotosController < MediaController
  def update
    super do
      [Photo.find(photo_params[:id]), photo_params]
    end
  end

  private
  def photo_params
    params.require(:photo).permit(:id, :name, :album_id, :file)
  end
end

class VideoController < MediaController
  #  🎉 There should be only the code which is difference from PhotosController
end
```

## This idea is from ...
{% link https://dev.to/n350071/override-the-included-gem-method-by-using-hock-13ej %}
Git problems and solutions
Tags: git, gitflightrules
Published: 2020-02-10 21:38:03

---
title: Git problems and solutions
published: true
description: A great repository of different git problem and solutions
tags: git, git-flight-rules
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/94wpxiv0it37veueaxl8.jpg
---

Want to share a great repository of git problems and solutions for every situation in your dev life. Big credits to the author! Enjoy!

https://github.com/k88hudson/git-flight-rules
SignalR core python client (VI): Client to server streamming 3.X
Tags: signalrcore, python, client, signalr
Published: 2020-02-10 21:06:28

---
title: SignalR core python client (VI): Client to server streamming 3.X
published: true
description: Signalr core library now dealing with client to server stream
tags: signalrcore, python, client, signalr
series: SignalR core python client
cover_image: https://www.campusmvp.es/recursos/image.axd?picture=banner-asp-net-core-750x300.png
---
# Intro

Thistutorial is aligned with [microsoft docs](https://docs.microsoft.com/es-es/aspnet/core/signalr/streaming?view=aspnetcore-3.1) tutorial written in Javascript + C#  

## Server signalr

In your Hub class you only need to add the method for upload items

```c#
public async Task UploadStream(ChannelReader<string> stream)
    {
	    while (await stream.WaitToReadAsync())
	    {
		    while (stream.TryRead(out var item))
		    {
			    // do something with the stream item
			    Console.WriteLine(item);
		    }
	    }
    }
```
## Python client

I tried to make python client similar to Javascript client. With a similar syntax and behaiviour the librarie´s learning curve will be lower for people who has read the tutorials and worked with signalr in javascript previously.

#### Create hub connection

```python
from signalrcore.hub_connection_builder import HubConnectionBuilder
hub_connection = HubConnectionBuilder()\
    .with_url(server_url, options={"verify_ssl": False}) \
    .configure_logging(logging.DEBUG) \
    .with_automatic_reconnect({
            "type": "interval",
            "keep_alive_interval": 10,
            "intervals": [1, 3, 5, 6, 7, 87, 3]
        })\
    .build()
hub_connection.start()
```

#### Import and create subject

```python
from signalrcore.subject import Subject
subject = Subject()

```

#### Manage stream

```python
myCoolStreamItem = "some content"

# start Stream
hub_connection.send("UploadStream", subject)

# call next any time you need to upload a item
subject.next(myCoolStreamItem)

# stop stream
subject.complete()
```


## Links

[Github](https://github.com/mandrewcito/signalrcore)
[Pypi](https://pypi.org/project/signalrcore/)

Thank you for reading, and write any thought below :D
New Repo Trick for github
Tags: github, git
Published: 2020-02-10 20:58:26

I found this cleaver little trick and I thought that it could be useful to share.

That or you can show off some cool trivia to your friends and colleagues on how git-fluent you are.

```
repo.new
```
Put that bad boy in your browser URL bar and **BAM**. Ready to make a new repo.

```
Organization:   GitHub, Inc. (GITHU)
RegDate:        2012-11-15
Updated:        2017-04-19

OrgName:        GitHub, Inc.
OrgId:          GITHU
```

###### Above is some the output from a Whois for the paranoid.
The fact that I barely know how to use git has been biting me in the butt a lot lately 😭
Tags: git, watercooler
Published: 2020-02-10 20:37:42

Easily the weakest part of my dev game is git, which is probably the most universally important tool to know.

I've been painting myself into frustrating git corners lately and I think I need to expand the number of commands I truly understand.

Thank you for listing ❤️
Definition of Fatal, Error, Warn
Tags: logs, logging, errors, levels
Published: 2020-01-22 14:39:39

---
title: Definition of Fatal, Error, Warn
published: true
description: Log/error levels are not always clearly defined.
tags: logs, logging, errors, levels
---

### Problem

Log and error levels are not always clearly defined making developers unsure of which level to use.

### Solution

Define them explicitly. These are our definitions, you may have others.

|Level|Definition|Examples|
| ----|----|----|
| Fatal | An error that is so bad the service/system CANNOT perform any meaningful processing, and ideally should shut itself down (`Process.exit(1)`).| Misconfiguration of environment (wrong connection parameters etc.) |
| Error | An error that the system/service cannot recover from, but SHOULD NOT affect other processing. | Parsing errors, e.g. HTTP's "bad request".|
| Warn | An error that the system/service MAY recover from.| Retry loops, e.g. due to timeout.|
| Info | A non-error event in the system that is of interest to the business and/or operations. | Metrics, auditing, tracing etc. |
| Debug | A log point with high detail but of low value to normal business operation. | Used for understanding more about how the system is behaving. |

Edit: added info and debug. Flipped the order around.

### Feedback requested

If your definitions differ from ours I'm interested to hear about it. :)
Last Weeks' Top 5 Unseen Articles
Tags: top7, healthydebate, bestofdev
Published: 2020-02-10 20:26:28

Day after day, people like you write fantastic articles here on dev.to. But, due to the sheersize of this platform, not every article gets the attention it may deserve. So, this is my attempt to highlight the best articles published last week, which haven't got a lot of reactions (yet).

What makes them the Best? 🤔 Well, I chose them, so they covered a topic I liked.

Shameless plug: Consider following me on [twitter](https://twitter.com/kriswep).

###Carreer boosting 🚀

This one from [Raúl Sánchez](https://dev.to/rsanchezp) isn't really an article but rather a discussion. Nonetheless there are a lot of great insights in the comments there, check it out or add your own tips!
{% link https://dev.to/rsanchezp/advice-for-an-introvert-jr-dev-who-wants-to-give-a-talk-at-local-meetups-20mp %}

###Design 🎨

Clicking a button on an UI should do something, and it should give immediate feedback that something happened. [
Brian Neville-O'Neill](https://dev.to/bnevilleoneill) wrote a thorough explanation about designing a ripple effect for buttons. This article comes with a lot of explanations and an example. Worth the read.
{% link https://dev.to/bnevilleoneill/designing-a-ripple-effect-for-ui-feedback-3h4g %}

###GraphQL 📈

[Hasura](https://dev.to/hasurahq_staff), a company building an really impressive open source GraphQL engine introduced their Paid Pro Plan. Surely an important step for them on the way to be an lucrative company. (The main offering is still Open source and free). The article details the new offer, including some video demos.
{% link https://dev.to/hasurahq/introducing-hasura-pro-10j9 %}

###Wait is almost over ⏳

React Suspense is Reacts' long awaited new feature/paradigm. [Jake Lumetta](https://dev.to/jakelumetta) introduces us to the concepts and shows a lot of code examples while showing us how to build great user experiences with suspense.
{% link https://dev.to/jakelumetta/building-great-user-experience-with-react-suspense-3emk %}

###Motivation 👏

Sometimes you need a little push. [
James Wade](https://dev.to/jpswade) makes some points why it can be a good idea to be bold. What he mostly means be that is go and do the things you think should be done.
{% link https://dev.to/jpswade/be-bold-194e %}

That's my pick. There were a lot of great articles last week, so I'd be happy if you could chime in and share your Unseen Articles in the comments.
The Shame of Legacy Code
Tags: legacycode, technicaldebt, developer, onboarding
Published: 2020-02-10 20:22:20

---
title: The Shame of Legacy Code
published: true
description: Legacy code can be code that brings you shame but still be useful. How to deal with the shame of it?
tags: legacy code, technical debt, developer, onboarding
---

The **Shame of Legacy Code** is the feeling you get when you explain legacy code you wrote, or somebody else in your team wrote, to somebody who is not familiar with it.

I started learning about its devastating effects since last year. I've been helping new developers onboarding in the codebase my team handles and so I have been the point of contact for any question related to the design of the code.
Question after question, I found myself answering more that the design was not good or that some part of code was messy. I paid attention to the reaction of the new developers and I could see in their face the surprise mixed with disappointment or even disgust by the status of the code.

Their reaction hit me hard. Really hard. More than I expected and more than I wanted to admit to myself. Even if I didn't write the code I somehow felt guilty because I let this happen under my watch.

The result was a sense of despair and lack of motivation that made me on the verge to quit many times. Several nights I went home from work and cried out of despair because I felt I was a failed developer, a complete incompetent one.

A developer cannot sustain to do bad work every day for long time without it taking a toll on him/her. One will eventually forget what it means to do something properly.
I did not quit because that is the easy way and I don't believe you grow by going away from the tough situations. 

But then again, when is the time you are allowed to walk away?
Any unconventional tips after being laid off?
Tags: career
Published: 2020-02-10 19:45:22

---
title: Any unconventional tips after being laid off?
published: true
description: Was laid off a few days ago. Looking to rebound quickly. Any tips?
tags: career
---

Hey Dev,

I was laid off on Friday and now begin the hunt for a new job. I am looking for tips, specifically things I may not have thought about doing now that I am unemployed.

I have updated the resume, contacted a few recruiters that I am friendly with - and luckily for me I just updated my personal website two weekends ago :)

During this time of unemployment, I hope to take a few React courses. I haven't used React since 2018 so looking forward to learning all about Hooks and all that new shiny stuff.

Buy any advice helps. Look forward to reading your responses!
Which Package Manager should I choose?
Tags: productivity, typescript, node
Published: 2020-02-10 19:36:34

> [Original Post](https://blog.yggdrasilts.com/package-managers)


Package Manager is the backbone in every [TypeScript](https://www.typescriptlang.org/)/[NodeJS](https://nodejs.org/en/) project. There are several options to choose but, because of its popularity, [npm](https://www.npmjs.com/), [yarn](https://classic.yarnpkg.com/lang/en/) or [pnpm](https://pnpm.js.org/) are the candidates.

In my experience, I have been switching between [npm](https://www.npmjs.com/) and [yarn](https://classic.yarnpkg.com/lang/en/). The first choice was [npm](https://www.npmjs.com/). It was the first package manager in the [NodeJS](https://nodejs.org/en/) ecosystem and it was the obligatory step if you started to do things with [NodeJS](https://nodejs.org/en/).

Later, when [yarn](https://classic.yarnpkg.com/lang/en/) came to the playground, I changed to try it because I had read different articles with good impressions and I have to say it was mine as well.

After some time, and some [npm](https://www.npmjs.com/) improvements, I came back to [npm](https://www.npmjs.com/), not without testing [pnpm](https://pnpm.js.org/) briefly before but, with not a good taste. At the beginning of this year, the yarn team released the [version 2](https://yarnpkg.com/) but, unlike my previous try, this time I continued using [npm](https://www.npmjs.com/), I am happy with it and it is not needed any package manager change in my projects.

I have made my decision and I have chosen [npm](https://www.npmjs.com/) but not everyone is choosing [npm](https://www.npmjs.com/) and if you want to share your projects with others developers, I think it is a good practice try not to force anybody to use your package manager selection so, I started to search some way to create projects with an *agnostic* package manager and I came across with [npm-run-all](https://github.com/mysticatea/npm-run-all) library.

This library is able to run your *run-scripts* in different ways (serial, parallel) with no package manager indications, I mean, you can use [npm](https://www.npmjs.com/), [yarn](https://classic.yarnpkg.com/lang/en/) or your favorite package manager with no worries about the other scripts execution.

Our [Axiosfit](https://github.com/yggdrasilts/axiosfit) library is using it and I encourage you to try it as well.

If you want to see a more complex sample, also you can check our [TypeScript Full Stack project](https://github.com/yggdrasilts/typescript-full-stack-project).

Enjoy!! 🌳

> 'INFO' Although it is true that there are some other tools like [Gulp](https://gulpjs.com/) or [Grunt](https://gruntjs.com/) to customize your run tasks, I like to be independent and only use my package manager scripts.
A pattern a day keeps the reviewers away - [Day 0] - What are the design patterns?
Tags: beginners, tutorial, productivity, codequality
Published: 2020-02-10 19:27:56

Hey 👀✨

During the past few months, I've been working on a back-end project made with Ruby on Rails. Last year I was working as a Front-End developer, I've never had the opportunity to apply design patterns almost anywhere, until now. 

It's a pretty useful thing, that probably every developer that works with objects should at least know and practice, and this is why I'm here, to give you (and me!) a daily short post about the different design patterns that exist (or at least, those that are used the most), with an example, and an explanation.

Because doing **good code** will help you, your workmates, and those who will be in the future.

![Teamwork!](https://media.giphy.com/media/3oEdv4b54SMGgxfnTW/giphy.gif)
<figcaption>Do teamwork!</figcaption >

So, let's start with **the basics**, how can we start learning about something if we don't know what it is?

This will be a short one.

#What is a Design Pattern?

**Design patterns** will help you solve those most common issues that we find in software design. It's not a matter of copy and pastes to your code. **It is not actually "code"**, a design pattern **is just a general idea for solving problems that probably every programmer here has suffered**.

You will find many "blueprints" that many developers have polished to give general solutions to general problems. Those blueprints are called Design Patterns.

![Instructions](https://media.giphy.com/media/dNST4esNFxvWg/giphy.gif)
<figcaption>Just follow the instructions, and you'll be just fine!</figcaption>

A short example for this could be that, imagine that you need **exclusively one instance of an object**, let's say an exclusive role for a user, with global access inside your application, then, you would apply the [Singleton Pattern](https://sourcemaking.com/design_patterns/singleton), which **ensures** that a class has only one instance and provides a global point of access to that instance. 

By following the Singleton Pattern rules and examples, you would be able to create your own class following the best procedures to have a clean, easy to test, and flexible code.

And, as there are a lot of problems around here, there are also a lot of awesome solutions to get rid of them, and I'll do my best to show them to you shortly, on the next posts.

And that's it for today, told you it was a short one!

![Bye!](https://media.giphy.com/media/m9eG1qVjvN56H0MXt8/giphy.gif)

**I'll try** to keep posting every day one of the different patterns that are around. I can't promise I'll fulfil this task every day though!

Aching to know more about design patterns? I really recommend this book, [Dive into design patterns](https://sourcemaking.com/design-patterns-ebook). It is pretty complete and you'll find many patterns with real-life examples and solutions. Do not hesitate to visit it if you like it! 

Also, you can follow me so you are tuned to whenever I post something through my [Twitter](twitter.com/brownio_) account!
My first blog post on Dev. yay!
Tags: react
Published: 2020-02-10 19:27:42

I just wrote my first blog post - super excited to join this community.

Please read my [post here](https://dev.to/ng_real_ninja/react-crash-course-create-your-first-react-app-in-5-minutes-4238) and let me know how I can improve my writing.
parse json with python
Tags: python, beginners
Published: 2020-02-10 19:15:47

<a href="https://json.org/">JSON</a> (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write.

Usually web apps transfer JSON data back and forth. If you create your own web apps, they likely transfer JSON data (or XML). If you want to play around with the json format, here's a <a href="https://jsonformatter-online.com/">tool</a>

So how do you work with Python and JSON?

First, you should already know the <a href="https://pythonbasics.org">basics of Python</a> programming.

## Python and JSON

Python has a module named <a href="https://docs.python.org/3.5/library/json.html">json</a>. This lets you convert json data from the web to python objects and vice versa.

Consider this example in the Python interpreter:

```python
>>> import json
>>> # json data
... 
>>> x = '{ "name":"Alicia", "age":30, "city":"Toronto"}'
>>> # prase json data
... 
>>> obj = json.loads(x)
>>> print(obj["name"]
... )
Alicia
>>> print(obj["city"])
Toronto
>>> 
```

It loads the json module, defines raw json data. Then converts the json data to a python object.

```python
>>> obj = json.loads(x)
```

And then you can use it as Python <a href="https://pythonbasics.org/class/">object</a>

```python
>>> print(obj["name"])
>>> print(obj["city"])
```

You can load JSON data <a href="https://pythonbasics.org/json/">from a url</a> or <a href="https://pythonbasics.org/read-json-file/">from a file</a>.

## Parse JSON

You've seen this above in the Python <a href="https://pythonprogramminglanguage.com/repl/">REPL</a>, but for clarity lets put it in a code file. In code, to load json data and convert it to a Python object, you can do this:

```python
import json

# json data                                                                     
data = '{ "name":"Alicia", "age":30, "city":"Toronto"}'

# parse json data                                                               
obj = json.loads(data)

# python object                                                                 
print(obj["name"])
print(obj["city"])
```

Save it as example.py and run it, you'll see it has been converted to a Python object. You can also <a href="https://pythonspot.com/json-encoding-and-decoding-with-python/">decode a Python object to JSON</a> amongst other things.
Cloudinary
Tags: webdev, javascript, beginners, podcast
Published: 2020-02-10 18:55:27


Original: https://codingcat.dev/podcast/0-8-cloudinary-with-tessa-mero

{% youtube https://www.youtube.com/watch?v=yv4zq614xJs %}

## Get to know Tessa

So you went to school in Washington correct?

It seems like you have always been involved with helping people around technology whether teaching or evangelizing for an organization, what started that for you?

You travel a lot, is it mostly for fun or the job?

## Cloudinary Questions

How did you get started at Cloudinary?

What is it like being a developer advocate for Cloudinary?

How big is the staff that keeps the SDKs up to date?

You recently took over the MDE (Media Developer Experts) program, was this a big shift for you?

I feel like Cloudinary is very unique in the industry, do you know of any direct competitors?

ImageKit...

## Random

We met at Refactor.Tech and you took me to my first Korean BBQ, it seems like you have been ordering that stuff your whole life. So what is your favorite Korean BBQ dish?
CSS3 Creative Resume
Tags: codepen
Published: 2020-02-10 18:54:17

<p>I thought this would be a perfect project to use LESS mixins in.
Designed by: Pixeden: <a href="http://www.pixeden.com/resumes-templates/creative-resume-template-vol-1" target="_blank">http://www.pixeden.com/resumes-templates/creative-resume-template-vol-1</a>
Librarian Image is from Dribbble: <a href="http://dribbble.com/shots/271458-Librarian" target="_blank">http://dribbble.com/shots/271458-Librarian</a> 
by talented "Artua"</p>

{% codepen https://codepen.io/SaraSoueidan/pen/pdEec %}