The project is in a healthy, maintained state
The 'method_arguments' gem simplifies the process of setting object attributes from method arguments in Ruby. It introduces a streamlined approach to assign instance variables directly from method arguments with minimal boilerplate code. This utility is especially useful in constructors or methods with numerous parameters, enhancing code readability and maintainability.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

~> 3.1
 Project Readme

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
  1. Argument types *rest and **keyrest are ignored regardless of their name:

    def initialize(arg, *arg_rest, kw_arg:, **kw_rest)
      __method_args__ # returns { a: <value>, kw_arg: <value> }
    end

    Casting unknown arbitrary arguments to instance variables is not recommended for security reasons.

  2. The method does not support argument forwarding:

    def self.call(...)
      new(__method_args__).call # raises error
    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

  1. Add to your Gemfile, then run bundle install:

    gem "method_arguments"
  2. 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:

  • v2.7.2
  • v3.0.3
  • v3.1.2

If you encounter any issues with later versions, please feel free to report them.