Creating A Snippet in Xcode

Submitted by swarut on Fri, 05/10/2013 - 11:58

Using snippet  can help improving speed, especially for a verbose language like Objective-C. 

Adding snippet is easy, just highlight the code you want and drag it to snippet window. Xcode is clever enough to know what is the right scope for the snippet. It will set the snippet scope automatically according to where your origin code scope is, and you are allowed to change it later.

After dragging the code to snippet window, new snippet item is added. You can open the edit window by clicking at snippet item. Here you can assign the completion shortcut that can be used with a normal code completion. Noted that the completion scope has an effect to the code completion. Two snippets can share a common shortcut if they were in different scope. Another important thing to note here is that you can add a place holder in the snippet where you can trigger a place holder replacement using tab key. To add a place holder, you have to wrap the place holder name with <# #> block. For example, the above highlighted subview container is written as <#subview container#>.

I found out that I already created lot of snippet.. the problem now is to remember the shortcuts, haha. Make sure you can remember yours!.

Setting Up Rails Application on Webfaction

Submitted by swarut on Wed, 05/01/2013 - 23:24

Around 3 months ago, I got noticed from a friend about Webfaction, a web hosting service I've never heard before. He told me that there is a 10 years celebration that offer 100$ back to the new customer who applies for its service at least a month.

Without hesitation, I quickly applied to Webfaction, and luckily, I got an award 100$ that grants a free service charge for 10 months service. I spent 10 minutes watching the introduction video there and found that getting basic rails app running is very easy. 5 more minutes, I got my hello world app run. Yippie... cheap, easy and very quick. However, I did not do anything more than this until a week ago that I decided to move one of my app from heroku to webfaction.

After spending a day setting up the stuffs, it's good for me to jot this down again.

Creating A New Rails Application on Webfaction

Webfaction admin panel is neat. I love it a lot more than Dreamhost. I can get my rails app created even I didn't read its document. Here are the steps:

Adding a new domain

From the top navigation, select domain/websites then select the domains link in secondary menu. You will the add domain button. just click it and enter the domain that you want. After that, the domain that you just created will appear in the list. With a basic set up, this is enough to go. Do not forget to configure your domain name to use webfaction's domain name server (see dns list at Account-Dashboard menu).

Adding a new Rails app

On the secondary menu, select websites link and click at add new website. Enter the name of the app, and pick the domain that you just selected. In the content block, click at 'add an application' - 'create a new application'. Pick the desired name, then select Rails in app category dropdown, and pick your desired option in app type. Now you can get your app set.

Deployment

Deployment to webfaction can be done in two ways: a.) to upload the file manually via FTP then manually run all rake stuffs and b.) to use Capistrano. I've never used Capistrano before, but the first choise sound painful, so I go with the latter one.

Setting up Capistrano

This part is well documented in help section on webfaction. You can simply follow this instruction. However, there are more configuration you need. Dow Drake wrote a very good guide on his blog. You can simply his guide. Unluckily, there are several things he missed to add. The one that you should consider is the way to install therubyracer gem.

I myself try running 'gem install therubyracer' via ssh, but it doesn't work. The installed gem is corrupted with a critical segmentation fault error. I've noticed that the error is raised from ruby 1.8, which is different from the ruby version I selected at the time I created my app. After exploring webfaction document, I found this stating that we can not simply use 'gem install' command as its will invoke ruby 1.8. If you wanted to use ruby 1.9, you have to change that command to 'gem1.9 install' instead. So now, we can install therubyracer gem with 'gem1.9 install therubyracer'.
Also, you need to create a public key for your user on webfaction and upload the public key to your target version control system.

After load of works you've done, now the deployment is easy just by calling 'cap deploy'. Anyway, please note that the deployment is made using the source you put in your repository. Thus, do not forget to push your change up before doing the deoployment.

Miscellaneous

Importing Data From Heroku PG

It is well written here. After exporting the data, you can import it to webfaction by accessing your app folder on webfaction via ssh. Then, instead of follow webfaction's guide, use the command written under 'Restore to local database'.

Database.yml

There are various ways to handle database.yml. The bad way you need to avoid is to track it with your version control system. I found this link giving a good guide on how to create database.yml on the fly, which look a lot better.

Final Words

Webfaction is good. All stuffs can be done easily. Most of the stuffs are written in the document and on its community. After spending a few hours, you will get used to it. The loading speed is fast. I can say that, after my free 10 months are ended, I will surely become a regular customer.

Git : Splitting Commit into Multiple Commits

Submitted by swarut on Thu, 04/11/2013 - 14:42

There might be a case when you want to split one commit into multiple commits, so that it is proper for rebasing. To do so, the interactive is a right tool to use.

The steps are as follows:

1. use git rebase -i xxxx where xxx the a hash of a specific commit  that occurs before the commit of interest.

2. place 'e' or 'edit' in front of commit hash (replace the 'pick' word with 'e' or 'edit').

3. close the editor, go back to the terminal, the rebase will be run and pause at the commit you want.

4. reset the head with git reset HEAD^. Then you can separately commit the files according to your need.

Good Bye 12, Welcome 13. Life Must Move on.

Submitted by swarut on Tue, 01/01/2013 - 05:43

2012 is passing? This is extremely fast, incredibly fast!!! I felt as if I just came back to my home after being a refugee from a flood crisis in 2011.

Lot of things happened this year, making this year a very remarkable period. Same as always, I would like to jot down the short stories of mine.

January

A month of house-cleansing after 2011 flood crisis. Luckily that we did clean a lot at the end of 2011's December. The thing we did this month are only finding new hoursehold stuffs and arrange them in a proper way.

On 17 January, I joined Oozou, a very great software house in BKK. I got a chronic pain at my left wrist due to the excess use of it during a refugee period (from a sandbag carrying and a wrong posture on working).

February

Due to the serious situation, I decided to tell her my feeling. She did not give me the exact answer and we did not call ourselves a lover. However, there were many good times happened. We had meals together, we met after work, everything seems to be ok. I am very happy.

For the work, I was put to SmartSupport project at Oozou. Boxbox for iphone is finished this month.

Capybara's Wait_until's Bug

Submitted by swarut on Fri, 11/30/2012 - 17:52

Ruined 4 hours finding a bug I did. The story began from the comment on github asked by a senior to use capybara's wait_until() instead of sleep() in the spec. Things work fine but one of the scenarios fails.
The original version of that scenario is shown below.

  1. scenario 'Replying a message', js: true do
  2.   visit messages_path
  3.   find('#inbox .nav-tabs li:first-child a').click
  4.  
  5.   sleep 1
  6.   within('#inbox .tab-content') do
  7.     page.should have_selector("#message_body", count: 1)
  8.  
  9.     fill_in 'message_body', with: "I'm replying you, Phat"
  10.     click_button "Create Message"
  11.  
  12.     sleep 1
  13.     page.should have_selector("div.message", count: 2)
  14.     page.find("div.message:last-child").should have_content "I'm replying you, Phat"
  15.   end
  16. end

I made a change to this code by using wait_until instead of sleep as follows.

  1. scenario 'Replying a message', js: true do
  2.   visit messages_path
  3.   find('#inbox .nav-tabs li:first-child a').click
  4.  
  5.   wait_until(1) do
  6.     within('#inbox .tab-content') do
  7.       page.should have_selector("#message_body", count: 1)
  8.  
  9.       fill_in 'message_body', with: "I'm replying you, Phat"
  10.       click_button "Create Message"
  11.  
  12.       wait_until(2) do
  13.         page.should have_selector("div.message", count: 2)
  14.         page.find("div.message:last-child").should have_content "I'm replying you, Phat"
  15.       end
  16.     end
  17.   end
  18. end

The problem then come from the wrong assertion on the last statement that expect the content "I'm replaying you, Phat" to be shown. As I tried to trace for an error, the message can't be created properly, so the expected item does not appear. I tried using find("#message_body").value and saw that there is the value I added out there. However, when the form is sent to the controller, the body is empty which cause the validation to be failed, and the item can't be saved. Finally, I tried to change the thing back a bit a found that the following code works.

  1. scenario 'Replying a message', js: true do
  2.   visit messages_path
  3.   find('#inbox .nav-tabs li:first-child a').click
  4.  
  5.   sleep 1
  6.   within('#inbox .tab-content') do
  7.     page.should have_selector("#message_body", count: 1)
  8.  
  9.     fill_in 'message_body', with: "I'm replying you, Phat"
  10.     click_button "Create Message"
  11.  
  12.     sleep 1
  13.     page.should have_selector("div.message", count: 2)
  14.     page.find("div.message:last-child").should have_content "I'm replying you, Phat"
  15.   end
  16. end

Thank Capybara's wait_until() to burn my time out a lot.... darn!

Separating Shared Static Variables in Rails Concern

Submitted by swarut on Thu, 11/29/2012 - 18:03

I run into to a case where I have to split the function of the model into concerns (modules). One thing that is done in refactoring is that I created two identical static variable in both concerns which looks like the following code.

  1. module Roles
  2.   extend ActiveSupport::Concern
  3.  
  4.   ROLES      = [:regular, :mentor, :portfolio_founder, :family, :staff]
  5.   BIT_MASKER = BitMasker.new(ROLES)
  6. end
  1. module VisibilityFiltering
  2.   extend ActiveSupport::Concern
  3.  
  4.   VISIBILITIES = [:regular, :mentor, :portfolio_founder, :family, :staff]
  5.   BIT_MASKER   = BitMasker.new(VISIBILITIES)
  6. end

So, there are two concerns here. The Roles concern will be mixined into User model and the VisibilityFiltering will be mixedin into Discussion model. You will see that both concerns have ROLES and VISIBILITIES that share identical value also the BIT_MASKER. How can we separated this to achieve DRY?

According to the team senior's refactor, he pushes these static variable directly into the model, and adds a delegate to handle the value retrieval. Basically, as the desired value are the set of role symbols that are held by a user, the roles are then added to User model as follows.

  1.   class User < ActiveRecord::Base
  2.     ROLES = [:regular, :mentor, :portfolio_founder, :family, :staff]
  3.  
  4.     has_roles ROLES
  5.   end

Simple as it's seen, the ROLES class variable is added. The thing to focus is the has_roles() method. It is not defined in the User model directly, but in the Roles concern.

  1. module Roles
  2.   extend ActiveSupport::Concern
  3.  
  4.   ROLES      = [:regular, :mentor, :portfolio_founder, :family, :staff]
  5.   BIT_MASKER = BitMasker.new(ROLES)
  6.  
  7.   included do
  8.     class_attribute :roles, :roles_masker, instance_reader: false, instance_writer: false
  9.  
  10.     delegate :roles_masker, to: 'self.class'
  11.  
  12.     module ClassMethods
  13.       def has_roles(roles, opts={})
  14.         self.roles = roles
  15.         self.roles_masker = BitMasker.new(roles)
  16.       end
  17.     end
  18.  
  19.     before_save :set_roles, :if => :verify_roles?
  20.   end
  21.  
  22.   def set_roles
  23.     roles = self.class.roles.select do |role|
  24.       method = "#{role.to_s}?".to_sym
  25.       self.respond_to?(method) && self.send(method)
  26.     end
  27.   end
  28.  
  29. end

Locator in Capybara::Node::Actions Is Not A CSS Selector

Submitted by swarut on Thu, 11/15/2012 - 18:16

3-4 hours wasted, with the help of my junior, I found that the parameter 'locator' that is supplied generally in Capybara::NodeActions's methods is not a css selector: we can not add # or . to convery the use of id and class. Instead, we should explicitly specify the id or the name without adding . or #. .... I wonder why it's not consistent. One reason is the ease of use (you can supply, id, name, or label), but this is not a worth trading in my opinion.

Instance_eval And Class_eval in Ruby

Submitted by swarut on Mon, 11/12/2012 - 16:31

The are two interesting methods for evaluating a string or block: instance_eval() and class_eval(). Both of them are interesting as they let you dynamically add extra variables or methods to a class or an instance.

class_eval is a class method to evaluate a passed string or block in the class scope. For example:

  1.   class Person
  2.   end
  3.  
  4.   Person.class_eval do
  5.     def hello
  6.       puts "hello"
  7.     end
  8.  
  9.     def self.race
  10.       puts "human"
  11.     end
  12.   end
  13.  
  14.   p = Person.new
  15.   p.hello # "hello"
  16.  
  17.   Person.race # "human"

instance_eval is an instance method that let you evaluate the code in an instance scope. Consider the following example:

  1.   class Person
  2.   end
  3.  
  4.   p1 = Person.new
  5.   p1.instance_eval do
  6.     def goodbye
  7.       puts "goodbye"
  8.   end
  9.   p1.goodbye # "goodbye"
  10.  
  11.   p2 = Person.new
  12.   p2.goodbye # NoMethod erorr

One thing that may be confusing is that the instance_eval and be called from the class too. But this confusion will be cleared if you recalled that every things in Ruby are object, including the Class. Like in this case, Person is a class, but it is also an instance of a Class class ( Person.class returns Class). Thus, insance_eval is available for Person too! We can also use instance_eval to add a class method to the class like:

  1.   class Person
  2.   end
  3.  
  4.   Person.instance_eval do
  5.     def race
  6.       puts "human"
  7.     end
  8.   end
  9.  
  10.   Person.race # "human"

Another thing that may look strange is to define a method using self.xxx in instance_eval.

  1.   class Person
  2.   end
  3.  
  4.   p = Person.new
  5.   p.instance_eval do
  6.     def yo
  7.       puts "yo"
  8.     end
  9.   end
  10.  
  11.   p.instance_eval do
  12.     def self.yo
  13.       puts "yo"
  14.     end
  15.   end
Both instance_eval here gives the same result (to add yo() to the instance). What's about if we defined both in the same block?
  1.   class Person
  2.   end
  3.  
  4.   p = Person.new
  5.   p.instance_eval do
  6.     def yo
  7.       puts "yo"
  8.     end
  9.  
  10.     def self.yo
  11.       puts "self.yo"
  12.     end
  13.   end
When call p.yo(), it will print out "self.yo" here. As both definition is the same, so the last one take a precedence.

Ruby : Include and Extend

Submitted by swarut on Fri, 11/09/2012 - 18:21

As ruby is a dynamic language, there are many alternative ways for you to modify classes or instances anytime you want. Two possible ways are to use include or extend. These methods seem to be alike? the answers are yes! and no!. Let's see the following code.

  1.   module Walkable
  2.     def walk
  3.       puts "I'm walking"
  4.     end
  5.   end

We have a Walkable module here which can be used to add walk to a target. Suppose we are going to make a Person class which can walk. We can do the following.

  1.   class Person
  2.     include Walkable
  3.   end
By doing so, walk() will be added as Person's instance method which you can call with person_instance.walk(). Include() will turn every methods defined in the module to the target's instance methods. Using Pry to for investigation, we get:
  1.   [10] pry(main)> ls Person
  2.   # Object.methods: yaml_tag_subclasses?
  3.   [11] pry(main)> ls p
  4.   # Walker#methods: walk
  5.   [12] pry(main)> 
What's about extend? What's it for? It actually modify the target method, however, for every targets (the use of include is limited to the Class).
  1.   class Dog 
  2.     extend Walkable
  3.   end
If you expected the above code to give a same result as how we use include(), you were wrong. By extending Walkable here, the walk() method is not added to the Dog's instance, but to the Dog itself. So, using Pry, you will see that walk is not Dog's class method.
  1.   [18] pry(main)> ls Dog
  2.   #Object.methods: yaml_tag_subclasses?
  3.   #Walker#methods: walk

The different thing between include() and extend() is that extend() will directly apply the method as at the target's level. If you called extend at class level, then the methods in the module are added as class method. If you called extend at an instance, the methofs in the module will then be added to as that instance's methods (only that instance, not for all instances of the same class). Thus, we can add walk() to a dog instance by:

  1.   class Dog
  2.   end
  3.  
  4.   dog = Dog.new
  5.   dog.extend(walk)

This is a basic for include() and extend(). There are also some extra usage of extend to supports many design patterns which I have to explore more. Will surely come back to write again soon ;)

Pages