Creating A Snippet in Xcode
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
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
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.
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
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.
-
scenario 'Replying a message', js: true do
visit messages_path
find('#inbox .nav-tabs li:first-child a').click
sleep 1
within('#inbox .tab-content') do
page.should have_selector("#message_body", count: 1)
fill_in 'message_body', with: "I'm replying you, Phat"
click_button "Create Message"sleep 1
page.should have_selector("div.message", count: 2)
page.find("div.message:last-child").should have_content "I'm replying you, Phat"
endend
I made a change to this code by using wait_until instead of sleep as follows.
scenario 'Replying a message', js: true do
visit messages_path
find('#inbox .nav-tabs li:first-child a').click
wait_until(1) do
within('#inbox .tab-content') do
page.should have_selector("#message_body", count: 1)
fill_in 'message_body', with: "I'm replying you, Phat"
click_button "Create Message"wait_until(2) do
page.should have_selector("div.message", count: 2)
page.find("div.message:last-child").should have_content "I'm replying you, Phat"
endendendend
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.
scenario 'Replying a message', js: true do
visit messages_path
find('#inbox .nav-tabs li:first-child a').click
sleep 1
within('#inbox .tab-content') do
page.should have_selector("#message_body", count: 1)
fill_in 'message_body', with: "I'm replying you, Phat"
click_button "Create Message"sleep 1
page.should have_selector("div.message", count: 2)
page.find("div.message:last-child").should have_content "I'm replying you, Phat"
endend
Thank Capybara's wait_until() to burn my time out a lot.... darn!
Separating Shared Static Variables in Rails Concern
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.
-
module Roles extend ActiveSupport::ConcernROLES = [:regular, :mentor, :portfolio_founder, :family, :staff]
BIT_MASKER = BitMasker.new(ROLES)
end
module VisibilityFilteringextend ActiveSupport::ConcernVISIBILITIES = [:regular, :mentor, :portfolio_founder, :family, :staff]
BIT_MASKER = BitMasker.new(VISIBILITIES)
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.
class User < ActiveRecord::Base
ROLES = [:regular, :mentor, :portfolio_founder, :family, :staff]
has_roles ROLES
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.
module Rolesextend ActiveSupport::ConcernROLES = [:regular, :mentor, :portfolio_founder, :family, :staff]
BIT_MASKER = BitMasker.new(ROLES)
included doclass_attribute :roles, :roles_masker, instance_reader: false, instance_writer: false
delegate :roles_masker, to: 'self.class'
module ClassMethodsdef has_roles(roles, opts={})
self.roles = roles
self.roles_masker = BitMasker.new(roles)
endendbefore_save :set_roles, :if => :verify_roles?
enddef set_rolesroles = self.class.roles.select do |role|
method = "#{role.to_s}?".to_sym
self.respond_to?(method) && self.send(method)
endendend
Locator in Capybara::Node::Actions Is Not A CSS Selector
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.
XCode Can Not Compile Because of Availability.h
This is strange. After updating my xcode, I can not compile my project. The error shows that the problem come from availability.h. I have no clue how to fix this. After Googling, this post on stackoverflow saves me: http://stackoverflow.com/questions/12524771/xcode-wont-compile-to-simulator. In short, this can be solved by deleting the project folder in ~/Library/Developer/Xcode/DerivedData.
Instance_eval And Class_eval in Ruby
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:
-
class Person endPerson.class_eval do
def helloputs "hello"
enddef self.race
puts "human"
endendp = Person.new
p.hello # "hello"
Person.race # "human"
instance_eval is an instance method that let you evaluate the code in an instance scope. Consider the following example:
class Personendp1 = Person.newp1.instance_eval do
def goodbyeputs "goodbye"
endp1.goodbye # "goodbye"
p2 = Person.newp2.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:
class PersonendPerson.instance_eval do
def raceputs "human"
endendPerson.race # "human"
Another thing that may look strange is to define a method using self.xxx in instance_eval.
class Personendp = Person.new
p.instance_eval do
def yoputs "yo"
endendp.instance_eval do
def self.yo
puts "yo"
endend
class Personendp = Person.new
p.instance_eval do
def yoputs "yo"
enddef self.yo
puts "self.yo"
endend
Ruby : Include and Extend
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.
-
module Walkable def walkputs "I'm walking"
endend
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.
class Personinclude Walkableend
[10] pry(main)> ls Person
# Object.methods: yaml_tag_subclasses?[11] pry(main)> ls p
# Walker#methods: walk[12] pry(main)>
class Dogextend Walkable
end
[18] pry(main)> ls Dog
#Object.methods: yaml_tag_subclasses?#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:
class Dogenddog = Dog.newdog.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 ;)
