Module: Spira::ActiveRecordIsomorphisms::ClassMethods

Defined in:
lib/spira/active_record_isomorphisms.rb

Instance Method Summary collapse

Instance Method Details

#isomorphic_with(ar_name, opts = {}) ⇒ Object

Define an isomorphism between a Spira model and an ActiveRecord model.

Parameters:

  • ar_name (Symbol)

    The name of the ActiveRecord model in snake_case

  • opts (Hash) (defaults to: {})

    a customizable set of options

Options Hash (opts):

  • :delegation (Boolean) — default: true

    Enable/disable delegation of attributes

Raises:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/spira/active_record_isomorphisms.rb', line 22

def isomorphic_with(ar_name, opts = {})
  raise NoDefaultVocabularyError, 'A default vocabulary must be set.' unless default_vocabulary

  # Define the foreign key property
  id_sym = id_getter(ar_name)
  if properties.keys.include? id_sym.to_s
    raise IsomorphismAlreadyDefinedError,
      "An isomorphism with #{ar_name} has already been established or the property #{id_sym} is already in use."
  end
  property id_sym, type: Spira::Types::Integer

  opts.reverse_merge!({ delegation: true })

  ar_class = model_class_for_sym(ar_name)
  define_spira_methods(ar_name, ar_class)
  define_active_record_methods(ar_name, ar_class)

  if opts[:delegation]
    define_spira_attr_delegations(ar_name, ar_class)
    define_active_record_attr_delegations(ar_name, ar_class)
  end
end