Search code examples
ruby-on-railsrubyruby-on-rails-4self

is it correct to add self like in this case in ruby on rails


I am trying to make it available to repost a post in my app...I see in a Youtube video this code..

class Pin < ActiveRecord::Base
validates_presence_of :bio
belongs_to :user

mount_uploader :image, PictureUploader

def repost
    repost_pin = self.dup
    repost_pin.save
end

is it correct to use self like here? and would it be possible to change to this:

def repost
    dub
end

in the end repost will be called on the instance variable @post(@post = Post.find(params[:id]) ) .... maybe I misunderstanding something here...anyone can help?


Solution

  • You can skip self when it is clear from context that you are reading a current instance's attribute or calling its method.

    When writing you should be more careful as this:

    def write
      test = 'test'
    end
    

    will create a local variable test even if there is an attribute with the same name. Alternatively, this:

    def write
      self.test = 'test'
    end
    

    will assign the value to current instance's attribute named test.

    In your example you could skip self since dup is a method of Object and therefore is available in current context as a valid identifier:

    def repost
        repost_pin = dup
        repost_pin.save
    end
    

    That said, it is not an error to explicitly use self e.g., to mark your intent to use the object's attribute or method. Ruby style guide does not recommend it though.