Skip to content

Commit

Permalink
Allow ActionController::Parameters as inputs
Browse files Browse the repository at this point in the history
This fixes #381.
  • Loading branch information
tfausak committed Sep 8, 2016
1 parent b906f91 commit ae3a864
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/active_interaction/base.rb
Expand Up @@ -169,8 +169,7 @@ def eagerly_evaluate_default(filter)
#
# @private
def initialize(inputs = {})
raise ArgumentError, 'inputs must be a hash' unless inputs.is_a?(Hash)

inputs = normalize_inputs!(inputs)
process_inputs(inputs.symbolize_keys)
end

Expand Down Expand Up @@ -234,6 +233,22 @@ def run_validations!

private

# We want to allow both `Hash` objects and `ActionController::Parameters`
# objects. In Rails < 5, parameters are a subclass of hash and calling
# `#symbolize_keys` returns the entire hash, not just permitted values. In
# Rails >= 5, parameters are not a subclass of hash but calling
# `#to_unsafe_h` returns the entire hash.
def normalize_inputs!(inputs)
return inputs if inputs.is_a?(Hash)

klass = 'ActionController::Parameters'.safe_constantize
if !klass || !inputs.is_a?(klass)
raise ArgumentError, 'inputs must be a hash'
end

inputs.to_unsafe_h
end

# @param inputs [Hash{Symbol => Object}]
def process_inputs(inputs)
@_interaction_keys = inputs.keys.to_set & self.class.filters.keys
Expand Down
17 changes: 17 additions & 0 deletions spec/active_interaction/base_spec.rb
@@ -1,6 +1,7 @@
# coding: utf-8

require 'spec_helper'
require 'action_controller'

InteractionWithFilter = Class.new(TestInteraction) do
float :thing
Expand Down Expand Up @@ -58,6 +59,22 @@ def execute
end
end

context 'with non-hash inputs' do
let(:inputs) { [[:k, :v]] }

it 'raises an error' do
expect { interaction }.to raise_error ArgumentError
end
end

context 'with ActionController::Parameters inputs' do
let(:inputs) { ActionController::Parameters.new }

it 'does not raise an error' do
expect { interaction }.to_not raise_error
end
end

context 'with a reader' do
let(:described_class) do
Class.new(TestInteraction) do
Expand Down

0 comments on commit ae3a864

Please sign in to comment.