Welcome on the show!" else message = "Sorry pal. You're out." end callback.call(message) end end Movie.cast(pony) { |message| pony.give_message(message) }
module InstanceMethods def name puts @name end end def self.included(receiver) receiver.extend ClassMethods receiver.send :include, InstanceMethods end end class Pony include PonyExtensions def initialize(name) @name = name end end Pony.homeland fluttershy = Pony.new("Fluttershy") fluttershy.name # Equestria # Fluttershy
name end end # autoloader.rb def Object.const_missing(const) puts "Could not find '#{const}'. Trying to load ..." require "./#{const.downcase}" puts "Success!" const_get(const) end p = Pony.new("Rainbow Dash") puts p.name # Could not find 'Pony'. Trying to load ... # Success! # Rainbow Dash
song = meth.to_s.split('_')[1..-1].collect(&:capitalize).join(' ') puts "Let's sing the song '#{song}'" else super end end end pinkie_pie = Pony.new pinkie_pie.sing_american_idiot pinkie_pie.dance # Let's sing the song 'American Idiot' # `method_missing': undefined method `dance' for #<Pony> (NoMethodError)
if decorator_class = @decorate_next_with @decorate_next_with = nil DecoratorHelper.apply_decorator(decorator_class, name, self) end end end class DatabaseConnectorWithDecorator extend FunctionDecorators decorate CacheDecorator def count Logger.info "Called :count" return 1337 end end
responding to calls to the named method. Contrast this with remove_method, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver.
< Pony def hello; "In Dragon"; end end d = Dragon.new p = Pony.new puts d.hello puts p.hello Dragon.send(:undef_method, :hello) puts d.hello # In Dragon # In Pony # undefined method `hello' for #<Dragon> (NoMethodError)
after :throw_party, :cleanup def throw_party run_with_callbacks :throw_party do puts "We're having a great partey!" end end def cleanup puts "Cleaning up all this mess ..." end end applejack = Pony.new applejack.throw_party # I never leave without my party canon! # We're having a great partey! # Cleaning up all this mess ...
callback end def before_callbacks @__before_callbacks ||= {} end def after(method, callback) after_callbacks[method] ||= [] after_callbacks[method] << callback end def after_callbacks @__after_callbacks ||= {} end def [](callback_type) send("#{callback_type}_callbacks") end end module InstanceMethods def run_with_callbacks(method, &impl) run_callbacks(:before, method) yield run_callbacks(:after, method) end def run_callbacks(type, meth) self.class[type][meth].each do |cb| case cb when Symbol self.send(cb) when Proc cb.call end end end end