Dynamic method names on JavaScript (es6) classes

I had something come up at work using a library which required classes with method names that matched exactly some magic strings being passed around. I’m not a huge fan of this pattern, but discovered a way to reduce the errors by having method names be dynamically generated – so renaming/refactoring the string wouldn’t have any unintended side effects

module.exports = {
 STATIC_METHOD: "myStaticMethodName",
 INSTANCE_METHOD: "myInstanceMethodName"
} // used throughout the codebase
const {STATIC_METHOD, INSTANCE_METHOD} = require("./methods")

class MyClass {
  static [STATIC_METHOD] () {
    // code
  }

  [INSTANCE_METHOD] () {
    // code
  }
}
const MyClass = require("./myClass")

MyClass.myStaticMethodName()

const mcInstance = new MyClass()
myInstance.myInstanceMethodName()

Monkey Patching Event Listeners

There was an interesting question in my local slack javascript community for a way to capture the performance of different events that happen on a page.  One way that was suggested was to hook into the native event listeners on the DOM. So without further introduction, here’s one way to monkey patch event listeners on the DOM.

Here’s a runable codepen example:

 

See the Pen monkey patched event listeners by Michael Jasper (@mdjasper) on CodePen.

Adding GraphQL to Ruby on Rails

GraphQL is a query language for APIs and a runtime for fulfilling those queries with your existing data. GraphQL provides a complete and understandable description of the data in your API, gives clients the power to ask for exactly what they need and nothing more, makes it easier to evolve APIs over time, and enables powerful developer tools. – http://graphql.org/

This guide will walk through installing and creating a GraphQL API in a Ruby on Rails application. It is a companion piece to the excellent Getting Started with Rails guide from RailsGuides. There are lots of resources that teach GraphQL-itself better than I can, so this guide just focuses on actually installing and using it in a Rails app.

Initial Schema

Let’s first verify that the schema of your app is what is expected for this guide. We will start off right were the RailsGuides guide leaves off. You should have   articles  and comments  tables with the following schema:

Install GraphQL Gem

The GraphQL gem is located at https://rubygems.org/gems/graphql. Find the latest version of the gem, and add it to your Gemfile:

Then run the graphql install command in your terminal:

This should modify the Gemfile to add a development tool GraphiQL, created necessary files in the application, and add GraphQL routes to the route file.

Let’s do a quick status check to see if everything is working so far. Start the rails server, and visit the GraphiQL route,  localhost:3000/graphiql.

You should see the GraphiQL user interface.

Adding Schema

Since GraphQL uses knowledge of relationships between types, we must first defined the types we will allow to be queries. In this case, Article and Comment. Add the following article and comment type files to  /graphql/types

These files define the schema and the relationship between Articles and Comments in a way that GraphQL can understand.

Adding Queries

Let’s add a article query to the api. Open  /graphql/types/query_type.rb  and add the following query below the  :testField query:

You should now be able to execute a query against GraphQL using the Graphiql tool

Here is the text of the query for your copy+paste convenience:

Adding a query to return all articles is just as simple. Add the following query type:

Using the endpoint

Up to this point we’ve used the GraphiQL tool to build and test our API. Let’s move to the actual graphql endpoint, located at /graphql

To test the endpoint you can use a tool like Postman to make requests to the app.

In postman, Let’s make a request to  localhost:3000/graphql (remember to set the header  Content-Type: application/json).

Set the request body to:

In my case, the response is:

Testing errors

Unless you’ve already configured your application differently, at this point it is likely that you will run into the error

Rails, by default, will protect your application from a particular type security risk called a “cross-site request forgery”

A side-effect of this is that you cannot POST to the graphql endpoint unless we temporarily disable this feature, by modifying your application_controller to read:

Please note that this is an important feature, and should only be disabled during developments, or if you want to create a completely public api endpoint.

Wrapping up & Next Steps

At this point we have installed GraphQL into our Rails app, created schemas for Articles and Comments, and written query types to return that data from our application, as well as testing the real API endpoint using postman.

From here you can take any path to consume the data, such as through a front-end application like a React or Angular application, or exposing the endpoint publicly!

Some next steps may be:

  1. investigate a front-end graphql client, like Apollo
  2. fix inefficient queries with batching
  3. look into implementing security

Dynamic super classes (extends) in ES6

tl;dr

Create a class factory which allows dynamic super classes to by applied to an es6 class (dynamic inheritance). This will be transparent to a consumer — meaning they will interact with it in the same way as the initial class.

Problem statement:

I was recently working on some code which extended an asynchronous module to add some additional functionality. The class initially looked like this:

However, testing a module like this is difficult for two reasons.

  1. The async nature of the behavior is challenging to test and mock
  2. The explicit super class Fetcher which is imported in the module is difficult to override without reaching down into the prototype and manually modifying methods during the test. Yuck!

Solution:

Wrap the extending (child) class declaration with a function, which accepts a parameter for its super class, and a default parameter value. Then the inner class can be declared using the SuperClass parameter. This will allow the child class to reference either its default parent, or the custom super class explicitly passed in.

The child class then extends or overwrites any methods from super that are required. Finally, a new’d up instance of the child class is returned with the remaining arguments passed to the class factory function.

For consistency of use, we can force the function to be called using new, making the abstraction completely transparent to any consumer.

Now we can call the extending class (with no SuperClass property) and it will have its default and expected behavior:

Or, with the SuperClass property to dynamically set its parent:

Working Example

 

See the Pen dynamic super class by Michael Jasper (@mdjasper) on CodePen.

Adding mp3 files to a Create React App app

If you’re looking for the steps to include static files, like an mp3, to a create-react-app project — and use es6 import statements to use them in a component, here are the steps. This process will involve “ejecting” from create-react-app, so think about the implications of that before proceeding.

1) Eject from the create-react-app by running npm run eject. The create-react-app documentation describes the eject command

If you aren’t satisfied with the build tool and configuration choices, you can eject at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except eject will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use eject. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

2) Include the files you want to use somewhere in the src folder. Probably with the component which will be consuming them.

3) We need to modify our dev and prod webpack configs to allow the files to be import-ed by through webpack and included in the build folder. Add an entry to the exclude list which will test for the file. The exclude list should look like this:

Add a loader to the list of loaders for the file type you want to use:

Do this for both the dev and prod webpack files in the config folder.

3) Within the component file, you can now import the file you with to use, specifying the relative path to the file

4) Then you can use the file within your component. For the example of a mp3 file, you can create a new Audio element in the constructor, and play or pause it using some event handler and function

 

Simple React Examples

I ❤️  react, and have spent a bit of time teaching react concepts to others through bootcamp trainings, and university courses.

Here are a few examples of concepts and code I’ve written for students that might be useful for you too:

Simple Composable Drawer Component

Illustrates simple props.children composition, as well as composition with stateful components.

  • Smart component
  • composition
  • children

TODO app

Stateful component composition with user generated data. Illustrates animating-out changes to state when todos are removed from state.

  • Smart components
  • component lifecycle
  • event binding

Search with debounced input

Search-preview of the Google Books api. Illustrates a very simple debounce implementation for network request performance.

  • fetch
  • composition
  • debounce
  • performance

Higher Order Components

Use a higher order component to generalize a common task of fetching and loading data into a component.

  • composition
  • fetch
  • promises

props.children composition

Very simple composition example.

  • containers
  • composition

 

Getting Started with Data Visualization in React

A primary goal of data visualization is to communicate information clearly and efficiently via statistical graphics, plots and information graphics. Numerical data may be encoded using dots, lines, or bars, to visually communicate a quantitative message.Effective visualization helps users analyze and reason about data and evidence. It makes complex data more accessible, understandable and usable.

-https://en.wikipedia.org/wiki/Data_visualization

TL;DR: Use data visualization too:

  1. Communicate information clearly
  2. Visual communicate a quantitative message
  3. Help users analyze and reason about data and evidence
  4. It makes complex data more usable

Good and Bad Examples

A pie chart that shows the 100 most active “tweeters” of a particular hashtag? Terrible visualization. Measuring it against our criteria, it doesn’t effectively communicate a message, or enable any type of reasoning about the data — other than to reason that 100 is far to many data points for a pie chart.

Almost never use a pie chart -everyones stats teacher

A tree chart with shows the worlds defense budgets? Great visualization. It is clear and understandable, and illustrates a message to the viewer.

A map of the 2012 Electoral College results by state? I believe this is an excellent visualization. It shows not only the states votes, but shows the weight each state has in the electoral college. It is accessible to the viewer.

A chart of the 100 most popular websites per month? At a quick glance, which is most popular? Is it the largest, or closest to the center? Which is the largest anyway? This is an ineffective visualization.

Technologies to visualize data on the web

There are three ways the data can be presented/visualized on the web

  1. Images: Visualization is designed in a tool like photoshop, illustrator, or tableu
  2. CSS: Css properties, such as width or height determine the shape and size of objects which can represent data points.
  3. Javascript: Using a javascript library that will create SVG or Canvas elements, and add interactive behavior to them

Javascript visualization libraries

There are many popular visualization and charting libraries. Three very popular and robust are:

D3

http://d3js.org

https://www.npmjs.com/package/react-vis

Vis

http://visjs.org/

https://www.npmjs.com/package/react-graph-vis

Highcharts

https://www.highcharts.com/

https://www.npmjs.com/package/react-highcharts

Building a data driven chart in React step-by-step

We’re going to use Facebook’s excellent Create-react-app starter kit, so first, let’s create a clean install of CRA:

Then install dependancies

Let’s use d3 with the React-vis wrapper. First install the react-vis package into our project

At this time, there is an unmet dependency problem with will prevent the app from compiling, so also install the peer dependency

Finally, run the project

Now the project is running, we can consume the react-vis package in our app. In the “App.js” file (the main component rendered by the app at this time), import the react-vis components and css.

We are now ready to use the components from the react-vis package in our App. Somewhere in your app insert a element:

We can now look at the page in our browser and see the chart rendered:

Creating an API for our chart to consume

 

 

Modern 100% height divs

In 2011 I published a popular article, 100% height Divs with 2 lines of code, which showed how to use JavaScript to get around the difficult layout problem of having two elements side-by-side both at 100% height of their container. In 2012, an update was published which showed a similar solution using jQuery. Both of these methods are now obsolete, and modern css solves the problem quite simply.

Enter flex-box.

Flex-box, now widely supported, allows complex layouts – like the 100% problem – to be solved simply and elegantly. A great post (CSS-Tricks has a great guide to flex-box (which I reference frequently))

Here is an example of a simple 2 column layout using flex-box:

See the Pen bpzQjo by Michael Jasper (@mdjasper) on CodePen.

And another example of a more complex layout using flex-box:

See the Pen XdOyay by Michael Jasper (@mdjasper) on CodePen.

And finally, an example of flex-box to build an entire page layout:

See the Pen Flexbox golden layout by Michael Jasper (@mdjasper) on CodePen.

 

ES6 Depth-first object (tree) search

A co-worker recently asked about searching for properties in a JavaScript object, where the properties could be located in unspecified locations within the object (not nested though). This was the job for a depth-first tree search! I don’t get to post about more traditional computer science topics very frequently, so I thought I’d share my little ES6 recursive search function:

Explanation (commented source)

Example

This code can be used like so: