How to implement methods that act "directly" on the attributes of an object?

I use Ruby on Rails v3.2.2, and I would like to call the methods "directly" on the attributes of the instance, and not on their recipient objects. That is, if I have an instance User @userfor which

@user.name
# => "Leonardo da Vinci"

I could implement methods that act directly on the attribute nameso that I can write something like

# Note: 'is_correct?' and 'has_char?' are just sample methods.
@user.name.is_correct?
@user.surname.has_char?('V')

Is it possible? If so, how can I do this?

Note. I am trying to implement a plugin.

+3
source share
2 answers

, , IMHO , , .

, @user.name String, , String. , String, singleton String. , , , .

- - :

@user.valid?(:name)

has_char?('V'), String:

@user.surname.include?('V')
+3

lil singleton , , . ! :)

class Bar

  def initialize foo
    @foo = foo
    def @foo.bar 
      p "baaaaaaar"
    end
  end

  def foo
    @foo
  end

  def foo=(foo)
    @foo = foo
    def @foo.bar 
      p "baaaaaaar"
    end
  end
end

a = Bar.new "foo"
p a.foo
p a.foo.bar
a.foo = "bar"
p a.foo.bar
# >> "foo"
# >> "baaaaaaar"
# >> "baaaaaaar"
# >> "baaaaaaar"
# >> "baaaaaaar"
0

All Articles