Reputation: 822
I was reading an article about ruby service objects at: http://code.tutsplus.com/tutorials/service-objects-with-rails-using-aldous--cms-23689
I'm not understanding why @user_data_hash is being assigned a value. It is not being used anywhere in the code. I've seen few other examples doing same thing in other articles I've read. What is the need of assigning to this instance variable?
class CreateUserService < Aldous::Service
attr_reader :user_data_hash
def initialize(user_data_hash)
@user_data_hash = user_data_hash
end
def default_result_data
{user: nil}
end
def perform
user = User.new(user_data_hash)
if user.save
Result::Success.new(user: user)
else
Result::Failure.new
end
end
end
Upvotes: 0
Views: 53
Reputation: 107117
@user_data_hash
is used, because
attr_reader :user_data_hash
is a macro for:
def user_data_hash
@user_data_hash
end
That means: This line user = User.new(user_data_hash)
in the perform
method will read the hash assigned to @user_data_hash
:
Upvotes: 2
Reputation: 29880
attr_reader
defines a method called user_data_hash
, which returns @user_data_hash
. So it is being used whenever you call user_data_hash
.
Upvotes: 1