What does Memoization mean?

I was watching a screencast the other day and the person mentioned in the video: “… and this gives you an mm(…) array”. The (..) means that I did not understand what I had just heard. I admit that I rewinded the video a few times and I could only grasp something along the lines of ‘memorized array’. It was then that I googled this and was autocorrected to “memoization”. WAT?

It turns out that memoization is recording the results of earlier calculations so that we don’t have to repeat the calculations again. It simply means caching the output.

An example may clarify this further. Say I have method that tells me how many Twitter followers a user has:

def total_twitter_followers
  current_user.twitter_followers
end

This is perfectly valid, however, every time we call this method during one request it always calls the Twitter API for the result. By memoizing the call, you store the value thus avoiding expensive fetches again:

def total_twitter_followers
  @current_user_total_followers ||= current_user.twitter_followers
end

The ||= operator is a so-called conditional assignment that only assigns the value on its right to the variable on its left if the variable is not true. Since pretty much everything in Ruby evaluates to true when coerced into a boolean (except nil and, of course, false, as well as a couple of other things) this is exactly what we want: The first call returns the actual string and from the second time on, no matter how often the method is called on the same object, the “cached” result will be used.

Hope you learned something today.

Stacked Solution

I love when I get exposed to new ideas and concepts that enhance my work or expand my intellectual acumen. That is one of the reasons why I picked software development as a career: each day I learn something in the job. It is never boring.

Especially people like me that did not acquire a traditional Computer Science degree (I actually learned programming through this public-private initiative.), chance upon concepts of CS that both better our overall programming understanding and explain the theory behind our coding practices.

I had the opportunity to work on a computer science problem with Tim Mansfield, a very knowledgeable programmer and, as it could be noticed from the short interaction we had, a great guy.

The problem we worked together is called Balanced parenthesis. Later I learned that balanced parenthesis is one of the tasks done by a compiler. It verifies if parentheses in a source code have their counterpart or not. For example you would want that each opening ‘{‘ or ‘(‘ in a source code must have a corresponding closure ‘}’ or ‘)’. So if the code is not put properly, i.e. if they are not balanced ‘{(})’, the compiler should throw an error.

Here is the problem at length:

Write a function to determine if a string is
‘balanced’. Balanced means that opening and closing
brackets match each other in the proper order. Other
characters are possible and should be handled. The
possible characters for balancing are {}, (), and []

Example Input:

‘{}’ -> True
‘{[]}’ -> True
‘{5}’ -> True
‘{[}’ -> False
‘[A]{}d()’ -> True
‘a’ -> True
‘a}’ -> False
‘([)]’ -> False
‘([])’ -> True
‘{‘ -> False
‘{{{{}}}’ -> False

The best way to solve this is to break down the problem at hand by writing in plain English.

  #split the string into an array of characters
  #loop through the array
  #if open symbol i.e. '{','[','(' then store them in a list
  #if closing symbol then remove last opening symbol in list
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced symbol.

Therefore delving now into the code we have:

def is_balanced(input)
 #split the string into an array of characters
  array_chars = input.chars

  open_brackets = []
 #loop through the array
  array_chars.each do |char|
    #if open symbol i.e. '{','[','(' then store them in a list
    if char =~ /[\[|\{|\(]/
      open_brackets << char
    elsif char =~ /[\]|\}|\)]/
      #if closing symbol matches an its opening symbol then remove last opening symbol in list
      bracket_matching = { ']' => '[', '}' => '{', ')' => '('}
      bracket = bracket_matching[char]
      return false unless open_brackets.include?(bracket)
      open_brackets.pop
    end
  end
  # if everything matches then the remaining list should be empty, otherwise there is unbalanced parenthesis.
  open_brackets.empty?
end

is_balanced('{{}}’) #=> true
is_balance('[(])') #=> false

We notice in this code that there is always inserting and removing one element from the end of the array. What is entering last, it is actually coming out first.

The implemented solution to this problem is called a Stack data structure. Thinking again, I remember implemented something similar when I worked on a linked-list problem months ago. There you go. I learned something that has already an impacted on my programming skills and for that it made my day.

Role-Based Authorization with Rails 4 Enum

I have started creating an employee engagement application recently. Its purpose is to allow companies to engage their employees in volunteering activities around social projects. For this application I need to create 3 different roles and access levels.

I am using Ruby on Rails and I discovered that you could do this with gems such as ActiveAdmin and Rolify. But I decided to give Rails 4 Enum a try.

In my application each User will have one role: a super_admin(that takes care of the whole application), company_admin(an person that administers employee engagement with this application), and employee(user from a company that uses the application). Therefore these are single-defined roles. Now if the User had the possibility to have more than a role, for instance a company_admin could also be a super_admin then this would be a bit more complex. It is indeed multiple role based authorization and the gem Rolify would do a better job at this.

Anyways, below is one way one can implement three different access levels using Enum.

An enumerated-type or enum in Rails is a hash where the values reference to integers in the database. Example

User.access_level # => {"employee"=>0, "company_admin"=>1, "super_admin"=>2}

More info about enum methods here

Assuming that you installed Devise and have a User table or similar, first add the access_level column to the users table

 rails g migration AddAccessLevelToUsers access_level:integer
class AddAccessLevelToUsers < ActiveRecord::Migration 
 def change
   #adding the default to zero will automatically set the user access level to the first Enum attribute
   add_column :users, :access_level, :integer, default: 0
 end
end

Now in the User Model add:

class User < ActiveRecord::Base
  # you can also explicitly define enum as:  enum access_level: [:employee => 0, :company_admin => 1, :super_admin => 2}
  enum access_level: [:employee, :company_admin, :super_admin]
  
end

Migrate the changes to database and create three users in Rails console. Assign them access levels

 # by default the user access_level is employee
 user1.access_level #=> employee 
 # below we are assigning access_level to user2 and user3 rather the default employee
 user2.company_admin!
 user3.super_admin!

For sanity check, let’s use some conditionals on a page view of your choice to see if it worked.

<% if current_user.super_admin? %>
  <h3>Welcome Super Admin</h3>
<% elsif current_user.company_admin? %>
  <h3>Welcome, Company Admin</h3>
<% else %>
  <h3>Welcome</h3>
<% end %>

If you sign up as a user3 you should see “Welcome Super Admin” on that page.

This is a simple implementation of single-role-based authorization using Rails 4 Enum. I hope you learned something.

Postgresql Did Not Work After I Updated to OS X Yosemite(With Solution)

This morning, I tried to start up an application on Rails with a Postgresql server and had this error:

PG::ConnectionBad: could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; (::1) and accepting
&gt;       TCP/IP connections on port 5432?
&gt;     could not connect to server: Connection refused
&gt;       Is the server running on host &quot;localhost&quot; (127.0.0.1) and accepting
&gt;       TCP/IP connections on port 5432?

Checked server.log and it showed me what directories it was looking for. I also went to where postgresql gets stored to confirm the suspicion.

cd /usr/local/var/postgres

The directories pg_tblspc pg_twophase pg_stat_tmp were missing. These directories are empty anyways but when you boot up your pg server the server looks for them. I think the Yosemite update got rid of these directories. So I created them again anyways.

mkdir pg_tblspc pg_twophase pg_stat_tmp

And added a .keep file in them so that I don’t have this problem in future OS updates.

touch pg_tblspc/.keep pg_twophase/.keep pg_stat_tmp/.keep

Voilá

Understanding URL Query Strings

URL, short for Uniform Resource Locator, is web address that you see on web browsers.

You may have seen urls that look something like this.

http://website.com/page?example=this

The part after the question mark is a query string. It appears at the end of a URL and provides a way to send additional information that a web server can use to control the output of its response.

Generally a query string is used to search a database for information, and return a single record.

For example, if you want to send a link to a youtube video but you wish to start the video at a particular time you can forward the link as such:

www.youtube.com/watch?v=iAJhtHDwcS4#t=39m29s

Where v=iAJhtHDwcS4 after the question mark identifies which video to show from the youtube server and t=39m29s after # is the minutes and seconds the video will start from. The character # is used here to further specify a subsection (or fragment) of the video.

Query strings can hold multiple value pairs. Simply add an ampersand, followed by another 
name, an equal sign and another value.

http://website.com/page?field1=value1&field2=value2&field3=value3...

There are some requirements for query strings. 
Most importantly, you can’t just use any symbol you want in a query string. 
Some characters like the ampersand(&), equal(=), space( ), and
 quote marks(“”) have special meaning in a URL. 
So if you send information that includes
 those special characters you need to encode them.
That is, translate them into a set of symbols that 
are safe and don’t conflict with their URL specific version. 
For example, ampersand is represented by “%26”. 
A space is converted to a plus(+). 
And a plus is converted to “%2B”.

URL encode and decode is a website that can decode url query string symbols in case you are curious: http://www.url-encode-decode.com/

When Stuck, Reverse It for Clarity

Recently I tried to create a ruby method that formatted a number to a string but comma separating large numbers.

For example: 100000 should result in 100,000 and 352456745 in 352,456,745

My first monstrous attempt was:

def number_to_string(number)
  num_str = number.to_s
  array_str_num = num_str.to_s.split(//)
  result = []
  array_str_num.each_with_index do |value, index|
    result << value
    result << ',' if index % 3 == 0
  end
  p result.join
end

But this returned “1,000,00” for 100000 which is NOT the end result I envisioned.

Then after twenty minutes of frustration, I left my room to quench my thirst. While I was drinking a nice cold beer my subconscious kicked in and I pictured the solution right away. I actually had to reverse the array of stringed numbers and add one to index to place the comma in the position that I wanted.

def number_to_string(number)
  result = []
  # reverse the string and then split it
  number.to_s.reverse.split(//).each_with_index do |value, index|
    result << value
   #add 1 to index to get the comma in the correct position
    result << ',' if (index + 1) % 3 == 0
  end
  result.join('').reverse
end

number_to_string(100000)
#=> 100,000

number_to_string(352456745)
#=> 352,456,745

Yes! It worked now. The code is ugly as fuck but it gave me the expected result. A friend once told me that if I was ever totally stuck at a problem, then I should reverse the data. When I was studying for the SAT for example, one of strategies for vocabulary retention I used was to say a word backwards out loud a few times. I have no idea why this tactic works, but apparently it helps programmers too.

So if you happen to feel hopelessly lost because of a hard problem, try reversing how you are viewing, approaching, or even reading it. Don’t forget that a cold beer on your side might also do the trick.

Thanks to @caffo for referring me to the problem. Hope we can have a cold beer someday.

Creating Your Own attr_reader and attr-writer

Have you ever wondered how you would create your own Ruby attr_reader and attr_writer.

Just so we are on the same page.

class Cat
 attr_reader :name
 attr_writer :name

 def initialize(<span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre=""><span class="hiddenGrammarError" pre="">name)
  @name</span></span></span></span> = name
 end
end

cat = Cat.new("Tobias")
cat.name #=> "Tobias"

cat.name #= "New Tobias"
cat.name #=> "New Tobias" 

attr_reader in the Cat class above is the same as if we create a method inside of it that the object’s the attribute name.

and attr_writer, as you have guessed but now allows the attribute to be written or assigned

class Cat

 def initialize(name)
  @name = name
 end

 def name
  @name
 end

 def name=(value)
  @name = value
 end
end

Build Your Own

Because attr_reader and attr_writer are pieces of code that creates code, we’ll have to enter the realm of metaprogramming.

For attr_reader, we will create an instance method that return its corresponding instance variable. And for attr_writer, we will code an instance method that assigns a value to an instance variable and returns it.

module Attrs
 
 def my_attr_reader(attr_name)
  define_method(attr_name) do 
   instance_variable_get("@"+attr_name.to_s)
  end
 end

 def my_attr_writer(attr_name)
  define_method("#{attr_name}=") do |value|
   instance_variable_set(“@“+attr_name.to_s, value)
  end
 end
end

In the module above I am using Ruby methods that let me define a method(define_method), get an instance variable(instance_variable_get) and set it(instance_variable_set). Don’t you love Ruby?

class Cat
 extend Attrs

 my_attr_reader :name
 my_attr_writer :name

 def initialize(name)
  @name = name
 end
end

cat = Cat.new("Tobias")
cat.name #=> "Tobias"

cat.name = "New Tobias"
cat.name #=> "New Tobias"

Voilá

Notice that I am using extend rather than include with the module Attrs. This is so my_attr_reader and my_attr_writer can become class methods.

Also, these are defining my_attr_reader and my_attr_writer once. In order to define multiple readers and writers at once like attr_reader and attr_writer you can do

module Attrs
 
def my_attr_reader(*attr_names)
 attr_names.each do |attr_name|
  define_method(attr_name) do
   instance_variable_get("@"+attr_name.to_s)
  end
 end
end

 def my_attr_writer(*attr_names)
  attr_names.each do |attr_name|
   define_method("#{attr_name}=") do |value|
    instance_variable_set("@"+attr_name.to_s, value)
   end
  end
 end
end

*attr_names lets you pass in zero or more attribute names. For each of those, a corresponding method is defined.

In case you are curious, the actual attr_reader and attr_writer in Ruby are implemented with functions written in C. When we simulate this behavior with our own Ruby methods we don’t get the advantage of these C functions.

And that is how you can replicate Ruby attr_reader and attr_writer with metaprogramming.
We used define_method, instance_variable_get, and instance_variable_set to define a method on a caller, get and set an instance variable.

This is just the tip of the metaprogramming iceberg.

Happy metaprogramming!

Passing Params With Rails Render AKA Lesson on Rails Render vs Redirect_to

Problem: User is directed to the purchase page of the website with a discount code
url/discount_code=trial5&product=greatest-product
While purchasing user forgets to add password, hit submit button
Rails(with Devise gem) sends user to url/users but now discount is gone!

This bug … well…bugged me for a morning. I hope this post helps others with the same problem.

This is how my RegistrationsController which inherits from Devise looked

  def new
    @user = User.new
    @purchase = Purchase.new
    super
  end

  def create
    @user = User.new(user_params)
    if @user.save
       redirect_to desired_path
    else
      @purchase = Purchase.new
      return render 'new'
    end
  end
 

I figured what I needed was to send the discount params to render ‘new’. How could I could that. First let me tell you the difference from redirect_to and render.

Render
We can give render the name of an action to cause the corresponding view template to be rendered.

For instance, if you’re in an action named update, Rails will be attempting to display an update.html.erb view template. If you wanted it to display the edit form, associated with the edit action, then render can override the template selection.

When render :edit is executed it only causes the edit.html.erb view template to be displayed. The actual edit action in the controller will not be executed.

Redirect_to

Redirect_to creates a new http request. When a user submits data it comes in as a POST request. If we successfully process that data we likely next display them the data they just created. We could display the article using render in the same POST that sent us the data. But it is not the Rails way. If the user hit the back arrow on the browser it will prompt the User to submit form data again?! when you successfully store data you want to respond with an HTML redirect. That will force the browser to start a new request.
That’s why in the create method in the registrations controller I want to redirect if @user is successfully saved. In this example, the application saves user if new user buys a product.

The Solution

After this brief lesson on the difference between render and redirect. The solution to persist discount when the new.html.erb page is rendered by loading the discount object before rendering the action.

  def new
    @user = User.new
    @purchase = Purchase.new
    super
  end

  def create
    @user = User.new(user_params)
    if @user.save
       redirect_to desired_path
    else
      @purchase = Purchase.new
      @discount = Discount.find_by(code: params[:purchase][:discount_code])
      return render 'new'
    end
  end
 

The params[:purchase][:discount_code] was being passed to the render new action but what I just needed was to load define @discount with the Discount object so my new.html.erb knew what to do with it.

Debugging is a skill that comes with time and good understanding of the framework and tools you are using to develop software. Slowly but surely, we are all on our way there.

Redirect User to a Specific Page After Sign In With Devise

Devise is a great gem that allows you to authenticate users and manage sessions in your application. At times you may want to overwrite the devise code a bit to perform a task your application needs. I had to do the same the other day and the solution might help you too if you happen to be wanting to have the user visit the current page after logging in.

Context:

User is on purchase page but is not logged in. If purchase attempt is made with an email already in the database, user is prompted to log in and soon after he/she needs to be redirected to that specific purchase page where he/she can complete the transaction.

After some research I used some of the code from the How to in the plataformatec/devise github page.

In the ApplicationController I wrote


after_filter :store_location

def store_location
  # store last url - this is needed for post-login redirect to whatever the user last visited.
    if (request.fullpath != "/users/sign_in" &&
        request.fullpath != "/users/sign_up" &&
        request.fullpath != "/users/password" &&
        request.fullpath != "/users/sign_out" &&
        !request.xhr?) # don't store ajax calls

      session[:previous_url] = new_purchase_path(params["product”]) if params["product"]
   
   end
 end

  def after_sign_in_path_for(resource)
    session[:previous_url] || root_path
  end

The code above is storing the session[:previous_url] only if params[“product”] exists.

Although this worked it was not the most elegant solution I could find. As far as I could tell devise stores previous url as session[:user_return_to] for a visitor tries to access a page that it does not have access unless user logs in.

Having this in mind I went to my registrations controller and I set session[:user_return_to] to the path of a purchase page.


class RegistrationsController < Devise::RegistrationsController

def new
    @user = User.new
    @purchase = Purchase.new
    session[:user_return_to] = request.fullpath
    super
  end

def create
    @user = User.new(user_params)
    unless @user.save
     @purchase = Purchase.new
      return render 'new'
    end
    sign_in @user
    session[:just_signed_up] = true
    session.delete(:user_return_to)
 end


In this Registration Controller session[:user_return_to] is set to request.fullpath in the method new. Request.fullpath by the way returns the string full path of the last url requested.
Just so the session[:user_return_to] is not saved to more areas than it should, I make sure it gets deleted in the create method. The session.delete(:user_return_to) is erasing the value of key “user_return_to”.

Variable Hoisting in Javascript

To hoist is to raise, to lift up according to the Merriam Webster dictionary. When I first encountered the term JavaScript Hoisting I thought that it should raise up something but I did not know what. Now I know and I would like to share it with you. JavaScript has the ability to hoist variables that is to say to lift them to the top of a particular scope.
Continue reading “Variable Hoisting in Javascript”