method_arguments gem
With the method_arguments gem you can easily set object attributes from method arguments.
Transform this:
def initialize(user_entity, first_name:, last_name:, email:, phone:, dob:)
@user_entity = user_entity
@first_name = first_name
@last_name = last_name
@email = email
@phone = phone
@dob = dob
end
into this streamlined version:
def initialize(user_entity, first_name:, last_name:, email:, phone:, dob:)
set_instance_vars(__method_args__)
end
Features
1. Reading Method Arguments
Within any method, call __method_args__
to retrieve its arguments as a Hash.
def initialize(user_entity, first_name:, last_name:, age:, **kw_rest)
"Method ##{__method__} received #{__method_args__.inspect} arguments"
end
Limitations
-
Argument types *rest
and **keyrest
are ignored regardless of their name:
def initialize(arg, *arg_rest, kw_arg:, **kw_rest)
__method_args__
end
Casting unknown arbitrary arguments to instance variables is not recommended for security reasons.
-
The method does not support argument forwarding:
def self.call(...)
new(__method_args__).call
end
2. Filling instance @variables
Use set_instance_vars(hash)
to assign instance variables from a Hash.
3. Filling instance @variables using attribute writers
To leverage setters (attribute writers), add use_writers: true
argument. If a writer with the corresponding name exists, it will be invoked.
Example
Before:
def initialize(user_entity, first_name:, last_name:, age:)
@user_entity = user_entity
@first_name = first_name
@last_name = last_name
self.age = age
end
def age=(val)
@age = Integer(val)
end
After:
def initialize(user_entity, first_name:, last_name:, age:, ...)
set_instance_vars(__method_args__, use_writers: true)
end
def age=(val)
@age = Integer(val)
end
Installation
-
Add to your Gemfile, then run bundle install
:
gem "method_arguments"
-
Prepend your code with
require "method_arguments"
Supported Ruby Versions
This gem is designed to be compatible with Ruby 2.7 and above. It has been tested on the following MRI versions:
If you encounter any issues with later versions, please feel free to report them.