About Coding
Life is good, until you want better. Before enter a coding bootcamp I was given the typical advised and warnings before starting such as "prepare for a difficult journey" and such. They all have a place and time why they are consistently told. But while going through the process I learned that its difficult because it helps build character and resilience. These and many more that could many coders could agree upon are what makes the entire process from inception to developer so life changing. Smile Eat Sleep and Code.
One building Block at a time
At the very core of every programmer lays an indispensable skill that is hard to quantify or expressed in few words. That skill is within the ability to read, write and learn at the consistent pace of that which mimics technology, which is constantly.
The best way I approach this requirement is by first choosing a technology or language of interest. Being interested in what you choose is very important since it is whats going to keep you motivated when your spirits are down and there is no way out.
The second part is to dissect the subject matter into its most basic component and learn that very very well. Similar to math in elementary. You fist learn to count and the logic behind counting up to 10. Using the knowledge gain from learning the basics will help you master the next level of mastery in the subject field making the entire process a catapult effect. Mean while practicing every step of the way what was learn in order to solidify the retention of the knowledge gained.
This is just my simple way of learning and mastery new subjects.
Association in OOP
Association in Object Oriented Programming (OOP) represents a relationship between objects.
Each object is independent of each others life cycle and owner.
A good life example would be in a school setting were you have multiple students interacting with a teacher or where one student can interact with multiple teachers. In both situation both students and teachers are independent of each others.
Working With Files in Ruby
Indispensable Ruby methods
Working with directories in Ruby
"Creating a Ruby GEM"
Rail Supported Associations:
- belongs_to
- has_one
- has_many
- has_many :through
- has_one :through
- has_and_belongs_to_many (no need to ever use)
-
belongs_to
sets up a one-to-one connection. This also means that the foreign key is in this class . In other wordsbelongs_to
can ONLY go in the class that holds the foreign key.belongs_to
relationship will be calledyourassociationname_id
Thebelongs_to
association supports these options:- :autosave
- :class_name
- :counter_cache
- :dependent
- :foreign_key
- :primary_key
- :inverse_of
- :polymorphic
- :touch
- :validate
- :optional
-
has_one
sets up a one-to-one connection with another model. This also means that there is a foreign key in another table that references this class. So has_one can ONLY go in a class that is referenced by a column in another table.has_one
supports the following options:- :as
- :autosave
- :class_name
- :dependent
- :foreign_key
- :inverse_of
- :primary_key
- :source
- :source_type
- :through
- :validate
-
has_many
association indicates a one-to-many connection with another model. You'll often find this association on the "other side" of a belongs_to association. This association indicates that each instance of the model has zero or more instances of another model.
The table with the foreign key will be declare after has_many
which is referred as the association table.
has_many
association supports these options:
- :as
- :autosave
- :class_name
- :counter_cache
- :dependent
- :foreign_key
- :inverse_of
- :primary_key
- :source
- :source_type
- :through
- :validate
-
has_many :through association
is where you create a - through table to act as a go-between for two models that have a many-to-many relationship. -
has_one :through
one-to-one connection with another model. -
Association Options
:class_name
specify the class your association should point.
class Post < ActiveRecord::Base belongs_to :author, :class_name => "User" belongs_to :editor, :class_name => "User" end
Rails will automatically look for the foreign key named after the association, e.g. author_id or editor_id, in the Posts table and it associated with
User
method:foreign_key
allows you to specify the name of the foreign key name if you are not going by regular ruby naming convention.
class User < ActiveRecord::Base has_many :authored_posts, :foreign_key => "author_id", :class_name => "Post" has_many :edited_posts, :foreign_key => "editor_id", :class_name => "Post" end
-
:source
Rails uses the name of the association in the through table to determine which foreign key and table name to reach out to. If it’s named anything irregular, you’ll use the:source
. Think of:source
as being just like :class_name but for the associations in the “through table”.class Post < ActiveRecord::Base has_many :post_authorings, :foreign_key => :authored_post_id has_many :authors, :through => :post_authorings, :source => :post_author belongs_to :editor, :class_name => "User" end
-
"Working With Sinatra and the MVC Architecture"
Working With Sinatra and the MVC Architecture
Most web applications follow a similar convention in terms of their functionality and structure. In this posting I'll illustrate how a simple application follows common structures and logic found on bigger sites.
When using Sinatra , a DSL language that uses ruby as its foundation, at its most basic level only the sinatra gem and an app.rb file is require to start running your application.
- Installs the sinatra gem
gem install sinatra
- The 'app.rb' file will specify your application's routes and will require your sinatra gem.
require 'sinatra' get '/' do 'Hello world!' end
* Your app can be view by visiting http://localhost:4567
This is would be the most basic level of running a basic web application.
With time your applications needs will start to grow and a clean file structure will become a necessity to managing and maintaining your application running smoothly.
A great a approach to follow is to build a [rails](https://en.wikipedia.org/wiki/Ruby_on_Rails) like file structure.

##### The app folder contains your [MVC structure](https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller).
The Model-View-Controller (MVC) architectural pattern breaks down your application into three main components: the model, the view, and the controller.
*The Model*
> The model is responsible for your applications logic and application specifics data manipulation. It also specifies the applications relationship with other tables and applications. Such relations are not limited to one-to-many, one-to-one and many-to-many .
*The View*
> The view is responsible for the user interface. It directly interfaces with the users.
*The controller*
> The controller is like the mediator for the controller and the view. For the most part it directs the application traffic. Controller objects can also perform setup and coordinating tasks for an application and manage the life cycles of other objects.
*Helper Folder*
> The helper folder is conventionally used to host shared code among classes. Such shared code included modules codes that are shared through out your application.
*Config*
> Config folder host the require other files and gem for your application environment. In most cases it also includes your database adapter.
*db*
>DB folder host your database and table schema(structure). Beside containing these crucial files it hosts generated migrations that where used to manipulate your tables.
*lib*
>Lib folder as the name suggest conventionally host created libraries or library obtain from other models to data manipulation.
*config.ru*
> Config.ru files is used to wrap your application together. As a result this file will require the files in the config folder that host your environment configurations and acquire other vital files, gem and libraries. Here is where you tell your application where the files for the MVC architecture are located.
*Gemfile*
>[Gemfile](https://bundler.io/) acquires all the third party gems that your application will be using. Such gems might include Sinatra, ActiveRecord, Shotgun and testing apps like Pry, and Tux
*Rakefile*
> [Rakefile](https://en.m.wikipedia.org/wiki/Rake_(software) ) is used to create task for your application. These task include the task of creating migrations, entering a testing console and many more. You could either create your own process or acquire rake task from gems and integrate them in your rake file such as the ```sinatra-activerecord``` gem. Typing ```rake -T``` in your console displays all available rake task.
"Ruby Style Guide "
Ruby Style Guide Suggestions (According to Shopify)
-
Make all lines of your methods operate on the same level of abstraction also known as Single Responsibility Principle (SRP). (Single Level of Abstraction Principle)
By making each have a single functionality or responsibility not only leads to better organized code but for better readability and refactoring. In layman terms, its like having a registration object that:
- Checks the IP address in a spam database,
- Sends an email to the new user,
- Adds a bonus to an account of a recommending user,
- Creates accounts in related services, and many more.
Instead of having a separate method for each action and calling them individually.
class RegistrationController < ApplicationController
def create(params)
user = User.create(params)
if user.valid? && ip_valid?(registration_ip)
user.save!
user.send_email
user.refer_bonus
user.related_services
end
end
end
wrong
```RUBY
class RegistrationService
def start(params)
user = User.new(params)
if user.valid? && ip_validator.valid?(registration_ip)
user.save!
after_registered_events(user)
end
user
end
private
def after_registered_events(user)
Mailer.new(user)
Referal.new(user)
Services.new(user)
end
def ip_validator(registration_ip)
@ip_validator ||= IpValidator.new
end
end
class RegistrationController < ApplicationController
def create
user = RegistrationService.new.fire!(registration_params)
end
end
```
good
Why is the refractor code good ? Beside being more organized if we needed to change any part of the registration events we would do so in its individual class. This makes the code easier to maintain and read has well.
- Code in a functional way. Avoid mutation (side effects) when you can.
[example goes here ]
- Do not program defensively
[example goes here ]
- Do not mutate arguments unless that is the purpose of the method
[example goes here ]
- Do not mess around in / monkeypatch core classes when writing libraries.
[example goes here ]
- Keep the code simple.
[example goes here ]
- Don’t overdesign.
[example goes here ]
- Don’t underdesign.
[example goes here ]
- Avoid bugs.
[example goes here ]
- Be consistent.
[example goes here ]
- Use common sense.
[example goes here ]
"Working With Active Storage"
Rails Active Storage
Rails introduced active storage recently has of the writing of this post. Active Storage is a built-in gem included on Rails 5.2 that handles file uploads to storage services from Amazon, Google, and Microsoft. Saving to local disk is also possible for development and test environments. Although there always been different methods of implementing this feature in Rails, such as with the paperclip Carrierwave, Dragonfly. It's a more holistic approach implementing Active Storage into your application since its a baked right into the Rails framework already. Active storage does require external gems such as MiniMagick in order to perform transformations and previews of the user's uploaded attachments.
Active Storage works by requiring two additional tables order to intergrate into your Rails application. These tables are active_storage_blobs and active_storage_attachments. The required tables are generated by running
rails active_storage: install
and
rails db: migrate
to execute the migration.
This migation creates to tables
active_storage_attachments
and
active_storage_blobs
Blob stores metadata like filename, content-type, byte size and checksum. The actual file is stored in the storage service or disk depending on your settings. A Blob can be attached to one or more Active Record objects through the Attachment join model.
Storing file attachments within your application provider could become expensive quick as a result it is recommended to use a cloud service such as AWS, Google Cloud and Microsoft Azures to name a few. Rails facilitate the configurations of these services by config/storage.yml file. Some cloud services provider require additional configurations in order to work with Active Storage.
By default, your local storage is used.
config/environments/development.rb
tells Rails which provider to use.
Once the proper tables are setup and the application is configured properly all that is left is the proper associations to be made within your models.
Active Storage supports has_one
, has_many
and many more associations by adding the suffix attached to the association such as has_one_attached
.
These associations allow for images to be attached to the object identified in the association by calling attach
. Other methods can be called such as attached?
to determine if an object has many attachments, detach
to delete the attachment but leaving its reference, while purge
completely removes the attachment alone with its blob. You also have access to purge_later
to remove the attachment through a queuing system.
There will be times where you would want to link an attachment on your page. To generate a download link one would call
rails_blob_path(atttachment_name, disposition: "attachment")
Transforming attachments requires the use of third-party gems such as mini_magick. Mini Magick allows for certain files such as pdf to be preview and images to be resized and transform by calling variant
and preview
methods on the object. Both variant
and preview
accepts hash arguments. When previewing videos the first frame for the video is used.
Active Storage also allows for direct uploads transferring any attachment from the client directly to cloud services. In order to activate this feature Rails asset pipeline must be setup correctly by including activestorage.js
in your application bundle. Once its enable using either npm
or via Rail's asset pipeline direct_upload: true
is passed from the view to allow direct upload. Direct upload is integrated with a Javascript framework or if you want to customize a drag and drop feature its possible by calling the DirectUpload class. Direct upload Javascript events allow progress indication while the file upload.
Since Active Storage is a fairly new library its code base is easier to navigate and explore for the curious among us.
You could find the source code on github or by running bundle open activestorage
from your commandline if you are using bundler.
"SPA With a Rails API and a Javascript Frontend"
Rails Backend with a Javacript Frontend
Most developers know Ruby on Rails also refered such just Rails, as a monolith framework where one app hosts it all. These type of applications have its place in ecosystem on web developement. Just as it is true for Rails having its advantage over other type of framework it also have it's drawbacks. As a result to some of the drawbacks you might encouter when using Rails as a monilith application framework Rails also offers an API (Application Programming Interface) version.
Advantages of using Rails as an API
Some of the advantage of using Rails as an API is that it frees up the frontend to other languages. This approch allows for more choices and options. By allowing the frontend to be detached we are able to host the backend with a different service provider than our front end.
How it works
Since basically we are running 2 seperate parts (backend and frontend) on part, typically the frontend makes a request to the backend. This is ussually called an API call. Once the API call is rceived the backend process this request and returns a status code. This code is used by the backend to signal if the request was successful or any other status that it wants to convey to the frontend. Given that the initial request was successful, the fronted proceeds in sending the user's or the intended request to the API and in return the API process the necessary actions required. Such actions include send back data to the frontend typically in the form of a hash or JSON. The frontend takes the response and process it, typically by display it the user or other actions based on the data.
Examples
On the Distraction Deck Single Page Application (SPA) I'm using rails as an API while using Javascript, CSS and HTML on the frontend on the client side. The following interactions take place once the client logs in.
- On the initial page the client logs in with their username and password
- The username and password is sent to the backend
- Once the username and password is received by the Rails API the following takes place
- Rails finds the user in the database
- validates the password given againt the user's password hash on file.
- Once the user passes the validation process the Rails API parses the user's table data into JSON format and sends back to the client
- Once the client receives the data the SPA loads and starts to display all the relevant information received.