# All talk but no code...

## My Presenter Library for Rails

Naming view helper methods in Rails can be difficult. What do you think about the following helpers?

Since all helpers live under the same scope, they all need to be named differently to avoid name collision. This can become tedious as the number of models grow.

For me personally, these two issues always bugged me when creating a helper method:

1. I don't know where to put the helper method.
2. I worry about name collision.

#### Reinventing the wheel

People thought of ways to organize these helper methods, which are now commonly called presenters, decorators or exhibiters.

One school of thought uses decorators to append functionalities on top the ActiveModel, draper, display_case and active_decorator being the three most well-known solutions.

Built-in helper methods all reside within view-context objects. So for presenter to work it needs access to the view-context object. However passing it for every helper call can be tedius. I liked how draper and active_decorator grabs that view_context for you, so you won't have to keep passing it to presenter when calling it.

However I see that its effort in decorating the model object can easily leak. For example would you remember to also decorate the association objects?

I wanted something else instead, a presenter object which contains only the helper methods. I add a presenter() method in the model object to access the presenter object. No decoration and less issues. The presenter() object also takes care of caching the presenter object, so you only instantiate a presenter per model once.

So I made my changes on top the active_decorator, and called it lulalala_presenter (all the good names are taken already).

#### Usage

First install by putting this in the Gemfile:

Say you want to add a title() helper method for auction, which takes care of truncation and html cleansing. I simply create a AuctionPresenter class. Remember to subclas it with LulalalaPresenter::Base:

And then in the view I call it like this

#### Less magic

I think it is good to start with less magic, but allow user to add magic if they want more convenience.

By default you use h to access all the build-in helper methods, and model to access the model object. If you are lazy you can choose to add stuff in your presenter so you can type less. For example you can delegate a few model attributes:

You can probably also automatically delegate everything to models using other delegation libraries.

#### Conclusion

At the end I quite like my results. For the top example, now I have

Having to type .presenter when calling helpers isn't so bad as I first thought. This makes it very obvious that the method belongs to presenter, so you won't ever mix up a helper methods with model methods.

My two goals are also fulfilled. If I need an og_image_tag helper for my auction, I immediately know I should put it in the AuctionPresenter, and I can name it without worrying about prefixing model names.

## Apply SEO-friendly url only to show path

Rails developers often use to_param to add more information to the url. Taking this very page as an example:

http://logdown.com/account/posts/290439-seo-and-to-param

We can clear get an idea of what this page is about. Therefore search engines favours this kind of urls.

However, if we just override to_param, we would also see other urls getting changed. One most notable example would be edit path:

http://logdown.com/account/posts/290439-seo-and-to-param/edit

I think this can cause issues as the seo-friend param can potentially get very long. Then it would be difficult to notice the edit in the url. Also it may not be that useful to do SEO on action urls (rather than the content urls). We probably will never want edit page to appear on search engines.

I think instead, we should conditionally do SEO on urls that needs it. One way to do this is to have our own version of the url helpers. For example, we can define post_url and post_path like this:

This means only show/delete/update paths will be SEO friendly. Other paths (especially custom actions) will be unaffected.

## Rails 4.1 upgrade and FactoryGirl.create with association

I was trying to upgrade from Rails 4.0 to Rails 4.1. Some specs broke, and I found a small behaviour change.

So my user has_one profile.

Prior to my upgrade, the profile association will not be loaded before/after FactoryGirl.create call.

However after Rails 4.1

This means I have to be careful to not have stale profile in tests, calling reload more often.

P.S. my factory_girl gem has remain unchanged in version 4.4.0 and factory_girl_rails gem in 4.4.1. So this is solely due to Rails behavior change.

## 從 sqlite 轉換到 postgresql

sqlite 的 data dump 其實需要更改不少地方，才能用在其他資料庫。這部份很容易犯錯，所以我想找其他方法。

## 注意的地方

• 有使用 foreign key 的話，記得依照 key 的 dependency 把匯入的順序調整，被 Key 指向的 table 移到前面。
• 匯出前也要先把 orphan record 先刪除（就是有 foreign key 指向已經不存在的資料時）
• 匯入前，先轉換資料庫然後跑 migration
• 匯入後，每個 table 的 id 並不會自動設成從目前最大的 id 開始繼續遞增。必須跑類似 ALTER SEQUENCE product_id_seq RESTART WITH 1453; 來對每個 table 一一作設定，不然的話可能新增的 record 會從前面沒有的 id 開始建立。
• 以前在 MySQL 或是 Sqlite 時似乎沒有指定 order 就會以 primary key 自動作排序。但是在 Postgresql 我發現丟回來的東西順序不是這樣（我看到的是相反的 id desc）。這代表 query 都得手動加入 order(:id) 才能確保跟以前一樣以 id desc 排序。

## Middleware模式的隨想

When I am integrating offsite payments in ActiveMerchant, I always need to provide an endpoint to receive payment notificaiton from gateway providers. After a couple of projects, I have come up with a best-practice to do it, and I thought this might be useful for others.

I have a PaymentNotification class solely to record notifications. This is because I want to decouple the persistence of notification from the order status change. If something goes wrong when I change Order, the notification will still be safely persisted in the database for later analysis.

As you can see, the controller action is pretty light. It only saves the notification. The notification request is setup so it contains order_id and payment method.

The interesting part is the PaymentNotification model. It has a few columns for persisting different information (mostly serialized). It is also linked to Order, for easier analysis.

The process method is to check the notification's validity and trigger order status update. It is to be called separately (maybe via a scheduled job). A few kinds of custom exceptions may be raised during process, because they are handled differently. Either way, errors will be recorded in the errors column.

Any improvement is welcomed :D

## 歐付寶有 < 跟 & 就會認證失敗

<input id="TradeDesc" name="TradeDesc" type="hidden" value="&lt;&amp;" />

THX.

API 文件並沒有標明不能特別限制特殊符號，經過測試其他特殊符號都可以使用。但是就只有 <& 不行。是說這兩個符號也沒有特殊到哪裡去，要是英文商店用個 & 字元也是很正常的吧。

THX.

## ActiveMerchant / offsite_payments gem needs to improve

ActiveMerchant is a very useful library for connecting to payment gateways. However it is also quite dated, with many flaws, and lack of proper documentation in one part (offsite-payment). In my experience, I feel it can be improved in the following ways:

The name "integration" in confusing, and makes it diffcult to search online. The gem should be split into two, one for on-site payment (gateway/billing module), and one for off-site payment (integration/Billing::Integration module). This is because the two are very different ways of paying. It can be confusing when you search for solutions but it turns out to be not what you want. Seems Shopify is alreadying doing that, splitting the offsite-payment module into its own gem. Good move!

The semantic of common fields in form helper need to be defined. Otherwise implementors will choose different names for the same concept, greatly reducing the interchangeability between gateways. Some consistency issues should also be fixed. For example in Paypal we pass our order id as the "order" field, and Paypal notification will return that as item_id attribute. This mismatch is confusing.

The gross() currently does not specify a return type. Paypal returns a string. Base class says it should "the money amount we received in X.2 decimal". Though there is a amount() method for returning a money object, the gross() method should still specify the return type to avoid inconsistencies when switching gateways.

The base framework code should be separated from gateway implementations. Users usually just want two or three gateways out of the 50 implementations. Having a separate repository per gateway also makes it easier to document gateway specific changes and settings in separate readme files.

There should be a check() method in the notification. It acts as the central method to check if the notification is valid. Currently there are many which implemented the acknowledge() function. However not all providers provide an API to verify the notification. With the generalized check() method it can call acknowledge() if it is implemented.

Adding hooks for form helper would be helpful. Many gateways require post-processing such as adding a checksum field. A hook would allow the interface to automatically call these post-processing instead of the developer having to remember calling them in view.

## Markdown 或是 LATEX

Ｍarkdown 跟 LATEX 其實要解決的是不同的問題，也就是你要產生需要排版有頁數的實體文件，還是就只是一長串的文件？

LATEX 要解決的一個核心問題就是必須解決分頁時放置圖片或是表格的問題。如果沒有分頁，那麼這些東西自然依照文字排放往下排即可，可是因為這些東西要是正好排在分頁邊緣時，不能腰斬只顯示一半。此外，因為分頁所以排版上也冒出許多限制，這些都是 LATEX 的強項。