Module: ActiveInteractor::Context::Attributes

Included in:
Base
Defined in:
lib/active_interactor/context/attributes.rb

Overview

Context attribute methods. Because Attributes is a module classes should include Attributes rather than inherit from it.

Author:

Since:

  • 0.1.4

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#attribute?(attr_name) ⇒ Boolean Also known as: has_attribute?

Check if the context instance has an attribute

Parameters:

  • attr_name (Symbol, String)

    the name of the attribute to check

Returns:

  • (Boolean)

    whether or not the context instance has the attribute

Since:

  • 1.0.1



90
91
92
# File 'lib/active_interactor/context/attributes.rb', line 90

def attribute?(attr_name)
  @attributes.key?(attr_name.to_s)
end

#attributesHash{Symbol => *}

Get values defined on the instance of context whose keys are defined on the context class' .attributes

Examples:

Get attributes defined on an instance of context

class MyContext < ActiveInteractor::Context::Base
  attributes :first_name, :last_name
end

context = MyContext.new(first_name: 'Aaron', last_name: 'Allen', occupation: 'Ruby Nerd')
#=> <#MyContext first_name='Aaron' last_name='Allen' occupation='Ruby Nerd')

context.attributes
#=> { first_name: 'Aaron', last_name: 'Allen' }

context.occupation
#=> 'Ruby Nerd'

Returns:

  • (Hash{Symbol => *})

    the defined attributes and values

Since:

  • 0.1.4



80
81
82
# File 'lib/active_interactor/context/attributes.rb', line 80

def attributes
  super.symbolize_keys
end

#initialize(context = {}) ⇒ Base

Initialize a new instance of Base

Parameters:

  • context (Hash, Base, Class) (defaults to: {})

    attributes to assign to the context

Returns:

Since:

  • 0.1.4



52
53
54
55
56
57
58
59
60
# File 'lib/active_interactor/context/attributes.rb', line 52

def initialize(context = {})
  merge_errors!(context.errors) if context.respond_to?(:errors)
  copy_flags!(context)
  copy_called!(context)
  context = context_attributes_as_hash(context) || {}
  super

  merge_attribute_values(context)
end

#merge!(context) ⇒ self

Merge an instance of context into the calling context instance

Examples:

context = MyContext.new(first_name: 'Aaron', last_name: 'Allen')
other_context = MyContext.new(last_name: 'Awesome')
context.merge!(other_context)
#=> <#MyContext first_name='Aaron' last_name='Awesome'>

Parameters:

  • context (Class)

    a context instance to be merged

Returns:

Since:

  • 1.0.0



107
108
109
110
111
112
113
114
# File 'lib/active_interactor/context/attributes.rb', line 107

def merge!(context)
  merge_errors!(context.errors) if context.respond_to?(:errors)
  copy_flags!(context)
  context.each_pair do |key, value|
    public_send("#{key}=", value) unless value.nil?
  end
  self
end