Assignbot
In Ruby, new operator does not guarantee, for sure, that you can mass-assign instance variables.
And when you want to do that, you should have known you should not writing the code by hand, over and over again.
Assignbot guarantee that you can mass-assign variables from .assign. Furthermore,
implementing Assignbot does not require massive code changes to your codebase,
unless you want custom behaviour.
Use cases
- Assign from the hash, from params
- Assign from the hash, from JSON
Installation
To install Assignbot, add this line to your Gemfile:
gem 'assignbot'And then execute:
$ bundle
Or install it system-wide by issuing:
$ gem install assignbot
Usage
Assume you have the following User class:
class User
attr_accessor :name, :age, :id
endBasic usage of assigner does not require significant code change to your model/ruby class, other than a one-liner include statement:
class User
include Assignbot
# your other ruby code
endBy doing so, you already make User to be assignable from a Hash:
user_params = {
name: "Adam Pahlevi",
age: 23,
id: "934-2311"
}
user = User.new
user.assign(user_params)
user.name == "Adam Pahlevi" # returns trueIf you would like to explicitly tell Assignbot what are the assignable variables, then you have to define the variables explicitly:
class User
include Assignbot
assigner do
name from: :name
age from: :age
id from: :id
end
# your other ruby code
endExplicitly defining assigner also allow you to map the value from source variable, which have different nomenclature, to the target variable in your Ruby class.
License
The gem is proudly available as open source under the terms of the MIT License.