Rails: Remove a table

I created a table that I did not need. I needed to remove the table. The actual terminology is to Drop a table. The way you do this is to create a new migration.

rails g migration DropProducts

In my case, I created a products table when I didn’t needed it. Inside the migration, I do the following.

class DropProducts < ActiveRecord::Migration
  def change
    drop_table :products
  end
end

fin

Terminal: Copy a folder

Similar to the way you would delete a folder with:

rm -rf folder_name

You must include -rf when doing a copy or cp

cp -r folder_name new_folder_name

-rf stands for recursive force. This will include the directory as well as all the files and subdirectories within.

Railscast – 002 Dynamic find_by Method

The GitHub Repo

I was arguing if this episode was even worth creating a project for. Decided to create since it would be so quick to make.

The episode talks about how you can replace:

class TaskController < ApplicationController
  def incomplete
    @tasks = Task.find(:all, :conditions => ['complete = ?', false])
  end

  def last_incomplete 
    @task = Task.find(:first, :conditions => ['complete =?', false], :order => 'created_at DESC')
  end
end

With:

class TaskController < ApplicationController
  def incomplete
    @tasks = Task.find_all_by_complete(false)
  end

  def last_incomplete
    @task = Task.find_by_complete(false, :order => 'created_at DESC')
  end
end

Attention should be drawn to the find_all_by_complete method used. This is a shortcut for the first find methods with all of the options passed in. The word that follows the by is the column that is in the Tasks table. You can then pass in the value of the records for that column you want returned. If you want only a single record that matched the conditions, then you would omit the all from find_all_by_complete making it find_by_complete. If you were finding a record by its name, then you doing this:

Task.find_by_name('bob')

Railscast – 016-Virtual-Attributes

The GitHub Repo
The Heroku app

I found this episode useful. It showed me that a model’s attribute does not have to be directly on one of the table’s columns. Not only did I learn about virtual attributes, but I also improved on associations, validations, and callbacks.

The virtual attributes were easy enough to understand. You create a setter and getter method named with the desired virtual attribute name. In the episode’s case it was price_in_cents sort of aliased to price_in_dollars. Within the method you could change the value of the virtual attribute to match whatever is in the database.

def price_in_dollars
  price_in_cents.to_d / 100 if price_in_cents
end

def price_in_dollars=(dollars)
  self.price_in_cents = dollars.to_d * 100 if dollars.present?
end 

Strftime

This is the first time I used the :strftime method, but it is not too dissimilar to how I have formatted dates within the terminal.

Rails 3 to Rails 4

One thing to note, these videos date back sometime before the current Ruby on Rails 4.0 release, thus I must convert some of the techniques shown in the videos into whatever they translate to in the new version of the framework. An example of this is the use of attr_accessible. Attr_accessible has been incorporated in the the strong parameters update in Rails 4. So instead of

attr_accessible :name, :price_in_dollars, :released_at_text, :category_id, :new_category, :tag_names

You would do the following in the ProductsController

def product_params
  params.require(:product).permit(:name, :price_in_dollars, :released_at_text, :category_id, :new_category, :tag_names)
end

Associations

I knew I was a little weak with associations, so when I saw that this project had categories, products, tags, and taggings, I decided to make everything from scratch. I followed along with the schema to create the migrations needed. When creating a has_many and belongs_to relationship you always put the parent id onto the child’s table. Example:

class Product < ActiveRecord::Base
  belongs_to :category
end

class Category < ActiveRecord::Base
  has_many :products
end

The schema would look like this:

 create_table "categories", :force => true do |t|
    t.string   "name"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
  end

  create_table "products", :force => true do |t|
    t.string   "name"
    t.integer  "category_id"
    t.datetime "created_at",     :null => false
    t.datetime "updated_at",     :null => false
  end

This relationship is similar to the taggings, tags, and products relationship. The taggings has the foreign key for both the tags and products. The difference is that products has_many tags through the taggings model.

Validations

I liked how Ryan Bates created his own custom validation method with check_released_at_text The validation first check if the released_at_text instance variable is present and the time is nil. If it is, then add to the errors object with a custom error message. If there was an ArgumentError, then again the errors object is appended with the custom error message. Creating a custom validation adds more control than if some of the more generic validation methods like presence or length.

Callbacks

The callbacks created this episode used before_save. The reasoning for this is to actually save the instance variable’s values to the database in the correctly formatted form. In the create_category callback it actually creates a new category record.

  def create_category
    self.category = Category.create!(name: new_category) if new_category.present?
  end

Pluck

The first time I’ve seen the pluck method used. I looked it up and found that tags.pluck(:name) is a shortcut for tags.map(&:name). The goal is to get only a certain attribute from the model.

Those where the noteworthy parts of the episode.

SystemStackError: stack level too deep

I was going to update a record through the form, but when I submitted the form, I was presented with the following error

SystemStackError in ProductsController#update
stack level too deep

After looking around I found this question on StackOverflow with a helpful answer. stack level too deep error

This error generally happens when you accidentally recursively changing an attribute. If you have a username attribute in User model, and a virtual attribute named username, that is directly changing the username, you end up calling the virtual, the virtual calls the virtual again and so on.. Therefore, take a look on whether something like that happens somewhere in your code. – Spyros

I looked within my Product model, and sure enough I was calling a virtual attribute recursively. Hate typos.

def price_in_dollars=(dollars)                                           
  self.price_in_dollars = dollars.to_d * 100 if dollars.present?         
end

I changed price_in_dollars to price_in_cents and everything was fixed.

def price_in_dollars=(dollars)                                           
  self.price_in_cents = dollars.to_d * 100 if dollars.present?         
end

Make all Railscast Projects

I came across a post about someone asking what was the best way to learn Ruby on Rails via Quora. One answer suggested one of the best ways was to follow along with every Railscast project then upload the repo to both GitHub and Heroku. I liked the concept, so I have bought a membership of Railscast and have downloaded all the episodes.

While the goal is to create every project, I will watch every episode and decide if it would be useful to make the project or not. Some episodes are just small tips, so creating a new project just to use that one tip seems inefficient.

I might be repeating what episodes showed, but I found that writing about what I learnt from the episode solidifies what I have learnt. Similar to language learning, you need a balance of input and output to get good at any skill. The input here are the Railscast episodes and the things I look up to finish the apps, and the output are the working app and the blog post.

The first few days of trying this method, I created an app then wrote up the blog post. This takes a lot of context switching between tasks. I am currently trying to go through as many Railscasts in one day, then writing about each the following day.

Change the data type of a column in the database

I accidentally created a column in the database with the datatype of string when it needed to be a integer. I’m on the BART, so I didn’t have internet. Fortunately I have a copy of the Rails repo and its guides. I opened up migrations.md and read to the changing tables section. Saw the following:

change_table :products do |t|
  t.remove :description, :name
  t.string :part_number
  t.index :part_number
  t.rename :upccode, :upc_code
end

I followed this and created the following migration:

change_tabe :products do |t|
  t.remove :price_in_cents
  t.integer :price_in_cents
end

Generate a scaffolded controller after making model

I’m starting to post each time I have to look up something online. I first created a products model, then I migrated the database. I needed a normal scaffolded ProductsController, and I found a StackOverflow question. “rails generate scaffold” when model already exists

I didn’t know there was so many generators until I saw the output of rails generate -h

controller
generator
helper
integration_test
mailer
migration
model
observer
performance_test
plugin
resource
scaffold
scaffold_controller
session_migration
stylesheets

Typed in rails g scaffold_controller product, and it did as it was supposed to do.

Find Anyone’s Email: A Ruby Script

Rapportive is no longer available, so this script no longer works

I just released my Find-Any-Email Ruby Script online a few days ago, and it has been picked up by a few people in the ruby community. In a little over a day, I have 101 stars, 15 forks, and over 3,000 views on the GitHub repo. Its my first time experiencing people using something I made at this scale.

That being said, credit must be given where credit is due. I stand on the shoulder of giants after all. I borrowed heavily from Jordan Wright’s Rapportive.py. I wasn’t too familiar with Python, so I ported it into Ruby. I got the idea for the name permutations from Distilled.net’s post about How To Find (Almost) Anybody’s Email Address. And honorable mention to Eric Wang’s post about how to get a startup job for a ‘guide’ on getting a job and hustling.

I used the manual process of hovering over each email within gmail with the rapportive plugin previously to get my internship in Tokyo. Now that I’m in San Francisco, I thought I’d repeat the process again here. After finding companies I would be interested working for, I searched for the highest person’s email address. Then I sent them a cold email. Not surprisingly some ignored my email, but some answered and were interested in meeting. After hovering over hundreds of email address, I got tired of it.

Then I remembered I knew how to program, so I could programmatically solve my own problem. That’s when I searched for Rapportive API and found Jordan Wright’s blog post. It’s a great read and way to learn how a security engineer works. Because of the similarities between Ruby and Python, I could fairly easily understand the code. Then I started searching for what the Ruby equivalent would be for some methods. Methods like Python’s request() to Ruby’s OpenURI library. I found porting a Python script into Ruby to be good exercise to understand both languages better.

Problems arose when I tried to port everything one-to-one. Some requests to Rapportive’s API were giving 429 and 403 errors. 429: Too many Requests, 403: Forbidden. In order to by pass this, I implemented a begin and rescue block with exponential backoff. Initially I didn’t even know about the concept of Exponential Backoff until I went a meetup downtown and someone suggested that I use it. I’m really grateful for learning about that because it’s so useful when working with APIs! Another note about the 429 and 403 errors, most of the time if these errors comes up, then the email does not have a person associated with them.

The emails were created using the permutate method which is given the arguments of first_name, last_name, and domain. Implementing the permutations and a method to loop each one into the request was the biggest contributions I had to this emailing finding technique. I was going to allow for the middle name argument, but decided against it after running into some problems when its left blank. The permutate method bothers me alittle because I can’t help but feel there is a better way of doing this. I have opened a question on stackoverflow, but I have not received a decent answer. In this part, I’m open to suggestions.

Comments have arisen about the morality of making such a script public. My response is that this technique has already be public for a long time before this script was published. Since this script borrows heavily from Rapportive.py, there is nothing that prevented people from doing this before. Even at a lower level, people aren’t going to email someone without a purpose. Example, Mark Cuban’s email is public, but I’m not going to spam him because it would be a waste of his and my time if I have nothing interesting to email about. It really just gives this technique exposure to Rubyist.

Another point is that this script is admittedly imperfect. Some valid email address are being skipped because Rapportive’s API is returning an error. You could possibly cross reference Rapportive’s API with gravatar’s or any other services’s API. Also every valid email is outputted instead of the one that you’re really looking for. To solve this, you could check that the name in the response matches with the inputted first and last name. I have opened bug issues on GitHub noting these problems. Because of these issues, I use this script as the first pass before doing it manually.

This the first time I pushed something online where I got this attention. It gets me excited to make more things and releasing it to the public.

Questions, comments, or concerns?
Follow me on Twitter¯

Bitcoin donation appreciated
18fZ6muNmBrtENMZhnAjUw8eEsytmY8mZJ