开发者

Method not found in instantiated class (Ruby/Rails)

开发者 https://www.devze.com 2023-03-20 11:42 出处:网络
So I come from a background in Java where you can create a class as such. TestClass x = new TextClass();

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 开发者_如何学Cheres 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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消