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.
30 April 2009
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).
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
- default_scope :conditions => "deleted_at is not NULL"
- 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.
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 :
require "rubygems"
require "xml/libxml"
#require "active_support"
def traverse(node)
children = node.children.select {|a| a.element?}
txt = "<h1>HTML output</h1><ul>"
last_depth, depth = 1, 1
while child = children.shift
depth = child.path.split("/").size.to_i - 2
if depth > last_depth
txt << "\n<ul>"
elsif depth < last_depth
txt << "</ul>\n" * (last_depth - depth)
end
txt << "<li>#{child.name} : <i>#{child.content if child.children.all? {|a| a.text?}}</i></li>\n"
a = child.children.select {|c| c.element?}
unless a.empty?
children.unshift(a).flatten!
end
last_depth = depth
end
open("output.html", "w") do |f|
f.write txt << "</ul>"
end
end
xml = XML::Document.file("chaplin.xml")
# p xml.root.namespaces
traverse(xml.root)
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.
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.
require "rubygems"
require "uninclude"
module Core
def save; "saved" end
end
module Dirty
def save; "clean + " + super end
end
module Transaction
def save; "transaction + " + super end
end
module Validation
def save; "valid + " + super end
end
class Base
include Core
include Dirty
include Transaction
include Validation
end
# PLUGIN adding more validation
module MyValidation
def save
"more validation + " + super
end
end
# PLUGIN overiding Transaction
module MyTransaction
def save
Base.send :uninclude, Transaction
body = "my transaction! + " + super
Base.send :include, Transaction
body
end
end
# Our everyday model
class A < Base
include MyTransaction
end
class B < Base; end
class C < Base
include MyValidation
end
a = A.new
b = B.new
c = C.new
puts a.save #=> my transaction! + valid + clean + saved
puts b.save #=> transaction + valid + clean + saved
puts c.save #=> more validation + transaction + valid + clean + saved
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’
module MyTransaction
def save
Transaction.instance_eval do
@@save = instance_method(:save)
remove_method :save
end
body = "my transaction! + " + super
Transaction.module_eval do
define_method :save do
@@save.bind(self).call
end
end
body
end
end
- another solution would be to use the callstack to intercept the presence of MyTransaction#save and tell Transaction to do a transparent super.
18 September 2008
Use case: How to Decorate your Plugins
Rails being ruby's killer app, I believe it's vital to illustrate whatever theoretical consideration with real life rails cases (and not just Coffee, spoon_required gibberish)
So take my image bank: class Asset holds the pictures and i gave it a tagging system. I quikly realized i needed to downcase all tags for consistency so I would not end up with both "Winston Churchill" and "winston churchill" as seperate tags.
acts_as_taggable_on, gives you a whole set of methods... some of which are dynamic given its argument (e.g acts_as_taggable_on(:tags, :people) will give you tag_list, and person_list)
Well 2 years ago i would of done something extremely ugly in my controller like:
params[:asset][:tag_list].downcase.... And just the thought of it makes me sick and consider zen boudhism as an alternative to eating cats.
So now that my controllers are all skinny, i was looking at a way to downcase the argument of tag_list=(arg) in my model. Lets make a short story shorter: tag_list= and person_list= being defined dynamically, they're just stubs for a more general method: set_tag_list_on(context, new_list, tagger=nil).
Below i've summed up my 4 or 5 attempts in two:
...but that didn't work because tag_list is actually dynamically defined directly in the body of the Asset class wheras set_tag_list_on lies in ActiveRecord::Acts::TaggableOn::InstanceMethods so it is higher up in the inheritance chain. And that is true for 95% of all instance methods of any active record plugin.
So as you see, nothing is more easy than "enhancing", "decorating", "altering", "bending" any method
The only constraint is that both the original code and your hack must be in modules 'bracket'. The good news is that a lot of code (like ActiveSupport and so on) is already concieved that way.
VoilĂ .
(Next I'll look at some rails internals and a suggested way to dump alias_method_chain)
So take my image bank: class Asset holds the pictures and i gave it a tagging system. I quikly realized i needed to downcase all tags for consistency so I would not end up with both "Winston Churchill" and "winston churchill" as seperate tags.
acts_as_taggable_on, gives you a whole set of methods... some of which are dynamic given its argument (e.g acts_as_taggable_on(:tags, :people) will give you tag_list, and person_list)
Well 2 years ago i would of done something extremely ugly in my controller like:
params[:asset][:tag_list].downcase.... And just the thought of it makes me sick and consider zen boudhism as an alternative to eating cats.
So now that my controllers are all skinny, i was looking at a way to downcase the argument of tag_list=(arg) in my model. Lets make a short story shorter: tag_list= and person_list= being defined dynamically, they're just stubs for a more general method: set_tag_list_on(context, new_list, tagger=nil).
Below i've summed up my 4 or 5 attempts in two:
class Asset < ActiveRecord::BaseTo tell you the truth my second attempt was actually
acts_as_taggable_on :tags, :people
# FIRST ATTEMPT
def tag_list=(new_tags)
set_tag_list_on('tags',new_tags.downcase)
end
def person_list=(new_tags)
set_tag_list_on('people',new_tags.downcase)
end
# SECOND ATTEMPT
module HackTag
def set_tag_list_on(context, new_tags, tagger=nil)
super(context, new_tags.downcase, tagger=nil)
end
end
include HackTag
end
module TagHack
def tag_list=(new_tags)
super(new_tags.downcase)
end
end
...but that didn't work because tag_list is actually dynamically defined directly in the body of the Asset class wheras set_tag_list_on lies in ActiveRecord::Acts::TaggableOn::InstanceMethods so it is higher up in the inheritance chain. And that is true for 95% of all instance methods of any active record plugin.
So as you see, nothing is more easy than "enhancing", "decorating", "altering", "bending" any method
- without touching the original code or endangering other classes using it...
- without resolving to black magic...
- and without polluting your code with methods saying without !
The only constraint is that both the original code and your hack must be in modules 'bracket'. The good news is that a lot of code (like ActiveSupport and so on) is already concieved that way.
VoilĂ .
(Next I'll look at some rails internals and a suggested way to dump alias_method_chain)
Labels:
decorator pattern,
module,
plugin,
rails,
ruby
16 September 2008
From Decorator Pattern to Before Filter 2
In my previous post From Decorator Pattern to Before Filter 1 we got to the point where we could write this:
Now the thing missing is that we're only filtering one method ('cost' in this case) wheras the before_filter in rails filters all methods by default. So how do we do this?
Quit easily, we just have to list all the instance methods inside the class Coffee (ruby provides this possiblity with "instance_methods(false)").... and... iterate!:
After that adding options like :except=>"smell" is easy. Dealing with inheritance is probably less obvious. The one main differance we have with the rails version of before_filter is the fact that it is set inside the classes body. Not at object creation, and for a good reason since controllers instances are created under the hood.
Of course the easy path is adding: extend(Creme) and before_filter(:spoon_required) in the Coffee's initialize method, but my question was: "is it possible to make it look like this" :
The answer is yes although it's a bit convoluted (it looks like a rail plugin with module InstanceMethod and so on) AND we still have to overide initialize somewhere which makes it dangerous.
Now one word of explanation: the hole elegance of the Decorator Pattern in ruby relies on the fact we're calling super instead of aliasing twice the method we're decorating (or unbinding and binding). Calling super() is possible because when we extend an object with a module (like in coffee.extend Creme) we're actually including the module in the ghostclass (or metaclass or singleton class) which sits right underneath the 'real' class in the inheritance chain.
(TODO add figure)
So wouldn't be nice if we could mixin a module 'underneath' a class by saying so in the body of the class so we could easily do all that aspect oriented stuff without having to worry about it at instanciation time ?
The great Library Facets, gives it a try with prepend which can be used this way :
But guess what, it's by overriding new:
Comments welcome !
coffee = Coffee.new
coffee.mixin Callback
coffee.before_filter :spoon_required, :cost
coffee.cost
Now the thing missing is that we're only filtering one method ('cost' in this case) wheras the before_filter in rails filters all methods by default. So how do we do this?
Quit easily, we just have to list all the instance methods inside the class Coffee (ruby provides this possiblity with "instance_methods(false)").... and... iterate!:
require 'rubygems'
require 'mixology'
module Callback
def filter_with filter, filtered_method
Callback.method_factory(filter, filtered_method)
end
def before_filter filter
methods = self.class.instance_methods(false)
methods.delete(filter.to_s)
methods.each do |filtered_method|
filter_with filter, filtered_method
end
end
def self.method_factory(filter, filtered_method)
define_method(filtered_method) do
send filter
super
end
end
end
class Coffee
def spoon_required
puts "get a spoon to steer sugar || creme"
end
def cost
puts "3"
end
def smell
puts "good"
end
def color
puts "black"
end
end
coffee = Coffee.new
coffee.mixin Callback
coffee.before_filter :spoon_required
# Every call beneath is prepended by :
# - "get a spoon to steer sugar || creme"
coffee.cost
coffee.smell
coffee.color
After that adding options like :except=>"smell" is easy. Dealing with inheritance is probably less obvious. The one main differance we have with the rails version of before_filter is the fact that it is set inside the classes body. Not at object creation, and for a good reason since controllers instances are created under the hood.
Of course the easy path is adding: extend(Creme) and before_filter(:spoon_required) in the Coffee's initialize method, but my question was: "is it possible to make it look like this" :
class Coffee
include Creme
before_filter :spoon_required
def spoon_required
puts "get spoon"
end
def cost
puts "3"
end
end
The answer is yes although it's a bit convoluted (it looks like a rail plugin with module InstanceMethod and so on) AND we still have to overide initialize somewhere which makes it dangerous.
Now one word of explanation: the hole elegance of the Decorator Pattern in ruby relies on the fact we're calling super instead of aliasing twice the method we're decorating (or unbinding and binding). Calling super() is possible because when we extend an object with a module (like in coffee.extend Creme) we're actually including the module in the ghostclass (or metaclass or singleton class) which sits right underneath the 'real' class in the inheritance chain.
(TODO add figure)
So wouldn't be nice if we could mixin a module 'underneath' a class by saying so in the body of the class so we could easily do all that aspect oriented stuff without having to worry about it at instanciation time ?
The great Library Facets, gives it a try with prepend which can be used this way :
require 'rubygems'
require 'facets'
module Creme
def cost
puts "before_filter"
super
end
end
class Coffee
prepend Creme
def cost
puts "3"
end
end
coffee = Coffee.new
coffee.cost
But guess what, it's by overriding new:
def prepend( aspect )
_new = method(:new)
_allocate = method(:allocate)
(class << self; self; end).class_eval do
define_method(:new) do |*args|
o = _new.call(*args)
o.extend aspect
o
end
define_method(:allocate) do |*args|
o = _allocate.call(*args)
o.extend aspect
o
end
end
end
Comments welcome !
Labels:
aspect oriented,
callback,
decorator pattern,
module,
ruby
11 September 2008
From Decorator Pattern to Before Filter 1
Looking at my previous post on the Decorator Pattern in ruby, I thought: 'here's an elegant solution to inject behaviour in an object method while respecting encapsulation... but what could be the use of it, a part from unmixing creme out of my coffee'.
- Hummm well in this rails plugin i started writing it could fit in....
- yes but as a more general solution...
- mmmm...Filtering of course !!! Just like the 'before_filter' in rails controller.
- you mean like that :
- as a rough start it gives you the idea. But we would need something more dsl-ish, like our reference in rails controller: 'before_filter :login_required'
- so i guess the next step is to give it a method to call on like spoon_required:
- ok, that was easy but the module is still tied to the class it's decorating. We need to abstract away the method we're filtering ('cost') in the module so it could be any method in the class. So this requires a little bit of ruby's magic :
- I think we've done the hardest part. The rest in episode 2.
- Hummm well in this rails plugin i started writing it could fit in....
- yes but as a more general solution...
- mmmm...Filtering of course !!! Just like the 'before_filter' in rails controller.
- you mean like that :
require 'rubygems'
require 'mixology'
module Callback
def cost
puts "put before filter here"
super
puts "put after filter here"
end
end
class Coffee
def cost
puts 3
end
end
coffee = Coffee.new
coffee.mixin Callback
coffee.cost
- as a rough start it gives you the idea. But we would need something more dsl-ish, like our reference in rails controller: 'before_filter :login_required'
- so i guess the next step is to give it a method to call on like spoon_required:
require 'rubygems'
require 'mixology'
module Callback
def cost
spoon_required
super
end
end
class Coffee
def spoon_required
puts "get a spoon to steer sugar || creme"
end
def cost
puts 3
end
end
coffee = Coffee.new
coffee.mixin Callback
coffee.cost
- ok, that was easy but the module is still tied to the class it's decorating. We need to abstract away the method we're filtering ('cost') in the module so it could be any method in the class. So this requires a little bit of ruby's magic :
require 'rubygems'
require 'mixology'
module Callback
def before_filter filter, filtered_method
Callback.method_factory(filter, filtered_method)
end
# Needed defin_method here so it's called in module's context
def self.method_factory(filter, filtered_method)
define_method(filtered_method) do
send filter
super
end
end
end
class Coffee
def spoon_required
puts "get a spoon to steer sugar || creme"
end
def cost
puts "3"
end
def taste
puts "African Arabica"
end
end
coffee = Coffee.new
coffee.mixin Callback
coffee.before_filter :spoon_required, :cost
coffee.cost
coffee.cost
- I think we've done the hardest part. The rest in episode 2.
Labels:
aspect oriented,
callback,
decorator pattern,
ruby
Subscribe to:
Posts (Atom)
