Monday, February 27, 2012

Changing aliased method does not alter the original one

Changing aliased method does not alter the original one, and vice-versa.

So, if you need to alter some method that you know it's aliased, you may stay unworried: you won't affect the other aliased methods, and you can use them if you need the original behavior.

See my tests and the results below.

#!/usr/bin/ruby

class A
  def original_method
    puts "original content"
  end
  alias aliased_method original_method
  alias_method :alias_methoded_method, :original_method
end

class B < A
  def original_method
    puts "modified content"
  end
end

class C < A
  def aliased_method
    puts "modified content"
  end
end

class D < A
  def alias_methoded_method
    puts "modified content"
  end
end

[A, B, C, D].each do |klass|
  puts "#{klass}:"
  obj = klass.new
  [:original_method, :aliased_method, :alias_methoded_method].each do |meth|
    print "#{meth}: "
    obj.send meth
  end
  puts
end
The results:
A:
original_method: original content
aliased_method: original content
alias_methoded_method: original content

B:
original_method: modified content
aliased_method: original content
alias_methoded_method: original content

C:
original_method: original content
aliased_method: modified content
alias_methoded_method: original content

D:
original_method: original content
aliased_method: original content
alias_methoded_method: modified content

Friday, February 17, 2012

RewriteRule running twice

Sometimes it seems that RewriteRule is running twice, even we use the [L] flag.

The truth is: it really runs twice (or even more times)! But only when URL is changed.

The [L] flag stops the running of rules following it, but if URL is changed, the new URL will be parsed again from the beginning.

There are many solutions to that (e.g., by using RewriteCond), but the one I used is to put, as first rule, one to tell the RewriteEngine to do nothing if the URL is what I want:


RewriteEngine on

# index is the last rule - is what I want, so doesn't change anything
# and go to it (thank's to [L])!
RewriteRule ^index.php$ - [L,QSA]

# get user id - URL changed, so [L] will cause the new URL to be reparsed
# - and so it will be matched on the above rule.
RewriteRule ^user/(.*)$ index.php?user=$1 [L,QSA]

# in case of user/..., following rules don't apply,
# since the above rule has [L]
# ...

See this post in Portuguese.