01 September 2009

Paypal Express & Active Merchant diagram

Paypal Express can be slightly confusing, specially when you want to stub the calls to the server for offline testing. So I made a quick and dirty "pense bete" to help myself, and thought I could share it. Tell me if you see anything wrong or unclear.

15 August 2009

Refactoring to REST : why context matters

The wrong path


The app I refactored licenses pictures. The licensee creates an order, selects pictures, finally submits the order, which is then reviewed by Mr licensor. The cart relied on on a current_order the same way current_user works (with a session id), to add or remove a picture from it.

A few months later we decided to extend the app to have automated invoices as well as payments online. Naturally I created an "Invoice" and a "Payment" model which both belonged to an "Order" with a "one to one relationship".

So, to access payments and invoices, I also relied on current_order.



That made sense at the begining : as soon as I accessed an Order#id it would check if the current_order was the same as the one found with params[:id] and if not, I updated it along with the cart.

#orders_controller.rb
def set_current_order
self.current_order==@order || self.current_cart= (self.current_order= @order).assets )
end


But what if i wanted to access a payment directly, without first going through the orders controller (e.g. in some email inviting a customer to pay) ? I would have to make sure the payment I'm accessing belongs to the user and then update current_order with @payment.order so I don't endup having any mismatch with a trailing current_order.

Not unsolvable but : ...

Bad guess !!! I should only access a payment through the order it belongs to. What I'm doing wrong here is setting the context (an order) after finding the object it lives in (it's payment).

The Importance of Context


Rule of thumb : get the context before the object it lives in !!!

Why you ask ? Because I could easily end up having a Payment view linking to an order it doesn't belong to.

That meant : instead of having links like this
link_to "payment", current_order.payment

...they should all be like this :
link_to "payment", [@order, :payment]


That way you have a consistent before_filter for every singleton (payment, invoice, items etc) belonging to an order.


Although the idea of having a single point of access through current_order seemed a good starting point, not translating it with the conventions REST resources suggest, had me tangled up in inconsistencies.

It might seem obvious to many of you, but with the :shallow=>true option you get in your routes, which enables access to a resource without its parent, one might forget why, in many cases, the context of a resource is more than relevant : necessary.


Next I will talk of form_for which doesn't play very well with a singleton resource.

Charly

04 August 2009

Tabbed Navigation for Rails

When I start a new rails app and write a tabbed menu, I always postpone the moment I'll determine how it's going to set the current tab. And when it comes to it, I usually do quick and dirty stuff with the controller name, the @category.name or whatever. But last time, facing a step by step form you could navigate through with tabs, I thought "enough of it I need a solution once and for all".

Sooo, looking at plugins first tabnav seemed to be the reference. But I wanted something i could easily tweek and understand, and this was just overkill for me needs.

Then I looked at the free for all tab helper which has some very interesting solutions, the most elegant being the one relying only on css and the body tag (no logic involved). But that wasn't flexible enough, they were all making the assumption the tabs would switch controllers.

So having to get my hands dirty I first refreshed my memory with my favourite source of hints and came up with what I believe is a very elegant and flexible solution.





This is minimalistic but you can see that it is very easily extendable. The main idea is that you are sendind to the tab class a matcher that is going to set the current tab.

My matcher was a bit complex as you can see below(it also sets the partial to render), but keep in mind that you could do exactly the same like this :

tab_for :controller => controller_name do |t|
...

and it works with no further logic.




What I appreciate most is that the logic for matching the tab is kept seperate ( it only relies on the params inside the links ) and the "tab_for do" syntax is very railsish & familiar.

30 April 2009

Couch Str0m and the Great Chicken

The hole Couchdb act as a Str0m sheds an interesting light on a notion I’m pretty fond of, because it partially reveals the mechanisms of community formation : it’s called intersubjectivity.

Before I start throwing Lacan at you, let me illustrate it with a (famous) joke : the guy thinks he’s a corn weed and is terrified he’ll be eaten by the giant chicken. He’s locked up in an asylum, follows a successful treatment and the doctors free him after 6 months. But as soon as he’s out the guy comes running back. Puzzled doctors ask : “What’s the matter, you know you’re not a corn weed don’t you ?”. “Yes I know it, but does the giant chicken know it ?”

What stroke me is that most of the posts/comments I stumbled upon while discovering all the rage were saying : “I’m not personnaly offended, don’t get mistaken by the idea i’m some prude, political correct fanatic, it’s just that i am offended for the people whom were offended”. So the question raises : who was really offended ? The giant chicken ?



As soon as you are in the social sphere, presuming people think a certain way almost automatically constrains your thoughts in shaping themselves like theirs. A portion of yourself might still whisper “these aren’t your own thoughts, you are not a corn seed”, and that voice may remain, but you’ll defend them and act upon them as if they were yours. The funny thing is that everybody is doing the same things which is acting upon the assumption the others think and believe a certain way.

Yes I just dicovered social convention, big deal ! More interestingly it is the fact that social convention is based on the implicit. By that i mean what is explicit is meant to be debated, questionned, opened to the games of construction & deconstruction under the knife of language. Implicit is sacred : as soon as someone breaks in and says “THE KING IS NAKED”, or “THE GREAT CHIKEN DOESN’T EXIST”which is throwing the implicit in the explicit, the community ciment cracks... violently.

It’s also very healthy.

18 April 2009

default_scope use case

Ryan Bate in rails 2.3 extras episode throws 2 sugestions on when to use default_scope (which is a sort of global named_scope, that can be overriden).
  1. default_scope :conditions => "deleted_at is not NULL"
  2. default_scope :order => "position DESC"

Ok thats fine but recently i've come up with a more interesting use.

I've built an online payment system for chaplin's image bank and going through all the hastle of getting ssl certificate, a new ip for the subdomain etc etc it certenly not something I wanted to repeat. (BTW thanks again to Ryan bates for the great serie of episodes on paypal). Well since I would be using it for other parts of charliechaplin.com domain I decided to share the payment table, invoice table and user table through differant rails application. That way I could also have an app gathering all the info for budget management.

Yes Rails modularization is definitely one aspect of the framework I was eager to explore at some point specially when it came to membership. However you still need to know if a payment comes from the image bank app, or the live perfomance app, or the funny hat app.

So instead of using STI with the risk of breaking things by renaming Payment with PhotoPayment or something, i brought default_scope in the game along with a before_save (or before_create if you prefer)





And voilĂ , nothing else to change.

Charly

07 November 2008

depth first tree traversal

I started a little library called RAAWS for Ruby Associate Amazon Web Services. It's in a very early stage of development, so don't use it yet.

Anyway fiddling around with amazon api responses, I often felt like having a clear look at the xml directly in my a rails view, but found nowhere a good depth-first tree traversal method in any of the libraries (hpricot, libxml, nokogiri, rexm...ha no) to help me spit it out in a readable html list.

So after a little struggle :


If anyone has a better way, please let me know, specially with node.path.split('/') to get the nodes depth, it' really a dirty hack.

02 October 2008

Rails refactoring exercise

I started my blog after reading jay field's post on the underuse of modules and 'design pattern in ruby' book. Mainly because i thought it would be interesting, as a learning process, to explore the silent power of modules.

So knowing Rails was doing a heavy use of alias_method_chain as it's AOP trick, i did a shallow dive in ActiveRecord's code to see how it could be transformed in the MultiInheritance-like-style of modules.




UPDATE
I published the post unfinished not thinking it would attract much attention without annoucement : so sorry for the lack of explanation.
  • the main idea is to move (almost?) all public instance methods of ActiveRecord::Base in a Behavior module called ActiveRecord::Core - which makes sense since they're the methods to be deCORAted.
  • The uninclude gem is here to enable the possibility for a plugin to override an AR "core" behavior in a sub "everyday" model.
  • Another way I thought of was this (below), unfortunately i get : NoMethodError: super: no superclass method ‘save’




  • another solution would be to use the callstack to intercept the presence of MyTransaction#save and tell Transaction to do a transparent super.