What is the value of the self in the Rails model and why aren't obvious instance methods available?

I have a special access method in my rails 3.1.6 application that assigns a value to an attribute, even if that value is missing. The my_attr attribute is a serialized hash that should be combined with this value if only an empty value is specified, in which case it sets the current value to an empty value. (Added checks to make sure the values ​​are what they should be, but removed for brevity, as they are not part of my question.) My setter is defined as:

def my_attr=(new_val)
  cur_val = read_attribute(:my_attr)  #store current value

  #make sure we are working with a hash, and reset value if a blank value is given
  write_attribute(:my_attr, {}) if (new_val.nil? || new_val.blank? || cur_val.blank?)

  #merge value with new 
  if cur_val.blank?
    write_attribute(:my_attr, new_val)
  else
    write_attribute(:my_attr,cur_val.deep_merge(new_val))
  end
  read_attribute(:my_attr)
end

This code works well as it is, but not when I use self.write_attribute (). Then I get the following error:

NoMethodError:
       private method `write_attribute' called for #<MyModel:0x00000004f10528>

: write_attribute, ? - Ruby Rails ( )?

+5
1

self . , , .

class Foo
  def implicit
    self # => #<Foo:0x007fc019091060>
    private_method
  end

  def explicit
    self # => #<Foo:0x007fc019091060>
    self.private_method
  end

  private
  def private_method
    "bar"
  end
end

f = Foo.new
f.implicit # => "bar"
f.explicit # => 
# ~> -:9:in `explicit': private method `private_method' called for #<Foo:0x007fc019091060> (NoMethodError)
# ~>    from -:25:in `<main>'

, send.

self.send :private_method

Update

ruby ​​metaprogramming.

, , Rubys. : . , , , . :

class C
  def public_method
    self.private_method 
  end
  private
  def private_method; end
end
C.new.public_method
NoMethodError: private method ‘private_method' called [...]

, self.

, , : -, , , -, . , , . " ".

Rubys, Java #, private -. , , . x y, ? - , , , . , ? , .

+11

All Articles