munnkey
munnkey
munnkey
21 posts
Don't wanna be here? Send us removal request.
munnkey · 7 years ago
Text
Coding Podcasts to follow
Here are a few podcasts that I regularly follow to keep up with what is going on at the software development arena:
https://syntax.fm/ - Syntax Web Development Podcast
https://reactpodcast.simplecast.fm/ - React Podcast
http://5by5.tv/rubyonrails - Ruby on Rails Podcast
https://itunes.apple.com/us/podcast/codeview/id1380293751?mt=2 - Codeview Podcast
http://codingafterwork.com/ - Coding after Work Podcast
https://www.codingblocks.net/ - Coding Blocks.net Podcast
0 notes
munnkey · 7 years ago
Text
Code Splitting with react-loadable
Fundamentally Single Page applications are compiled in one file to be parsed by web browser. As the size of the app increases with new functionallity and also 3rd party libraries, this file can become a fat bunch of code to be transfered before the page loads. That will be a problem with user experience after a point. React-loadable package helps you to split the code into multiple downloadable package.
react-loadable gives you Loadable() HOC (higher order component) which raps your components and gives you the ability to split these components from the initial code transfer needed before your SPA launches. Loadable wrapped components are used just like your regular components. The only difference is that these components are actively loaded through network when they are called. You can assign a loading state to a loadable component so user experience will be smooth
const LoadableComponent = Loadable({  loader: () => import(‘./Component’),  loading: () => <div>Loading...</div>, });
When LoadableComponent is called, it will be imported dynamically. It is more logical to split large application by routes and not by small components.
0 notes
munnkey · 7 years ago
Text
Explicit and Implicit Global Scoping in node.js and browser js
Lets look at the scoping differences at node.js. first lets try our code in browser console.
var _user = { admin: false } user = { admin: false }
console.log(_user, window._user) console.log(user, window.user)
According to this, our output on the browser is:
Object { admin: false } Object { admin: false } Object { admin: false } Object { admin: false }
That means _user, window._user, user and window.user will return { admin: false }. Now lets try this code snippet on node.js in a js file:
var _user = { admin: false } user = { admin: false } console.log(_user, global._user, GLOBAL._user) console.log(user, global.user, GLOBAL.user)
In the result we can see that in node.js var _user did not create a global reference, only a local one:
{ admin: false } undefined undefined { admin: false } { admin: false } { admin: false }
In other words...
console.log(_user)``` returns { admin: false } console.log(global._user) returns undefined
console.log(user) returns { admin: false } console.log(global.user) returns { admin: false }
That means var _user = { admin: false } did not create a global reference because we ran the code in Node as a separate file. This is one of the differences between JavaScript in the browser and Node.
If we run this snippet in the node console (REPL) the result will be similar to browser-based JavaScript, i.e., the global._user will be created, because REPL works in a global scope.
The conclusion:
In Node, it is always encouraged to declare global variables explicitely in global.NAME = VALUE format. Because by omiting var in the variable declaration, a global variable is created implicitly and that can cause confusions.
0 notes
munnkey · 7 years ago
Text
React Hooks
Last week was the React Conf week and a new feature proposal has been showcased by React Core Team (Sophie Alpert, Dan Abramow and Ryan Florence). React Hooks basically a new library which helps functional components access State and context in a clean and declarative manner. It is promising for us (mortals) who start to write components in functional syntax and convert it to a class syntax when needed. You can see the details at the opening video below:
youtube
0 notes
munnkey · 7 years ago
Text
SublimeText JSPrettier stopped working
This week (after MacosX Mojave update) JSPrettier package on SublimeText stopped working. When I searched the internet, I have seen that it is a common problem, triggered by different causes. After trying several methods, the following procedure worked for me:
1. command + shift + p to open the command palette
2. Select Package control: Remove Package from the list.
Tumblr media
3. Select JSPrettier from the list to remove
Tumblr media
4. command + q to close SublimeText and restart. This is important. Reinstallation of the package without application restart did not resolve my issue.
5. command + shift + p for Package Control: Install Package
6. Find JsPrettier and install it.
Done! My js files pretty and well formatted again.
0 notes
munnkey · 7 years ago
Text
Ruby Quick Tip: to_query
Do you need to convert a hash to a url query? Ruby has to_query method just for that:
Usage:
"https://www.exampleurl.com?" + { location: "NYC", country: "US" }.to_query # => "https://www.exampleurl.com?location=NYC&country=US"
Inverse:
require 'CGI' CGI::parse "location=NYC&country=US" # => {"location"=>["NYC"], "country"=>["US"]}
0 notes
munnkey · 7 years ago
Text
Rails 6 - Action Text
A new rich text editor functionality will be added to Rails v6 (which is expected  in 2019). Action Text is based on Trix. You can see the preview in the video (by David Heinemeier Hansson) https://youtu.be/HJZ9TnKrt7Q or test the alpha version at the project github page https://github.com/rails/actiontext
youtube
0 notes
munnkey · 7 years ago
Text
Quick Ruby tip: #dig
I am sure most of you had to check validity of the deep level keys in inconsistent hashes or multi level form inputs. Until now, I was using:
... if params[:user] && params[:user][:address] && params[:user][:address][:somewhere_deep]
Instead of this, you can use:
... if params.dig(:user, :address, :somewhere_deep)
Isn’t it neat?
0 notes
munnkey · 7 years ago
Text
Ruby & React GraphQL (Part 3) -Backend Authentication Using Knock and JWT
After writing first basic queries and mutations with the help of resolvers, we will now implement our authentication and get current_user context for customer specific outputs that we need.
Install necessary gems:
following lines have to be added to the Gemfile under backend root directory:
gem 'bcrypt', '~> 3.1.7' gem 'knock' gem 'dotenv-rails', '~> 2.1', '>= 2.1.1'
dotenv-rails is needed for only dev environment. This gem helps you assign environment variables easily with rails s runtime.
Creating Environment secret for Token generation
We will need a secret key for: 1. bcrypt which will handle our password verification 2. knock which will generate and verify tokens for user sessions.
For this, we create a secret key with preinstalled rails tool with the command: rails secret
It generates a one time secret key to the console. To save it as a dev environment variable, you create a file on the root directory of your backend with the command touch .env . And you add your generated secret key as a variable in that file:
TOKEN_SECRET = 'def2bd510b0026bac0fc15056d649ba620abfb3fe5f27f3f5aa9866d23e1948c9cc71f22d43cff78852c367...'
Important
You have to add .env file in your .gitignore file to avoid sharing it with your repository.
Install knock
Command Line:
$ bundle install $ rails generate knock:install $ rails generate knock:token_controller user
It will create the following initializer config/initializers/knock.rb and user_token_controller.rb file. Initializer file contains all the informations about the existing configuration options.
Configuring knock initializer and controllers
Open the backend/config/initializers/knock.rb file and add the following line:
config.token_secret_signature_key = -> { TOKEN_SECRET }
This way, we will be sure that knock will use our TOKEN_SECRET env variable.
Open application_controller.rb file to add the following lines:
include Knock::Authenticable before_action :authenticate_user
This way we can be sure that Knock:Authenticable is loaded with every controller and before loading related routes authenticate_user method will be called. But we want to exclude user_login route from user authentication. for that we open user_token_controller.rb file and add the following line: skip_before_action :verify_authenticity_token
Now our authentication setup is completed. We can test it by a login attempt to localhost:3000/user_token with a valid email and password. Before this make sure you have a user with a valid password and email in the system. If you don't you can create one in rails console using: User.create(email: '[email protected]', password: '12345678', password_confirmation:'12345678')
After creating the user, using chrome console, make a login attempt using fetch POST:
fetch("http://localhost:3000/user_token", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({auth: {email:'[email protected]', password:'12345678'}})}) .then(resp=>resp.json()) .then(json=>console.log(json))
If everything is correct you can see your token in the console with the line: jwt: 'ascvbhtrdcer676....'
At the beginning of the project we installed the graphiQL desktop wrapper for macOSx
You can add http header by clicking Edit HTTP headers, add a header with name: Authorization and value Bearer ascvbhtrdcer676....
This way with every graphql query that you make your authentication token will be sent to our backend and if user is authenticated the response will be sent back. If token is not valid, a not authorized response will be sent to user.
Now as our authentication works, knock create current_user variable automatically.
In our resolvers we can user current_user as an input.
Example:
in your query_type.rb file, when user fetch allUsers, instead of returning allUsers info, we can configure to return only current_user data by modifying the code:
Types::QueryType = GraphQL::ObjectType.define do name 'Query' field :allUsers, !types[Types::UserType] do resolve -> (obj, args, ctx) { [ctx[:current_user]] } end end
0 notes
munnkey · 7 years ago
Text
Safari Array Bug on iOS 12 & macOS Mojave
An important webkit related bug has been spotted with the new iOs 12 & Safari v12 on macOS X updates. 
When you use Array.reverse() function, even if the page is refreshed the array is persisted as reversed. 
Bug is confirmed by Apple and a fix is set on Safari Technology Previews but it is not pushed to the general availability yet.
Details about the bug and workaround patch code can be found on https://stackoverflow.com/questions/52390368/array-state-will-be-cached-in-ios-12-safari-is-it-a-bug-or-feature
0 notes
munnkey · 7 years ago
Text
Quick Tip: ActiveRecord optional belongs_to
When you define a belongs_to - has_many relationship in Rails, Rails automatically adds implicitly a validation on the belongs_to part. That means, if you want to create a new element, if belongs_to is empty you will not be able to save it.
Ex: Restaurants and Franchise models. A Franchise has_many restaurants. A restaurant can belong to a Franchise but it is not required. In that case we have to explicitly write it to the restaurant model.
Under app/models/restaurant.rb file we have to add required field to avoid this implicit belongs_to presence validation
Ex:
class Restaurant < ApplicationRecord belongs_to :franchise, required: false
0 notes
munnkey · 7 years ago
Text
Best GraphQL tutorials and links
For my latest project I decided to learn and use Graphql on a Rails / React setup. I gathered most helpful links on GraphQL in this post.
BackEnd - Ruby / Rails
This was the most difficult part in my journey. Actually it is not the best time to try to learn graphql on ruby: graphql-ruby gem is a very established and widely used library. It is used by github, airbnb etc... in production. but recently gem is changing its DSL syntax to a more ruby way class based. As it is a recent change, all tutorials and info on the forums are all still based on the old DSL syntax. Official documentation is mostly adapted to the new syntax but there are still glitches. So after several attempts to learn directly new syntax, I gave up and decided to go with the old DSL syntax. 
Frontend - React / Apollo
On the frontend, after learning GraphQL query syntax, you can access the backend using standard fetch. You will get a well known JSON output. If you are already familiar with RESTful APIs, it will be a breeze to use GraphQL.
But there are also frameworks that you can use to make graphql data access more convenient and easy. Relay and Apollo are most widely used graphql libraries. In particular, Apollo is the newest one in the game and its ease of use has made it the number one choice between graphQL based JS / react developers.
Main advantages of Apollo:
Every component can access graphql data, make queries and mutations
All backend requests are async. Apollo client wait for a period of time before sending requests to the backend, merge them in a single request and send them in one big request. It helps you reduce the backend traffic.
Apollo supports a frontend data cache. If a component request a data and if this data is already requested and cached at that session, it is shared with the component directly without making a new request to the backend. 
I highly recommend to learn manually fetching data from a graphQL API before startin to use Apollo like high level frameworks.
Resources
Here are important links that helped me during the process:
http://graphql-ruby.org/ : It is the official website with API documentation, Guides and get Started guide. It is the main reference point for using the graphql-ruby gem
https://www.howtographql.com/ : It is a free graphql dedicated tutorial site. It has tutorials based on node.js, python, ruby, java, elixir, scala and React / Apollo
https://www.codementor.io/karanjaeddy/build-a-to-do-list-api-with-graphql-api-rails-5-part-1-irjt1e7jm : A good rails / react based full stack app tutorial based on Graphql
https://www.apollographql.com/ : Official Apollo GraphQL website and documentation.
https://developer.github.com/v4/ : Yes, github provides graphQL APIs to everybody who has API access enabled. It is a good way to learn to use a graphQL API from your backend without creating an API. I highly recommend that you start to develop a basic app using github API if you want to learn frontend access and Apollo without losing time to learn building a GraphQL backend.
https://graphql-slack.herokuapp.com/ : GraphQL slack channel. they have specific channels for every language and library. I highly recommend it for the questions and guidance that you cannot find a resolution on the forums 
0 notes
munnkey · 7 years ago
Text
Ruby & React GraphQL (Part 2) - Creating GraphQL Types and Queries
After creating and using RESTful API’s for a while and making a presentation on GraphQL, I decided to use graphQL on my latest project. I will give details about this project on multiple blog posts. You can also find repository of the project at github. This is the second part of this blog post series:
Installing GraphQL Ruby
After installing the gem file and bundle install we have to run rails g graphql:install for the initialization. This command add graphql-ruby boilerplate (graphql controller, graphql route, graphql folder ander app directory, initial files, including query_type and mutation_type files, empty schema).
To continue we create our types which relate to our models:
I created user_type.rb, baby_type.rb, event_type.rb files for the same named models.
I wrote the following code in user_type.rb file to define my graphql type: ` Types::UserType = GraphQL::ObjectType.define do name 'User'
field :id, !types.ID field :name, !types.String field :email, !types.String field :children, types[Types::BabyType] field :babies, types[Types::BabyType]
end `
As you can see the syntax is pretty different from the rails convention. There are 4 basic types: ID, String, Int, Bool. you can also refer the types that you created in other types (for belongs to, has many type of relationships). for those who are spoiled of rails magical convention: there is no automatic Activemodel -> GraphQL type convertion at the moment. there are several unsupported libraries on Github but none of them are ready for a production environment.
I also defined my other types:
baby_type.rb ` Types::BabyType = GraphQL::ObjectType.define do name 'Baby'
field :id, !types.ID field :name, !types.String field :sex, !types.String field :birth_day, !types.String field :mother, -> { Types::UserType }, property: :user field :caretakers, types[Types::UserType] field :events, types[Types::EventType]
end `
event_type ` Types::EventType = GraphQL::ObjectType.define do name 'Event'
field :id, !types.ID field :event_type, !types.String field :event_time, !types.String field :baby, Types::BabyType field :caretaker, Types::UserType field :amount_1, types.Int field :amount_2, types.Int field :unit_1, types.String field :unit_2, types.String field :notes, types.String field :event, Types::EventType
end `
Queries
After definition of GraphQL types we have to create our queries and mutations:
For our example we will pass over the most basic query (which will return all users list. I updated the query_type.rb with following code:
` Types::QueryType = GraphQL::ObjectType.define do name 'Query'
field :allUsers, !types[Types::UserType] do resolve -> (obj, args, ctx) { User.all } end end `
We added allUsers field which takes no argument and returns an array of UserType. It has a resolve function which returns User.all array as an object.
All queries and mutations have either a resolve or a call function which takes three default arguments: 1. Obj: this is the parent object, if there is no parent object, this is null. 2. args: user arguments 3. ctx: context which you can define session or query context. Ex: you can define current_user in the ctx object so you can modify your resolve / call functions based on the user authorization and scope.
Mutations
I created a basic createBaby Mutation to start. For this, I created a folder named 'resolvers' under graphQL folder. I created create_baby.rb file in it with the following code:
` class Resolvers::CreateBaby < GraphQL::Function argument :name, !types.String argument :sex, !types.String argument :birthDay, !types.String
type Types::BabyType def call(_obj, args, ctx) Baby.create!( name: args[:name], sex: args[:sex], birth_day: args[:birthDay], mother: ctx[:current_user] ) end
end ` In the Resolvers::CreateBaby class I defined: 1. arguments needed 2. return type 3. call method which will create the object and return the necessary output (like the controller functions that we have in a restful rails api app)
After creating resolvers, I defined them in the mutation_type.rb file: ` Types::MutationType = GraphQL::ObjectType.define do name 'Mutation'
field :createBaby, function: Resolvers::CreateBaby.new
end `
At the next chapter we will implement a token based user authentication.
0 notes
munnkey · 7 years ago
Text
Ruby & React GraphQL (Part 1) - Backend Installation
After creating and using RESTful API’s for a while and making a presentation on GraphQL, I decided to use graphQL on my latest project. I will give details about this project on multiple blog posts. You can also find repository of the project at github.
Setup
I will go with Rails 5.2.1 API only using graphql-ruby gem on the backend. (I want to have REST option open for the whole project). 
As it will be an API only rails project, graphiql (web interface of graphql) will not be available on the backend. So I installed standalone graphiql app on my mac which also let you change http headers (great for authentication) and connect to any graphql backend.
You can install graphiQL app with Homebrew: brew cask install graphiql
After that, I created a new folder for my project: mkdir baby-tracker cd baby-tracker
I decided to go with a single repository for backend and frontend. So I created a new rails app for the backend: rails new backend --API --database=POSTRESQL cd backend
I modified the following line to the Gemfile to install graphql: gem 'graphql'
After the installation I bundle installed: bundle install
Now to complete graphQL installation you need to rails g graphql:install . graphQL route and controller is generated alongside the app/graphql folder which contains GraphQL Schema (which is different from GraphQL schema), GraphQL types (which we will create to basically represent our objects and related data)
Creating Models
After the installation lets create our database and models first. For quick model generation I use rails generator. As this is an API only Rails app you won't create views. As graphQL use only one endpoint for all request, you don't also need controllers related to your models. rails g model User name email password_digest
User authentication will be the details for another blog post. rails g model Baby name sex birth_day:date mother:references
Using ...mother:references at rails g, creates a belongs to relationship with appropriate model. As we have no mother model we want to assign this key to the users model. So we add the line belongs_to :mother, class_name: "User" to the `app/models/baby.rb file. That way we will be able to call related user with BabyInstance.mother.
We generate other models with the same method: rails g model BabyUser baby:references user:references role active:boolean rails g model Event baby:references caretaker:references amount_1:integer amount_2:integer unit_1 unit_2 notes event_type event:references evet_time:datetime Than I migrate my database with rails db:migrate.
At next part we will test relationships of our models, will generate seed and will create GraphQL Types.
0 notes
munnkey · 7 years ago
Text
Quick tip for deploying Rails Apps
When you are deploying your SQLite based Rails app to an online service provider, You most probably will convert your database to PostreSQL. In that case in order to avoid compability problems, double check your where() statements. PostreSQL doesn’t like ‘IS’ or ‘IS NOT’ syntax like SQLite. You have to convert them to ‘=‘ or ‘!=‘
0 notes
munnkey · 7 years ago
Text
Using debounce on Redux store controlled input areas
During the graduation project of my bootcamp, I spent approximately 2 hours on this problem:
I have a search box which has a controlled value by the redux store and on change I make an API request to a mapping service. I don’t want to trigger the fetch request every time user typed a key. So, lodash debounce is the way to go. But during the implementation I figured out several problems.
My structure is like below:
import { debounce } from "lodash";
const debouncedFunction = debounce(props.nearbyRestaurants, 500);
......
const handleSearchInput = (e) => {     props.setSearchValue(e.target.value)     debouncedFunction(props.controlledSearchTerm)  };
....
     <Input        icon="search"        placeholder="Search for a restaurant"        onChange={handleSearchInput}        value={props.controlledSearchTerm}  
     />
This (of course) didn’t work. As the value is controlled. e.target.value is not still changed when debounced function is called.
Solution 1 (Not working): 
So I stopped, controlling the value by deleting value filed in the input:
    <Input       icon="search"       placeholder="Search for a restaurant"       onChange={handleSearchInput}      />
That didn’t also work (of course). Because setting a value on the store is async and until debounced function is called the value is still not set.
Solution 2 (Not working):
So I decided to use event.target.input for debouncedFunction call:
const handleSearchInput = (e) => {    props.setSearchValue(e.target.value)    debouncedFunction(e.target.value) };
In the essence it should work: I am not controlling the input value anymore, I use event.target.value which is real time. I looked to my backend traffic. Yes: the queries had a latency for 500 ms. But still debounce was not eliminating consecutive queries but only waiting 500 ms before sending them. So for a user who want to search for ‘diner’, 5 api calls were made for :
1. ‘d’, 2. ‘di’, 3. ‘din’ 4. ‘dine’ 5. ‘diner’
That was not the essence of the debounce.
Not the result that I want. So hours passed and saw that, changing the store value consecutively with debounce function was causing to debounce to create separate instances of debounce waiting loops which was causing debounce (in a mysterious way) not handling the requests consecutively but in parallel. 
Solution 3 (Not working):
I decided to set the state in my debouncedFunction call. So debounce will set the state at the same time call the necessary function.
 let debouncedSearch = debounce((text) =>       props.nearbyRestaurants(text);       props.setSearchTerm(text);  }, 500);
 const handleSearchInput = (e) => {    debouncedSearch(e.target.value);  };
But thet didn’t work, because until debounce wait time is finished, syntetic event handler of react nullifies event value.
Solution 4 (Semi working): So I decided to use, Semantic UI Input’s second attribute that passes in the event handler as d which is persistant:
let debouncedSearch = debounce((text) =>      props.nearbyRestaurants(text);      props.setSearchTerm(text); }, 500);
const handleSearchInput = (e, d) => {   debouncedSearch(d.value); };
Now everything was finein the api call and set state perspective. Except that the search input value is no longer controlled. For a total control of this you have to write your own searchInput component with an internal state which will handle value control internally and update its own state with componentWillReceiveProps function to be sure that the input text value will be in sync with store value. But I decided to use it uncontrolled way for now.
If you have a better solution, I will be more than happy in the comments.
0 notes
munnkey · 7 years ago
Text
How to Create a Progressive Web App (PWA)
If you are now in the mystique world of JS and Web Apps, you started to be excited what you can do on a web page, you have to be also curious about how to transform your existing app to a mobile app. There are a lot of frameworks and libraries (like React Native etc...) which leverage your existing JS knowledge and code to create a mobile app. Creating and running native apps on mobile is an important thing on the production. But for those of you who still think that there is a lot to learn before jumping to learn another library for just mobile development, you can use Progressive Web Apps. PWA is basically a web app working standalone without a web browser on a mobile device with the ability to use extended features of the device like push notifications, gps location, dialer etc.. like a native app. PWAs are supported both by Android and iOS.
So here is the basic step by step tutorial for you to transform your web app to PWA:
Lets start with an existing basic app that you already have. I used my pokemon search app that I practiced during learning basic dom manipulation: First of all you can install Web Server for Chrome to transform your directory to a basic web server. You will show the related directory and press start: Voila: your app is now served through localhost:8887 
Tumblr media
After that, optionally to test features of PWA you can connect your android phone to your computer using developer mode. First activate developer mode on your phone:
Settings >> About Phone >> Touch ‘Build number’ 7 times. And it is activated: 
Tumblr media
After that you activate Settings >> Developer Options >> USB Debugging
Tumblr media
Now go to the chrome browser in your pc and open chrome://inspect/#devices to activate Discover USB devices and port forwarding: add localhost:8887 to your port forwarding list:
Tumblr media
After connecting your phone to your pc you have to see a view like the screenshot below:
Tumblr media
Now go to the chrome on your android device and enter localhost:8887 in the address bar:
Tumblr media
Now lets make the appropriate changes on your web app, so it will be recognized as a PWA on your devices.
We have to add the two lines below to the head of the html pages that we serve in our app:
Tumblr media
As you can see we added a viewport meta data to our app so that browser will know how to parse the website according to our instructions.
The second line is the Web App manifest json file that we need to create in order to define the characteristics of our app. Be careful about the formatting on the JSOn file. Browsers can be picky for the keys, case sensitivity and closed brackets:
Tumblr media
You can define multiple icons for an app for different resolutions. But we will stick with one for now.
Now refresh the browser on your mobile phone and click to:
Chrome Menu >> Add to Home Page
Tumblr media
and Voila! 
Tumblr media Tumblr media
As you can see we now have an app icon and an app which is running standalone. without a browser. With further modifications and adding service workers, you can make your application work offline, manage http requests, you can get rid of the top bar, push notifications to the users, get access device specific features like location, gyro data etc... For further info on service workers and using additional features, Google Developers Website has a good step by step tutorial and detailed documentation.
0 notes