1

So I come from a background in Java where you can create a class as such.

TestClass x = new TextClass();

and call its method like x.shout();

I'm attempting to do something similar in ruby with no such look. This could be syntactical or it could be I don't understand the concept of ruby and rails well.

So heres a class on a server in Ruby

class myResource< ActiveResource::Base
  self.site = "http://localhost:3008"
  def self.shout
    puts "I AM AN ACTIVE RESOURCE SHOUT!"
    puts " CAPS RAGE YEAH!"
    puts Time.now
  end
end

This sits on client side.

Heres the same class as an active record on server:

class myRecord < ActiveRecord::Base
  def self.shout
  puts "I AM AN ACTIVE RECORD SHOUT!"
  puts " CAPS RAGE YEAH!"
  puts Time.now
  end

end

So heres the result of what I've attempted.

On server in rails console:

?> myRecord.shout
I AM AN ACTIVE RECORD SHOUT!
 CAPS RAGE YEAH!
Wed Jul 13 10:17:33 +0100 2011
=> nil
>> 

On the client side however,

myResource.shout
NoMethodError: undefined method `shout' for myResource:Class
    from (irb):206
>>

In my mind this makes no sense as their almost identical and should be called as such.

If i instantiate either of them as

@test = myResource or myRecord.new(blah blah blah)

when i write @test.shout

I get the same undefined method.

My idea of what an object is in Ruby has been blown. Has anyone any advice on what I'm doing wrong here.

OVERTONE
  • 11,797
  • 20
  • 71
  • 87
  • Your code shouldn't work at all. Class names must start with a capital letter. – Dogbert Jul 13 '11 at 10:34
  • @dogbert. Hello. I love your cartoon. They original classes do start with capital letters. I was rushing through writing this question and didnt spot that. Apologies – OVERTONE Jul 13 '11 at 10:41

1 Answers1

2

Ruby classes are always capitalized. Also, you do not reference self when you are declaring a regular method in a class.

This is what you want:

class MyRecord 

    def shout
        puts "I AM AN ACTIVE RECORD SHOUT!"
        puts "CAPS RAGE YEAH!"
        puts Time.now
    end

end

Then run it however you want:

> MyRecord.new.shout
=> "I AM AN ACTIVE RECORD SHOUT!"
=> "CAPS RAGE YEAH!"
=> 2011-07-13 06:35:18 -0400
thenengah
  • 42,557
  • 33
  • 113
  • 157
  • NP:) `def method.self` is used for singleton method in modules. That will make more sense when you have mixins. – thenengah Jul 13 '11 at 10:54
  • I was under the impression that self methods were class methods (as opposed to instance methods)? – jaydel Jul 13 '11 at 11:24