Ruby , , , .
, , , - - .
Ruby , , . :
class Dog
def initialize(name)
@name = name
end
def bark
"woof"
end
def fetch(object)
"here that #{object}"
end
def sit
"sitting down"
end
private
attr_accessor :name
end
, , . , . , , , , , !? , :
class Tricks
def initialize(name)
@name = name
end
def fetch(object)
"here that #{object}"
end
def sit
"sitting down"
end
def come_when_called(my_name)
"I'm coming" if my_name == name
end
def put_toy_away(object)
"#{fetch(object)}, I'll put it away"
end
private
attr_reader :name
end
class Dog
def initialize(name)
@name = name
end
delegate :sit, :fetch, :come_when_called, :put_away_toy, to: :tricks_klass
def bark
"woof"
end
private
attr_accessor :name
def tricks_klass
@tricks_klass ||= Tricks.new(name)
end
end
, Dog , , . , Tricks , ( ).
Now we can have a Cat class that delegates responsibility for this Tricks class, although it would be one smart Cat!
Now you can also use the Tricks class yourself, so that the force that encapsulates single behavior in your class. You can even separate this behavior even more, but only you, as a developer, know whether it is worth it!
source
share