Writing

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


Ruby is a very versatile language that borrows from the concept that everything is an object. While this method makes working with Ruby more much more flexible and enjoyable to learn and work the way ruby handles files makes it even more powerful to work with.<o:p></o:p>

 If you been learning Ruby or are familiar with it’s class system you are most likely familiar with Ruby’s Input Out (IO) class. This class is responsible for putting things on your screen such as strings. One of it’s widely used method include “puts”, which is on output. Another similar method to “puts”  would be “print” with the difference of returning a line return depending which one you use.  Another come method used that is part of Ruby’s IO class would “gets”. “Gets” is an input which waits for the user’s input. Usually the user input is stored in variable which makes it easier to manipulate within you program. Puts, print and gets makes your program more powers because it allows the user to make decisions and based on those decision your program would act accordingly.<o:p></o:p>

Ruby’s file system work similar to that of most operating systems with  few exceptions that would make it much easier to work with once addressed. These exceptions include the way Ruby handles file path separators and file permissions, which ruby handles different depending on the operating system. Unix file system uses forward slashes for its path while windows uses backslashes. Given these differences ruby makes it safe to always use the forward slashes no matter what operating system you are running. <o:p></o:p>
·      Unix: shared/lib/myfile.rb<o:p></o:p>
·      Windows: Shared\lib\myfile.rb<o:p></o:p>
Ruby’s File class simplifies all this by providing us with the join method. The join method determines what your system can handle whether the forward slashes or the backslashes.  <o:p></o:p>
·      File.join(‘shared’,’lib’,’myfile.fb’)<o:p></o:p>

Working with files in ruby is very simple. Just like working with any other platforms there are some difference that we all need to become aware. It is assumed that every file on your computer belongs to you, with the exceptions of certain situations.  <o:p></o:p>
In Unix we change the files permission using the “chmod” command. (http://ss64.com/bash/chmod.html). In windows permissions are managed via Properties/Security tab. (https://msdn.microsoft.com/en-us/library/bb727008.aspx). <o:p></o:p>

Understanding how to locate files and its permissions helps us have better understanding of ruby’s fundamentals. Now that we got that cover its only natural that we also discus how to accesses the files and read them. <o:p></o:p>
Ruby provided us with two methods to reading files they are File.new and File.open. <o:p></o:p>
With File.new we are creating an object that would exists as a file in your system.  We give it a name and pass it on option. Like any other object we want to assign our new object to a variable.<o:p></o:p>
·      file = File.new(“test_file.txt” , w)   <o:p></o:p>
Below is a list of options that can be used for files. <o:p></o:p>
·      "r"  -  Read-only, starts at beginning of file.<o:p></o:p>
·      "r+" - Read-write, starts at beginning of file.<o:p></o:p>
·      "w"  Write-only, truncates existing file to zero length or creates a  new file for writing.  <o:p></o:p>
·      "w+" Read-write, truncates existing file to zero length or creates a new file for reading and writing.  <o:p></o:p>
·      "a"  Write-only, each write call appends data at end of file.      Creates a new file for writing if file does not exist.  <o:p></o:p>
·      "a+" Read-write, each write call appends data at end of file.      Creates a new file for reading and writing if file does not exist.<o:p></o:p>
It is always good practice to close your files access once you are done reading or writing to them in order to prevent accidental deletions or writes. With our previous example we close the file using the close method, file.close .  The other method that we can used is the open method.<o:p></o:p>
·      File.open (“test_file.txt”, “w”)<o:p></o:p>
This method creates a file with the specified name if it doesn’t exists and closes it for you. It is also possible to pass a code block with the open method. <o:p></o:p>
·      File.open(“test_file.txt”, “r”) do |file|<o:p></o:p>
·      #reads the file data<o:p></o:p>
·      end <o:p></o:p>

Since we went over the basics of creating files in Ruby writing to these files becomes easier. When we create a file or instantiate a file with the same name as one that already exists in the same location we are essentially erasing everything with it unless we use the “r” option.<o:p></o:p>
To write into a file in ruby we first instantiate the file object.<o:p></o:p>
·      file =File.new(“This_is_the_name_of_a_file.txt”,”w”)<o:p></o:p>
Once instantiate we could use various methods of writing to the file.<o:p></o:p>
·      puts    file.puts “This text will go into the file created”<o:p></o:p>
·      print   file.print “This text will go into the file created”<o:p></o:p>
·      <<     file << “This text will go into the file created”<o:p></o:p>
·      write   file.write “This text will go into the file created”<o:p></o:p>
Keep in mind that once we finished writing to the file we must close it in order to execute the methods. Until the file is closed everything stays in the system memory. This is done to preserve the amount of writes done to the local drive.<o:p></o:p>

Thus far we learn on how to access files, create files and write to files. Now we are ready to learn how to read from files.  There are different ways on reading from files in Ruby. We can partially ready from a file, only read an exact amount of characters, read an entire line or the entire document. <o:p></o:p>
·       file = File.new(“test_file.txt”, “r”)   assigns a variable to the read process <o:p></o:p>
·      file.gets  reads from the current pointer position to the end of the line including the line return. Also sets the pointer to the end of the line.<o:p></o:p>
·      file.read(num)  reads the exact amount of characters specified within the parenthesis including white spaces. Sets the pointer where it finished reading.<o:p></o:p>
·      file.each_line{|line| puts line}  reads each line of the file. Sets the pointer at the end of the file.<o:p></o:p>

File pointers in Ruby are very important part to writing and reading to and from files. Pointers tells ruby were to start reading and where to start writing. To find the current position  of the file pointer we use the pos method. We can also set the position of pointer, pos = 2 .<o:p></o:p>
·      file = File.new(“test_file.txt”,”r+”) assigns the file to the variable file with the read and write option.<o:p></o:p>
·      file.pos  returns the pointer status<o:p></o:p>
·      file.pos = 2  sets the pointer position<o:p></o:p>
·      file.eof? returns true or false depending if the pointer is at the end of the file<o:p></o:p>
·      file.rewind  Takes us to the beginning of the file and sets lineno to 0<o:p></o:p>
·      file.pos +=4  moves the pointer 4 position depending were the pointer is located<o:p></o:p>
·      file.pos -=4 moves the pointer back 4 position back depending were the pointer is located<o:p></o:p>
·      file.lineno doesn’t return the line number. It keeps track of how any times gets has been called. <o:p></o:p>
·      ** Be careful on setting the file pointer beyond the end of the file. Setting the pointer beyond the end of the file would replace any an accounted space to nil numeric equivalent of \000</i><o:p></o:p>

Renaming files<o:p></o:p>
Renaming files in Ruby is very straightforward. We use the rename method.<o:p></o:p>
·      File.rename(“test_file.txt”, “file_to_delete”) We call the rename method on the File class. We pass it the name of the file follow by the name that we want to rename it with.<o:p></o:p>
Deleting files<o:p></o:p>
Just like renaming files deleting them is just as simple<o:p></o:p>
·      File.delete(“file_to_delete”)  We call the delete method to the File class follow by the name of the file.<o:p></o:p>
Coping files<o:p></o:p>
 Copying files in ruby is just as simple as requiring the FileUtils class from ruby. This class is part of ruby but needs to be required first. Essentially this class allows us to use the most common commands that we are used to using via the command line in Unix. <o:p></o:p>
·      require ‘fileutils’<o:p></o:p>
·      FileUtils.copy (“test_file.txt”, “copied file”)<o:p></o:p>
Beyond copying files FileUtils allows us to change file permissions and provided us with many more options which are normally available via the command line.<o:p></o:p>

Working with files in ruby is very useful and straightforward. The same thinking can be apply when working with directories which I’ll cover in future posts. Mean while getting comfortable with Ruby’s File and IO class are essential to proficiently navigating, reading and writing files in Ruby. <o:p></o:p>


Indispensable Ruby methods

Ruby  can be and often is a very straightforward language to learn. But in order to become a great ruby ninja we must increase our personal Ruby toolbox. Some of the most indispensable tools that I have gather are refered to as innate methods. This methods are methods that every object created in ruby automatically inherit. You could see a list of these methods by calling the methods method on the object.
·      Object.new.methods
Some of these methods are very useful and have become part of my programming language. These methods are:
·      object_id
·      respond_to?
·      send   or  __send__

Object ID
Usually to compare objects we tend to use ruby equality operator == .
The equality operator is good at comparing objects such as strings at face value but not by its assigned id that ruby uses to reference objects and keep track of them.
·      a = “horse”
·      b = “horse”
If we use the equality operator on the example above we get a return of true
·       a == b
This accurse because ruby is comparing both variable at same value. Internally they are not.
·      a.object_id == b.object_id
This above code returns false since it checks to see if they are equal true as well as the example below.
·      a = “apple”
·      c = a

respond_to?
This method checks to see if an object response to a message being send.
This method exists in all objects. This method becomes very useful when checking the validity of a message being send. In conclusion it makes for shorter cleaner code. Consider the following:
x = Object.new
o   if x == (user_input)
§  do this …
o   elsif x== (user_input)
§   do this …
o   elsif x == (user_input)
§   do this ..
 VS
x = Object.new
if  x.respond_to?(user_input)
     x.user_input
else
    puts “Invalid call”
end
In the previous examples the respond_to? method predetermines if the user input will be valid to object being passed to.

send / __send__ / public_send
sendis used to send a direct call to an object. Since send is a very common word that could be used very often when writing methods ruby provides us with two alternatives, __send__ and public_send  . The big difference between these methods is that __send__ is able to access private methods that at times we might want to avoid. Unlike, public_send only have access to public methods.
if x.respond_to?(user_input)
  x.public_send(user_input)
else
 puts “Invalid call”

end

Working with directories in Ruby

Working with directories in Ruby is an essential skill to have in order to become a proficient programmer. Luckily working with directories is just as straightforward as working with files. The most basic keywords, methods and syntax that are indispensable to remember are as follow:
File class
·      dirname
·      expand_path
Directory class
·      pwd
·      chdir
·      entries
·      foreach
·      mkdir
·      delete

Utilizing the Directory class in combination with File class allows us to manipulate files and directories in any way possible. Ruby have a special keyword called __FILE__ that represents the current directory. If we run __FILE__ in combination with dirname  we get a representation of the current directory.

File.dirname(__FILE__)   è “.”

If we combine the representation of the current directory along with the expand_pathmethod which gives us the current path we get our current directory path.

File.expand_path(File.dirname(__FILE__)) èfull path to the current directory

Using File.dirname(__FILE__) is different from using Dir.pwd, found in the Directory class. Dir.pwdrepresents  the present working directory while when we use File.dirname(__FILE__)  we are asking for the current directory path relative to this file. This is more useful because we could move around directories by using Dir.chdir  and telling it where we want to go.
To go back a directory we pass ‘..’ to Dir.chdir . It could take an absolute path as well as a relative path.

Dir.chdir(‘..’) è 0

To list the contents of a directory we use  Dir.entries  and tell it which directories to display the content.

Dir.entries(“.”) è displays all the files in an array

Since the entries method displays its results in an array gives us the ability to sort the files if we want to or pass each one to an enumerable. The possibilities are endless. 

Dir.entries(“.”).each do |entries|
puts entries + “:”
end
Since looping the directory files is such a common task that ruby provide us with foreach method which works the same way as the each enumerable.
We also have the ability to make directories using  Dir.mkdir and providing it with a directory name.

Dir.mkdir(“this_is_a_dir”)

We also have the ability to delete directories using the delete method. Dir.delete

Dir.delete(“this_is_a_dir”)

The delete method only work if the directory is empty. To delete directories that are not empty we could use the Fileutil class the we used previously.

That is the basics on working with directories and files.


"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 words belongs_to can ONLY go in the class that holds the foreign key. belongs_to relationship will be called yourassociationname_id The belongs_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.

![MVCStructure]({{ site.url }}/images/MVC_file_structure.png)

##### 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.