Using Concern To Refactor Rails Model


Recently I’m working on upgrading a Rails 2.3 application to Rails 4.2 (Yes, it’s true, our company is still using 2.3 now, ( ‘Θ’)ノ( ‘Θ’)ノ( ‘Θ’)ノ). There are 5 models containing codes which are 90% the same. I tried to refactor them with Rails 4’s concern module.

What is concern

Rails 2.3 way

In Rails 2.3, if you extract code from model to a module, you need to create a module and put it into your /lib directory. To realize validations and class methods, you need to add a hook method in it, which was not an elegant way.

module Taggable
  def  self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
      # scope, validations, after_save .....

  module ClassMethods
    def find_with_tag(tag)
	 # .....

Realization with concern

In Rails 4, you can eaily realize it by creating a module extending ActiveSupport::Concern and include this module in your model.

module Taggable
  extend ActiveSupport::Concern
  included do
    scope :disabled, -> { where(disabled: true) }
  class_methods do
    def find_with_tag(tag)
	 # ...
  #put instance methods here


  • If you want to know which class is using this module in a class method, you can simply call self. For example, I want to cache class method find, then in my taggble module, I use
class_methods do
  def some_class_method(id)
    Rails.cache.fetch("#{}.find(#{id})", :expires_in => 15.minutes.to_i)
  • If it’s in an instance method, use self.class instead
def some_instance_method(id)
  Rails.cache.fetch("#{}.find(#{id})", :expires_in => 15.minutes.to_i)

And the code is more elegant (^m^ )クスッ.

Adjective Transformation in German

These days I was learning German grammar of transforming adjective. I learnt so many rules like, when the non which you describe is a accusative, if it’s male word append en, if it’s female or plural append e, if it’s neutral append es. But when the article is meine or keine and the word is plural, append en For nominative and dative phrase …..

Okay… My mood turns into (´Д`;)/ヽァ・・・

So I made a small program in Python to help me ‘remember’ which transformation of adjective to use (ノД`)ハァ.

def adj_transformation(adj, article, sex, case, plural):
    if case == 'accusative':
        if sex == 'male':
            adj += 'en'			
        elif sex == 'female' or plural:
            adj += 'e'
    	elif sex == 'neutral':
    	    adj += 'es'
    	elif (article == 'meine' or 'keine') and plural:
    	    adj += 'en'
    elif case == 'nominative':
     	if sex == 'male':
            adj += 'er'
    elif case == 'dative':
      	adj += 'en'
    return adj

adj = input('input adjective, regular transaformation only: ')
article = input('input article between ein, eine, keine, meine: ')
sex = input('choose sex of the non bwtween male, female, neutral: ')
case = input('choose case between nominative, dative, accusative: ')
plural = input('input 1 for plural, 0 for non-plural:')

target_adj = adj_transformation(adj, article, sex, case, plural)
print('correct transformation for ', adj, ' is ', target_adj)

If I want to know the correct form of alt (old) in the sentence Er is ein (alt) Mann, run this program:

input adjective, regular transaformation only: alt
input article between ein, eine, kine, meine: ein
choose sex of the non bwtween male, female, neutral: male
choose case between nominative, dative, accusative: nominative
input 1 for plural, 0 for non-plural:0
correct transformation for  alt  is  alter

The result will shown in your terminal, correct transformation for alt is alter

Now I have a ‘German mind’ へ(´∀`へ)ヨイヨイ♪(ノ´∀`)ノヨイヨイ♪.


自从lantern被墙,换了新的vpn以来,从google cdn, bootstrap cdn, cloudflare cdn加载资源速度变得超慢,请求CDN资源能花上半分钟,超级令人不爽(`‐●_‐´怒)。


  1. 把资源下载下来放在专门存放静态文件的文件夹中
  2. 如果网站主要面向的是国内的用户,换成国内的CDN也无妨。
  3. vpn开成全局模式。


  • 流行的js库和css框架基本上都有

  • 新浪和微软的CDN资源也很全,网上搜一搜就会有具体的资源地址

如果还是速度很慢的话, 一定是你家的宽带有问题啊ああああああああ (´¬O¬)

Setup SSH Login With Keygen In OSX

I’m quite tired with copy-pasting passwords from my Evernote every time I login to my company’s remote server. Especially my company uses a proxy server, which means I have to type two passwords to eventually login.


Then I found Keygen tool, which can help us login without typing password.


SSH Keygen is to generate a pair of key, putting the public key in your remote server, secret key in your local machine. If you are also using a Mac, ~/.ssh/id_ras is the default option of storing secret key, ~/.ssh/id_ras for public key. You can create many key pairs, and specify which pair to use by adding IdentityFile option in your ~/.ssh/config file.

Configurations With Single SSH Connection

1. generate keys in your local machine

~ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/user/.ssh/id_rsa): [press Enter]
Enter passphrase (empty for no passphrase): [press Enter]
Enter same passphrase again: [press Enter]
Your identification has been saved in /Users/user/.ssh/id_rsa.
Your public key has been saved in /Users/user/.ssh/
The key fingerprint is:
The key's randomart image is:
+---[RSA 2048]----+
|    ...          |
|     o . .       |
|    o o + o      |
|     + B B +     |
| .   .= S B o    |
|=o...o.o * o     |
|Bo+oE ... +      |
|=.++ ..  .       |
|o++oooo.         |

2. copy public key to your server

If you haven’t installed ssh-copy-id yet, use homebrew or Macports to install it. Then, copy your public key to your remote server, this step needs you type password.

~ ssh-copy-id -i ~/.ssh/ username@servername

3. Try login without password

Finally, make sure you can now login without password, and it’s done.


~ ssh username@servername
Last login: Sat Sep 17 15:00:45 2016 from XXX.XXX.XXX.XXX

Configurations for Multiple SSH connections

1. change ssh configuration

If you use a proxy server like my company does, edit .ssh/config file to change your ssh configuration (If there is no file named config in OSX, create a new one).

Host [servername]
ServerAliveInterval 90
ServerAliveCountMax 8
Hostname [username@servername]
User [username]
ProxyCommand ssh [username@proxyname] nc %h %p

2. generate key pairs

Same as Step 1 in Single SSH connection do.

3. copy your public key to both your proxy server and your real server

Same as Step 2 in Single SSH connection do.

3. Try login without password

Make sure you can login your real server password, and it’s done.


My Environment

OSX: 10.11.4

iTerm2: 3.0.9

My Journey in Meditation

My journey of meditation started two years ago, when I was a freshmen in collage. I read a book named “the mindful way through depression” by Zindel Segal. I started trying MBSR (Mindfulness-based stress reduction),it brings me life-transforming impacts, which can be called enlightenment, and thus my journey on meditation starts.

These are several meditating methods I tried:


MBSR (Mindfulness-based stress reduction) is a non-religious way to meditate. In this process, focusing on present moment, relaxing through deep breath, free from judgements are emphasized. When I first started doing this when I was a freshmen in college, I got wonderful experience, I started to realize how beautiful a tranquil present is. My concentration improved, I got more flows during studying and happier than ever before. I kept meditating in this way for the whole year on a weekly basis, and my happiness level goes like this.

I actually didn’t insist meditating after half year since I didn’t get any improvements since then. For me, who is passionate in seeking newest exciting things, it’s hard to keep those positive changes stay for a life time, because it’s becomes less exciting if we don’t feel there are more positive changes taking place.


Zen is one branch of buddhism originated in China, spread into various Asian counties, then became known as Japanese Zen. When I was an exchange student in Japan, I joined several zazen (座禅) assemblies hold by famous temples.

First I joined a half-hour Zazen activity in a 曹洞宗(そうとうしゅう)temple. People meditate facing a wall, and after a short period we will walk through the room (this is known as walking meditation, aiming to building up relationships between mind and body through simple daily activity). Then we read “Heart Sutra” (般若心经), the interesting thing here is it’s all written in Chinese characters but it sounds totally different when pronounced in Japanese. Finally came the monk explaining “Heart Sutra”, he told us everyone can be enlightened if he/she focuses on his/her real life, keeping doing good to others.

I joined another Zazen assembly in a famous 临济宗(りんざいしゅう) temple in Kyoto (see the official website), it’s a two days one night program. It was a snowy winter that time, and It was not such a pleasant stay there because we had to wake up at 4:30 am to start meditation. I tried my best to meditate but I was too sleepy. Anyway, scenery in the temple with snow falling down was quite beautiful.

Tibetan meditation

I did this follow a online course Tibetan Buddhist Meditation and the Modern World. Tibetan Buddhism is quite close to primitive India Buddhism. It emphasizes Buddhism such as unavoidable suffering and impermanence, and the first step to reduce suffering is to accept the fact that we are all suffering. For me, it’s a little difficult to fully engage in because it’s hard to understand these criteria without a Buddhism background knowledge.


In all, probably it will take many years to be enlightened, I enjoy so much with my way of trying all kinds of meditation. As a programmer who faces bugs everyday, it’s important to bring curiosity to code, also stay relaxed towards severe problems, then every line of code will become the deepest secret of universe.

life ( 4 )
music ( 1 )
programming ( 14 )
spirituality ( 1 )
中文 ( 2 )
language-learning ( 1 )

About Me

I'm a university student in the last year, also a web developer. I love exporing cultures, learning languages and making BGM music!