Using the question mark for string equations.
Roy van der Meij di 22 jun 10
In rails we have the method Rails.env.production? which simply checks if Rails.env equals “production”
I kinda liked that and I was curious how they did that.
It appears that DHH himself made a class StringInquirer which had a nifty method_missing method.
Let’s check it out! (you can find this file in gems/active_support#{version}/lib/active_support/string_inquirer.rb)
module ActiveSupport class StringInquirer < String def method_missing(method_name, *arguments) if method_name.to_s[-1,1] == "?" self == method_name.to_s[0..-2] else super end end end end
With this knowledge we can do something like this.
fancyness = ActiveSupport::StringInquirer.new("fancy") fancyness.fancy? => true fancyness.lame? => false
So what do we do when we want to make this core functionality for any stringg?
Simple! Monkey patch the class String!
class String def method_missing(method_name, *arguments) if method_name.to_s[-1,1] == "?" self == method_name.to_s[0..-2] else super end end end "fancy".fancy? => true a = "awesome" a.awesome? => true a.stupid? => false
I personally like it more to have core extensions in separate modules instead of hacking the String class directly. So here is the cleaned up version.
module CoreExtensions module StringExtensions def method_missing(method_name, *arguments) if method_name.to_s[-1,1] == "?" self == method_name.to_s[0..-2] else super end end end end String.send :include, CoreExtensions::StringExtensions "fancy".fancy? => true
So… is it fancy?
Gepost in hor | 0 reacties
Welcome to Holland On Rails
This weblog is the official Ruby techblog from the guys at Holder, a Ruby development company. Holder is also the company behind the RubyAndRails Europe Conference in Amsterdam.Recente Jobs
Bekijk alle jobs »»
Gereedschapskist
Onmisbare tools vooriedere developer!
- Ruby On Rails
Framework voor de web 2.0 developer. Eindelijk vooruitgang! - TextMate
Editor for true pro's
Typ, tab, top :-)
Nee, niet voor Win. - Made On A Mac
En nou is het over met die saaie grijze Windows bak van je!
Auteurs op deze site
Chris Obdam
'Less is more' evangelist, past dit ook dagelijks toe op zijn tandenborstel.Chiel Wester
Snelheidswonder op Ruby wielen. Leuk om mee te pair-programmen ;-)
Plaats je reactie