user938363
user938363

Reputation: 10350

Possible to retrieve value of instance which singleton class is attached to?

Here is a example of singleton class:

class MyPost < ActiveRecord::Base
  def initialize(title)
    @title = title
  end
end

post = MyPost.new(:title => 'post title')

def post.some_method
  #is it possible to retrieve value of `post`?
  my_post_title = post.title #???. Not working now
end

Is it possible to refer back to post in def post.some_method?

Upvotes: 0

Views: 45

Answers (2)

uday
uday

Reputation: 8710

There are errors: 1. unending single quote in the title. 2. when you are inside the post then you can access directly @title, you cannot call it post.title

class MyPost < ActiveRecord::Base
  def initialize(title)
    @title = title
  end
end

post = MyPost.new(:title => 'post title')

def post.some_method
  my_post_title = @title
end

post.some_method

or if you have set your attr_accessor for your title

require 'active_record'

class MyPost < ActiveRecord::Base
  attr_accessor :title
  def initialize(title)
    @title = title
  end
end

post = MyPost.new(:title => 'post title')

def post.some_method
  my_post_title = title
end

Upvotes: 1

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

Yes. Inside a method, the special variable self holds a reference to the receiver of the message:

class MyPost < ActiveRecord::Base
  def initialize(title)
    @title = title
  end
end

post = MyPost.new(title: 'post title')

def post.some_method
  my_post_title = title
end

Upvotes: 2

Related Questions