Skip to content

nepalez/dry-initializer-rails

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Jan 28, 2017
18f4273 · Jan 28, 2017

History

16 Commits
Jan 28, 2017
Jan 28, 2017
May 16, 2016
May 19, 2016
May 16, 2016
Jan 28, 2017
Jan 28, 2017
Jan 28, 2017
May 16, 2016
May 16, 2016
May 16, 2016
Jan 28, 2017
May 16, 2016
Jan 28, 2017

Repository files navigation

dry-initializer-rails Join the chat at https://gitter.im/dry-rb/chat

Gem Version Build Status Dependency Status Code Climate Test Coverage Inline docs

Rails plugin to dry-initializer

Installation

Add this line to your application's Gemfile:

gem 'dry-initializer-rails'

And then execute:

$ bundle

Or install it yourself as:

$ gem install dry-initializer-rails

Synopsis

The gem provides value coercion to ActiveRecord instances.

Add the :model setting to param or option:

require 'dry-initializer'
require 'dry-initializer-rails'

class CreateOrder
  extend Dry::Initializer

  # Params and options
  param  :customer, model: 'Customer' # use either a name
  option :product,  model: Product    # or a class

  def call
    Order.create customer: customer, product: product
  end
end

Now you can assign values as pre-initialized model instances:

customer = Customer.find(1)
product  = Product.find(2)

order = CreateOrder.new(customer, product: product).call
order.customer # => <Customer @id=1 ...>
order.product  # => <Product @id=2 ...>

...or their ids:

order = CreateOrder.new(1, product: 2).call
order.customer # => <Customer @id=1 ...>
order.product  # => <Product @id=2 ...>

The instance is envoked using method find_by(id: ...). With wrong ids nil values are assigned to a corresponding params and options:

order = CreateOrder.new(0, product: 0).call
order.customer # => nil
order.product  # => nil

You can specify custom key for searching model instance:

require 'dry-initializer-rails'

class CreateOrder
  extend Dry::Initializer

  param  :customer, model: 'User', find_by: 'name'
  option :product,  model: Item,   find_by: :name
end

This time you can pass names (not ids) to the initializer:

order = CreateOrder.new('Andrew', product: 'the_thing_no_123').call

order.customer # => <User @name='Andrew' ...>
order.product  # => <Item @name='the_thing_no_123' ...>

Compatibility

Tested under MRI 2.2+.

Contributing

  • Fork the project
  • Create your feature branch (git checkout -b my-new-feature)
  • Add tests for it
  • Commit your changes (git commit -am '[UPDATE] Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create a new Pull Request

License

The gem is available as open source under the terms of the MIT License.

About

Rails plugin to dry-initializer gem

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages