mazzi.github.io

PoC RoR React and CSV 07 / 08 / 2019

Has been a while without writing a technical post. Looking at startups I see often a webstack made out of Ruby on Rails (RoR) and React. With the facilities that RoR gives to create a REST API and the popularity of React, I understand the reasons.

To make a small PoC, I decided to import a random CSV to sqlite3 (why bother to use mysql/postgres for this example right?) so I can build a small backend with a service to find information easily.

Let’s start bottom up.

Model creation and importing the data

Download from this url the file 2019_domicilis_sexe.csv. It’s open data from Barcelona, identifiying “Homes of the city of Barcelona according to the sex of the people who live in them.” It’s just an example. Any other CSV file should be good as well, but you’ll need to change the mapping of the fields and the types.

How to import this data into sqlite3 using Rails, and seeds?

  1. Copy 2019_domicilis_sexe.csv into ./lib/seeds/ directory (if not exists create it)
  2. Modify ./db/seeds.rb and add the following code

     require 'csv'
    
     csv_text = File.read(Rails.root.join('lib', 'seeds', '2019_domicilis_sexe.csv'))
     csv = CSV.parse(csv_text, :headers => true, :encoding => 'ISO-8859-1')
     csv.each do |row|
         sd = SexDatum.new
         sd.year = row['Any']
         sd.district_code = row['Codi_districte']
         sd.district_name = row['Nom_districte']
         sd.neighbourhood_code = row['Codi_barri']
         sd.neighbourhood_name = row['Nom_barri']
         sd.sex = row['Sexe']
         sd.number = row['Nombre']
            
         sd.save
         puts "Entry saved"
     end
    
  3. Let’s create the model for this table using: rails g model SexData year:integer district_code district_name neighbourhood_code:integer neighbourhood_name sex number:integer By default Rails uses strings as type for db fields. Just be explicit on integers on this case.
  4. If the model was successfully created, you should see ./app/models/sex_datum.rb on your filesystem. A migration then, should be executed for the creation of the table: rake db:migrate.
  5. Now with the model, the csv data and the seeds, let’s import the data: rake db:seed
  6. To check that the model was created and the data imported, let’s use rails console: rails c
  7. Once there, let’s find records: SexDatum.all Check names, types and values. All set!

Writing the Controller and handling the routes

Let’s create the namespace for the routes, so we can handle versions in the future.

  1. Create the directory ./controllers/api/v1/
  2. And the file sex_datum_controller.rb in the same directory containing two methods: one to return all the records (just a test) and another one that will filter records by district_code (as an example)

     class Api::V1::SexDatumController < ApplicationController
         def index
             render json: SexDatum.all
         end
    
         def show
             datum = SexDatum.where district_code:params[:id]
             render json: datum
         end
     end
    
  3. Rewrite the contents (asumming that we have a project from scratch) of routes.rb so we can hit two urls http://localhost:3000/ and http://localhost:3000/api/v1/sex_datum/2. The number 2 is the district_code and is just an example.

     Rails.application.routes.draw do
         namespace :api do 
             namespace :v1 do 
                 resources :sex_datum, only: [:index, :show]
             end 
         end 
         root to: 'home#index'
     end
    

Writing the View in React.js

  1. An empty file should be created in ./app/views/home/index.html.erb. This file should act as a placeholder. The real content will be on ./app/javascript/components/App.jsx served by webpack. Remember to install the gem and configure the path on webpacker.yml (sorry, maybe a long topic for the same post) The tile App.jsx will have the following content:

     import React from 'react'
     import InputDistrictCode from './InputDistrictCode'
    
     const App = () => {
         return (
             <div>
                 Hello, I am a react component rendered via rails webpacker
                 <InputDistrictCode />
             </div>
         )
     }
     export default App
    
  2. Now defining InputDistrictCode.jsx

     import React, {Component} from 'react';
     import Result from './Result';
    
     class InputDistrictCode extends Component {
    
         state = {
             code : '',
             result : [],
         }
    
         handleClick = (event) => {
             event.preventDefault();
             fetch(`http://localhost:3000/api/v1/sex_datum/${this.state.code}`)
                 .then(response => response.json())
                 .then(data => this.setState( {result : data}))
         }
    
         handleChange = (event) => {
             const {name, value} = event.target
             this.setState({ [name] : value })
         }
    
         render() {
             return(
                 <div>
                     <input
                         name='code'
                         onChange={this.handleChange}>
                     </input>
                     <button
                         onClick={this.handleClick}>
                         Find it
                     </button>
                     <Result
                         data={this.state.result} />
                 </div>
             )
         }
     }
    
     export default InputDistrictCode;
    
  3. And the last component, Result.jsx

     import React from 'react'
    
     const Result = ({data}) => (
         <>
             {data.map( item => (
                 <div key={item.id}>
                 {item.district_name} - {item.id}
                 </div>))}
         </>
     )
    
     export default Result;
    

Run the rails server with rails s and the webpack sever ./bin/webpack-dev-server. Heading now to http://localhost:3000/ you should see something like this:

Simple form in React and RoR

Writing an integer in the input field and then hitting the button, some results from the database will be retrieved.

Hope it helps! If you need the code let me know in the comments.

Peter Drucker quotes 01 / 05 / 2019

Peter Ferdinand Drucker was an Austrian-born American management consultant, educator, and author, whose writings contributed to the philosophical and practical foundations of the modern business corporation.

Here 10 quotes to keep in mind regularly.

Doing the right thing is more important than doing the thing right.

If you want something new, you have to stop doing something old.

There is nothing quite so useless as doing with great efficiency something that should not be done at all.

What gets measured gets improved.

Results are gained by exploiting opportunities, not by solving problems.

So much of what we call management consists of making it difficult for people to work.

People who don’t take risks generally make about two big mistakes a year. People who do take risks generally make make about two big mistakes a year.

Meetings are by definition a concession to a deficient organization. For one either meets or one works. One cannot do both at the same time.

Long-range planning does not deal with the future decissions, but with the future of present decissions.

Management is doing things right. Leadership is doing the right things.

Twelve arguments to sneak in features 01 / 02 / 2019

When your product gets traction, you’ll nd yourself inundated with good ideas for features. These will come from your customers, your colleagues, and yourself. Because they’re good ideas, there will always be lots of reasons to say yes to them. Here’s 12 arguments that are commonly used to sneak features into a product:

  1. But the data looks good
  2. But it’ll only take a few minutes
  3. But this customer is about to quit
  4. But we can just make it optional
  5. But my cousin’s neighbour said…
  6. But we’ve nothing else planned
  7. But we’re supposed to be allowed to work on whatever we want
  8. But 713,000 people want it
  9. But our competitors already have it
  10. But if we don’t build it, someone else will
  11. But the boss really wants it
  12. But this could be “the one”

Extract from “Intercom on Product Management”.

An acid test for new features 01 / 02 / 2019

Here’s a simple set of Yes/No questions that you can quickly answer before you add another feature to your product roadmap.

  1. Does it fit your vision?
  2. Will it still matter in 5 years?
  3. Will everyone beneffit from it?
  4. Will it improve, complement or innovate on the existing workfow?
  5. Does it grow the business?
  6. Will it generate new meaningful engagement?
  7. If it succeeds, can we support and afford it?

Ben Horowitz's on Good and Bad Product Managers 13 / 12 / 2018

Good product managers know the market, the product, the product line and the competition extremely well and operate from a strong basis of knowledge and confidence. Is the CEO of the product. Takes full responsibility and measures themselves in terms of the success of the product. They are responsible for right product/right time and all that entails. A good product manager knows the context going in (the company, our revenue funding, competition, etc.), and they take responsibility for devising and executing a winning plan (no excuses).

Bad product managers have lots of excuses. Not enough funding, the engineering manager is an idiot, Microsoft has 11 times as many engineers working on it, I’m overworked, I don’t get enough direction. Barksdale doesn’t make these kinds of excuses and neither should the CEO of a product.

Good product managers don’t get all of their time sucked up by the various organizations that must work together to deliver right product right time. They don’t take all the product team minutes, they don’t project manage the various functions, they are not gophers for engineering. They are not part of the product team; they manage the product team. Engineering teams don’t consider Good Product Managers a “marketing resource.” Good product managers are the marketing counterpart of the engineering manager. They crisply define the target, the what (as opposed to the how) and manage the delivery of the what. Bad product managers feel best about themselves when they figure out how. Good product managers communicate crisply to engineering in writing as well as verbally. They don’t give direction informally but they gather information informally.

Good product managers create leveragable collateral, FAQs, presentations, white papers. Bad product managers complain that they spend all day answering questions for the sales force and are swamped. Good product managers anticipate the serious product flaws and build real solutions. Bad product managers put out fires all day. Good product managers take written positions on important issues (competitive silver bullets, tough architectural choices, tough product decisions, markets to attack or yield). Bad product managers voice their opinion verbally and lament that the “powers that be” won’t let it happen. Once bad product managers fail, they point out that they predicted they would fail.

Good product managers focus the team on revenue and customers. Bad product managers focus team on how many features Microsoft is building. Good product managers define good products that can be executed with a strong effort. Bad product managers define good products that can’t be executed or let engineering build whatever they want (i.e. solve the hardest problem).

Good product managers think in terms of delivering superior value to the market place during inbound planning and achieving market share and revenue goals during outbound. Bad product managers get very confused about the differences amongst delivering value, matching competitive features, pricing, and ubiquity. Good product managers decompose problems. Bad product managers combine all problems into one.

Good product managers think about the story they want written by the press. Bad product managers think about covering every feature and being really technically accurate with the press. Good product managers ask the press questions. Bad product managers answer any press question. Good product managers assume press and analyst people are really smart. Bad product managers assume that press and analysts are dumb because they don’t understand the difference between “push” and “simulated push.”

Good product managers err on the side of clarity vs. explaining the obvious. Bad product managers never explain the obvious. Good product managers define their job and their success. Bad product managers constantly want to be told what to do.

Good product managers send their status reports in on time every week, because they are disciplined. Bad product managers forget to send in their status reports on time, because they don’t value discipline.