Reputation: 10350
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
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
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