@yorzi

All about Ruby/Rails/Javascript/CoffeeScript/iOS/Ubuntu

Fork me on GitHub

Now My Blog Is Running on Octopress

Octopress

Octopress is owesome!

Last time I tried to migrate my wordpress blog to Jekyll, then I failed to find some beautiful theme. And when intridea cn blog was built using nanoc, I’d like to give it try, you know, I still gave nanoc up as I can not make the theme pretty by myself.

Days ago, I came across the octopress, I totally fell in love with its convenience and cool blog theme. I spent several hours to move my blog to github this afternoon. Oh my, Now I can write blogs in Markdown and deploy it to github.

Octopress has its official website with many valuable materials to help you get start and doing other regarding interesting things. Cool, hah? Try it out now!

Riding on Rails3 With Full Stack of Gems

NOTICE: Below post was released a month ago on Intridea Company Blog, also post here as a backup.

It’s been close to a year since Rails3 came out. Luckily, I’ve worked on several Rails3 projects after it’s released, so I’d like to share a stack of gems that I used in my previous projects. I guess they will give people a bit help while developing a new Rails3 app.

I don’t want to explain too much on these gems separately, well, most of the gems have good documents on their project wiki(every great gem should be well documented, right?). Instead, I just add regarding links to their repos so that you’d better take a further look while you really use it. In order to introduce the lists of gems clearly, I simply categorized them based on a rough structure.

Ok, here we start:

» Authentication

The above two are really amazing gems to speed up your authentication. Yes, I love both of them in different cases: ideally OmniAuth is better for applications which want to support multi-provider external authentication, so I’ve just added OmniAuth into RefactorMyCode Rails3 branch to take its auth benefits; Devise is totally powerful enough for classic authentication case. However, if you have too much your own business logic inside your login/registration/auth flow, you definitely need to make your own authentication.

» Access Control

Ryan is a star in Rails world, so his CanCan is really popular, which aims to do neat but powerful authorization. However, the declarative_autharization is also an option, actually, Ryan mentioned CanCan was inspired by declarative_autharization.

» Views/Page and Admin Scaffold

From a front-end perspective, I suggest you might need to try above gems to speed up and simplify your UI designing. For example on the admin section, it’d be great if you can apply your CRUD quickly to pages, that’s what rails_admin does. Surely, these gems won’t end all your UI problems, but it really helps when you doing prototype or being lack of some real designers.

» Quick SNS

Well, I don’t mean a whole solution of SNS or regarding feature, here theses gems can help you add the basic cross-object function rapidly, it increases your confidence to focus on designing over programming at the very beginning. Here I want to give a simple introduction to acts_as_favable, it allows for favorites refer to be added to multiple and different models.

» Form and Related Tools

Most of above gems are famous through <railscasts.com> created by Ryan. There are two pairs of options here: simple_form and formtastic / paperclip and carrierwave. I like all these solutions, you should pick up one to fit your project, if you want to know differences between each pair, get more details on their wiki :) Tiny is an HUGE gem for rich editing, I list it here to remind its exist, but I recommend you get the WYSWYG via some JS lib like CLEditor, it works gracefully.

» Searching Solutions

Talking about searching in rails, I think you have many words to say. Here I wanna roughly split these gems into two types: Object-based searching and Full-Text searching. I heavily recommend you use meta_search and/or meta_where as your model based searching, it can convert your form params directly to a search solution, that’s convenient. Full-Test searching depends on your case, but all these three gems(thinking-sphinx, acts_as_indexed, sunspot) are great.

» Pagination

No more will_paginate in Rails3, absolutely, the only option is kaminari.

» Background Work

There is one post to introduce resque clearly here, in that post, github staff mentioned their brief history of doing background jobs, so I think you can understand well the differences between delayed_job and resque solution.

» Status Machine

I like to use workflow a bit more, since it’s much natural to me, you definitely need one status machine to control your stable flow stuff, such as a registration flow status or a wizard-like features.

» Rack API framework

This gem is for adding API to Rails/Sinatra application. Michael gave people an awesome speech in RubyConf2010 on his Grape, here I suggest you should watch it to know more details about GRAPE. I believe you will fall in love with it.

» Memcached Client

These two gems are actually mainly written by one same author Mike Perham, he mentioned that Dalli is a high performance pure Ruby client for accessing memcached servers. It works with memcached 1.4+ only as it uses the newer binary protocol. It should be considered a replacement for the memcache-client gem. The API tries to be mostly compatible with memcache-client with the goal being to make it a drop-in replacement for Rails.

» Deployment and Monitor

I am not a system administrator, so every time talking about the regarding aspects will make me feel silly, I just try to describe tools which can help me out on unfamiliar area, that’s not bad, at least people like me, will do deployment and monitor quickly based on these gems, they do help.

» Cron job and Backup as a Pro

Above two gems are my favorites, before knowing these two gems, I have to write complex and stupid scripts to do backups that I am not familiar with. Cron job is also a pain in ass if you are not a system administrator. Now time changes, you, as a ruby programmer, can do the corn job and backup in ruby way, surely as a PRO. :)

» Testing Gracefully

Testing is always important, I know TDD and BDD are getting more and more popular, that means you have to own your super gun to make it happen. Right, here is a list of gems which can help you out, I didn’t cover all different levels of testing with these gems. Point is, rspec is my favorite framework for testing, factory_girl and faker are good supports. Anyway, test by your way.

» Toolkit

There are many handy gems which will give you convenience and power. Take above four as examples, ruby-debuy gives you a chance to check your running applications’ context at specific program point; hirb display your AR items in table view in console; cheat makes your terminal working as a pool of other gems’ manual; rails-settings-cached is for global configurations in Rails3 application. Yeah, throwing the brick out is to meet your GEMS.

How to find great gems?

First, you need to follow up Ryan’s railscasts, he is good at introducing new stuff in video. Second, you can go through great open source project’s Gemfile, yeah, it’s definitely the best way to come across valuable gems. Third, just subscribe github ruby trends to know what’s going on in Ruby/Rails community. There are also some other involving sites, like rubygems and railsplugins, you should take a glance when you free, I bet you will find useful gems.

It’s nearly the end of this post, this topic was originally shared with all Intridea China Team members during last Friday Teahour. You can find the PPT here. To share with more people, I turn it into this blog, I must miss many valuable gems in this list, so please comment your thoughts.

Weekly Updates : Javascript Rocks!

After quit from Idapted/Eleutian, I’d like to have a long term plan for writing blogs. However, as everything starts, it’s always hard. I thought it around, and finally decided to open my mind, and just try to start with a strong belief : Sharing! Then an idea comes out.

First of all, I think my weekly updates will help to share great things I came across or even I started to use, it has much fun to replay all these stuff, so I will do that in the weekend, that’s also part of my study review.

Ok, turn to the points:

  1. Now you must know JSLint. JSlint is a Javascript checker, which can help you ensure your JS’ quality. There are many great open source projects helping you to program in Javascript.

Sources: Github Proj: https://github.com/douglascrockford/JSLint Add JSLint to you TextMate: https://github.com/subtleGradient/javascript-tools.tmbundle

  1. Are you familiar with BDD? You should start to learn it now if you did not have a change to give it a try. Specially, if you are using Ruby/Ruby on Rails, I strongly recommend you try rSpec for the BDD. Back to the topic, I wanna share with you some similar BDD way in programming Javascript, jspec and Jasmine, obviously, they are cool. I just mention this as a reminder people who want to try interesting programming. I didn’t try them yet, but I guess I will do that in soon.

  2. JS in real-time application Node.js and NowJS

  3. Books to speed you up! • Javascript: The Good Parts (http://oreilly.com/catalog/9780596517748) • JavaScript Patterns (http://oreilly.com/catalog/9780596806767/) • High Performance JavaScript (http://oreilly.com/catalog/9780596802806/)

Javascript is a long journey, I am just on the start point. Anyway, exciting!

JS Note: setTimeout and setInterval

Yesterday, I discussed a JS issue with Blade, that I have to set up an automatic photo-switch effect on an existing page. I don’t want to change anything except adding a piece of javascript for doing that job because this page is already messy up by another engineer. Blade suggested I should use setTimeout for this effect.

* Case Study

The basic case is something like below(there are some other effects based on the structure and style, so don’t affect others):

会议城市:海口

时间:8月26日 14:00-18:00

地点:海口鑫源温泉大酒店

Now the task is to write a js to roll the cities and regarding images, how to make it happen?

* Solution with setTimeout

Actually, you can figure out this effect with setInterval as well. The difference between setTimeout and setInterval is how many times you want to run the function which is set as their parameters. setTimeout will execute the function only once when time is out. But setInterval execute the function repeatedly in certain interval which is set as a parameter.

Every time you should remember to clear the Timeout or Interval after finish your job through clearTimeout and clearInterval.

I have linked the regarding references for the four methods about, you should read the document and related samples to know more details.

More Resources: 如何在jQuery中使用 setInterval,setTimeout jQuery:Tab切换功能的集合

Real-Time Application With Rails3

I researched a little bit these two days about Real-Time Application(RTA), I found many useful solution to build real-time application.

First, a RTA is an application program that functions within a time frame that the user senses as immediate or current. The latency must be less than a defined value, usually measured in seconds. The use of RTAs is called real-time computing (RTC).

There are some example use cases of RTAs, including:

   * Videoconference applications
   * VoIP (voice over Internet Protocol)
   * Online gaming
   * Community storage solutions
   * Chatting
   * IM (instant messaging)

Mainly, I am interested in two solutions, which are Cramp based RTA and a NR2J(Node.js+Redis+Juggernaut+Jquery) solution, both of these two solutions have existing samples, I suggest you should go through all of them to understand RTA well.

Cramp based RTA Cramp is a ruby web framework with asynchronous feature, which is always running inside EventMachine reactor loop, there is a detailed introduction for it. A sample code is available here.

NR2J solution Introduction is here and sample code is here. I tried Node.js before, it’s getting popular recently, but I still don’t be used to implementing server side code with JS. I love Ruby and Rails anyway.

Other RTA resources: Real-Time/WebSocket/Rails3: http://laktek.com/tag/realie/ JSChat.org: http://jschat.org/

Zen Coding for TextMate

Bundles make TextMate as a super Editor, so if you love TextMate, you must love colorful bundles based on it.

I just find an interesting bundle to speed up your HTML/CSS coding, which is named as Zen Coding.

The core of this plugin is a powerful abbreviation engine which allows you to expand expressions—similar to CSS selectors—into HTML code. For example: div#page>div.logo+ul#navigation>li*5>a …can be expanded into:

The sytax is simple to understand, there is a sytax list here. You can also get more details about this bundle on its official site.

Enjoy it.

Dalli on Rails3

Today I tried a new pure Ruby memcahed client in one of my Rails3 projects, it’s named as ”Dalli”. It’s an excellent memcached client as Mike Perham announced in August last year. You can detect more details about it on its code. Dalli is just faster performance than memcache-client and easy to use in Rails3 or on Heroku.

Make sure you’ve installed 1.4+ memcached on your machine, then you can configure Dalli as what you did with memcache-client before: 1. add gem in Gemfile gem 'dalli' 2. Config the underlying cache store as dalli_store in production.rb

Memcached is delaulted on port 11211.

config.cache_store = :dalli_store, 'localhost:11211' 3. Now you will find the Rails.cache class is changed to Rails.cache.class:

Rails.cache.class == ActiveSupport::Cache::DalliStore 4. You can use it easily in you Rails3 application class Food < ActiveRecord::Base after_save :expire_food_caches

def self.all_view_types

  Rails.cache.fetch("food_types") do
      Food.all.map{|s| s.view_type}.uniq
  end

end

protected def expire_food_caches

   unless Food.all_view_types.include?(self.view_type)
       Rails.cache.delete("food_types")
   end

end end Note: Rails.cache.fetch() with a block will return the cached value if it exists, otherwise it will return the value and write cache with the value at the same time.

Resource about Cache: Scaling Rails :
http://railslab.newrelic.com/scaling-rails Caching with Rails :
http://guides.rubyonrails.org/caching_with_rails.html ActiveSupport::Cache::Store :
http://api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html#method-i-clear ActiveSupport::Memoizable :
http://ilstar.blogbus.com/logs/84754288.html#cmt

Love Git, Love Coding

“550,000 people hosting over 1,620,000 git repositories on github.com”

I’ve been using Git for a while, I wanna say, I love git and github very much.

One year ago, I was used to SVN as a version control approach. Yeah, SVN is great as a version control mechanism. You can quickly setup a svn server for your development because it’s an opensource project. However, Git/Github is greater to do version control and SNS coding.

Github now is a must-use website for my daily development work, I find interesting opensource projects on it, and I follow up the super stars (such as ”DHH” and ”Ryan Bates” etc.) and their daily contributions on the brilliant open-sourced projects.

Meanwhile, our Eleutian Tech Team moved to github several months ago, as it’s supporting team development well, and members in a team can share their updates easily and effectively. Personally, I am loving in the Gist recently, it’s really convenient to store and share any valuable code snippets on it. It’s also handy with the embed script for displaying it on your blog. (but it seems the gist won’t display in RSS feed because my last post with a gist didn’t display in the feed.)

There’s one more cool feature that is impressive when I first know it. It’s “Blame” mode on a piece of code. Everyone’s editing history and commit number is on the page, I guess it can be a testify to “Blame” the bad code, that’s funny.

I bet you will love in Git and github if you are an active programmer, or if you like to share code or projects, you’d better to give github a try. That’s unbelievable helpful to good programmers.

Resource: Pro Git: http://progit.org/ Why you shoud switch from Subversion to Git:http://thinkvitamin.com/code/why-you-should-switch-from-subversion-to-git/

Deploy Rails3 App in Sub-directory

Last weekend, seven and sonic did a great job to move all Idapted servers to a new datacenter, that’s really a fabulous movement. Seven just wrote it out on his blog, if you want to know more about this migration, please go through his post. Anyway, in this post I wanna share a simple but valuable tip about deploying Rails3 app in sub directory.

More resources: 1. Rails 3, Unicorn and RAILS_RELATIVE_URL_ROOT:
http://summit360.co.uk/2010/09/rails_3_unicorn.html 2. Enabling Rails 3 for your application:
http://www.nirvaat.com/ruby-on-rails/enabling-rails-3-for-your-application/ 3. Rails 3 routes in subdirectory:
http://community.webfaction.com/questions/1364/rails-3-routes-in-subdirectory

When Generating a Public Website

To backup a great topic, I pasted the following content to reminder me the public website concerns, it’s not a summary by myself, I picked them up from stackoverflow.com.

Interface and User Experience

  • Be aware that browsers implement standards inconsistently and make sure your site works reasonably well across all major browsers. At a minimum test against a recent Gecko engine (Firefox), a Webkit engine (SafariChrome, and some mobile browsers), your supported IE browsers (take advantage of theApplication Compatibility VPC Images), and Opera. Also consider how browsers render your site in different operating systems.
  • Consider how people might use the site other than from the major browsers: cell phones, screen readers and search engines, for example. — Some accessibility info: WAI and Section508, Mobile development:MobiForge
  • Staging: How to deploy updates without affecting your users. Ed Lucas’s answer has some comments on this.
  • Don’t display unfriendly errors directly to the user
  • Don’t put users’ email addresses in plain text as they will get spammed to death
  • Build well-considered limits into your site - This also belongs under Security.
  • Learn how to do progressive enhancement
  • Always redirect after a POST.
  • Don’t forget to take accessibility into account. It’s always a good idea and in certain circumstances it’s a legal requirementWAI-ARIA is a good resource in this area.

Security

Performance

  • Implement caching if necessary, understand and use HTTP caching properly as well as HTML5 Manifest
  • Optimize images - don’t use a 20 KB image for a repeating background
  • Learn how to gzip/deflate content (deflate is better)
  • Combine/concatenate multiple stylesheets or multiple script files to reduce number of browser connections and improve gzip ability to compress duplications between files
  • Take a look at the Yahoo Exceptional Performance site, lots of great guidelines including improving front-end performance and their YSlow tool. Google page speed is another tool for performance profiling. Both requireFirebug installed.
  • Use CSS Image Sprites for small related images like toolbars (see the “minimize http requests” point)
  • Busy web sites should consider splitting components across domains. Specifically…
  • Static content (ie, images, CSS, JavaScript, and generally content that doesn’t need access to cookies) should go in a separate domain that does not use cookies, because all cookies for a domain and it’s subdomains are sent with every request to the domain and its subdomains. One good option here is to use a Content Delivery Network (CDN).
  • Minimize the total number of HTTP requests required for a browser to render the page.
  • Utilize Google Closure Compiler for JavaScript and other minification tools
  • Make sure there’s a favicon.ico file in the root of the site, i.e. /favicon.icoBrowsers will automatically request it, even if the icon isn’t mentioned in the HTML at all. If you don’t have a /favicon.ico, this will result in a lot of 404s, draining your server’s bandwidth.

SEO (Search Engine Optimization)

  • Use “search engine friendly” URL’s, i.e. use example.com/pages/45-article-title instead ofexample.com/index.php?page=45
  • Don’t use links that say “click here”. You’re wasting an SEO opportunity and it makes things harder for people with screen readers.
  • Have an XML sitemap, preferably in the default location /sitemap.xml.
  • Use <link rel="canonical" ... /> when you have multiple URLs that point to the same content
  • Use Google Webmaster Tools and Yahoo Site Explorer
  • Install Google Analytics right at the start (or an open source analysis tool like Piwik)
  • Know how robots.txt and search engine spiders work
  • Redirect requests (using 301 Moved Permanently) asking for www.example.com to example.com (or the other way round) to prevent splitting the google ranking between both sites
  • Know that there can be bad behaving spiders out there
  • If you have non-text content look into Google’s sitemap extensions for video, etc. There is some good information about this in Tim Farley’s answer.

Technology

  • Understand HTTP and things like GET, POST, sessions, cookies, and what it means to be “stateless”.
  • Write your XHTML/HTML and CSS according to the W3C specifications and make sure they validate. The goal here is to avoid browser quirks modes and as a bonus make it much easier to work with non-standard browsers like screen readers and mobile devices.
  • Understand how JavaScript is processed in the browser.
  • Understand how JavaScript, style sheets, and other resources used by your page are loaded and consider their impact on perceived performance. It may be appropriate in some cases to move scripts to the bottomof your pages.
  • Understand how the JavaScript sandbox works, especially if you intend to use iframes.
  • Be aware that JavaScript can and will be disabled, and that Ajax is therefore an extension not a baseline. Even if most normal users leave it on now, remember that NoScript is becoming more popular, mobile devices may not work as expected, and Google won’t run most of your JavaScript when indexing the site.
  • Learn the difference between 301 and 302 redirects (this is also an SEO issue).
  • Learn as much as you possibly can about your deployment platform
  • Consider using a Reset Style Sheet
  • Consider JavaScript frameworks (such as jQueryMooTools, or Prototype), which will hide a lot of the browser differences when using JavaScript for DOM manipulation

Bug fixing

  • Understand you’ll spend 20% of the time coding and 80% of it maintaining, so code accordingly
  • Set up a good error reporting solution
  • Have some system for people to contact you with suggestions and criticism.
  • Document how the application works for future support staff and people performing maintenance
  • Make frequent backups! (And make sure those backups are functional) Ed Lucas’s answer has some advice. Have a Restore strategy, not just a Backup strategy.
  • Use a version control system to store your files, such as Subversion or Git
  • Don’t forget to do your Unit Testing. Frameworks like Selenium can help.

Lots of stuff omitted not necessarily because they’re not useful answers, but because they’re either too detailed, out of scope, or go a bit too far for someone looking to get an overview of the things they should know. If you’re one of those people you can read the rest of the answers to get more detailed information about the things mentioned in this list. If I get the time I’ll add links to the various answers that contain the things mentioned in this list if the answers go into detail about these things. Please feel free to edit this as well, I probably missed some stuff or made some mistakes.

Check out its original post thread at http://stackoverflow.com/questions/72394