Hi, I''m still trying to learn the in''s and out''s of Ruby and Rails. I''ve been testing my code a million different ways and have read a number of books and web sites, but something is still not clicking for me. I want to be able to call the protected methods and I have read both David Black''s and Prag Programmers books about how self can be tricky. But I still don''t know how to make it work. I want to call method_a and have it then process both protected methods. Is it possible to call my method_a directly (as shown in my script code) without having to do this: k = Klass.new k.method_a ------------------------ I''ve got this right now. This is called from a script. k = Klass.method_a(:variable = v) My model: class Klass def self.method_a(params = {}) a = Model.find(:first, :conditions => ["variable = ?", variable]) a.do_something a.do_more return a end protected def do_something puts "inside do_something" end def do_more puts "inside do_more" end end Thanks for helping a Ruby Newbie. -- Posted via http://www.ruby-forum.com/.
On Mon, Oct 26, 2009 at 5:26 PM, Cs Webgrl <rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:> I''m still trying to learn the in''s and out''s of Ruby and Rails. I''ve > been testing my code a million different ways and have read a number of > books and web sites, but something is still not clicking for me. I want > to be able to call the protected methodsRuby''s object system is a message passing system. If you have an object foo, and you do: foo.some_method foo doesn''t perform a method call on itself. foo just looks for somewhere to send the "some_method" message, somewhere that returns true for respond_to? foo.respond_to?(:some_message) In knowing how this works, you can send the message yourself, ignoring the private or protected nature of the receiver along the way. Here''s an example: #!/usr/bin/env ruby class Foo private def hidden puts "I am hidden" end end f = Foo.new begin f.hidden rescue puts "Can''t run hidden: #{ $! }" end f.send( :hidden )> ./private.rbCan''t run hidden: private method `hidden'' called for #<Foo:0xb7c2f92c> I am hidden -- Greg Donald http://destiney.com/
Greg Donald wrote:> > Here''s an example: > > #!/usr/bin/env ruby > > class Foo > private > def hidden > puts "I am hidden" > end > end > > f = Foo.new > > begin > f.hidden > rescue > puts "Can''t run hidden: #{ $! }" > end > > f.send( :hidden ) > >> ./private.rb > > Can''t run hidden: private method `hidden'' called for #<Foo:0xb7c2f92c> > I am hidden >Thank you for your example. I was able to test my code and call my methods using object.send (:method) My follow-up question to this is now, is this the best way to handle the protected methods using the code sample that I have above? Or do I have a design flaw in the code? Should I explicitly create and call object.New and the method instead of creating the object like I am doing? Thanks for your help. -- Posted via http://www.ruby-forum.com/.