A Rails plugin to encapsulate common array attributes methods.
This gem can be used to avoid repeating the same methods in models when working with arrays.
This branch targets Ruby 2.4+ only
Add this line to your Gemfile:
gem 'array_attributes'
then run:
bundle install
class Book < ActiveRecord::Base
string_array_attributes [:authors, :countries]
end
It assumes you are passing string attributes.
It also supports the following options:
:reject_blank
: whether the attribute should skip blank values:reject_if
: condition to reject values
class Device < ActiveRecord::Base
string_array_attributes [:ips], reject_blank: true, reject_if: ->(value) { value == '127.0.0.1' }
end
You can invoke attribute_raw
to get the array values joined by commas.
book = Book.create(authors: ['John Doe', 'Jane Doe'])
book.authors_raw #=> "John Doe, Jane Doe"
You can invoke attribute_raw=
to set the array value by entering the values split by commas.
book = Book.new
book.authors_raw="John Doe, Jane Doe"
book.save!
book.authors #=> ["John Doe", "Jane Doe"]
See LICENSE
.