Class: AssociateJsonb::WithStoreAttribute::InstanceMethodsOnActivation

Inherits:
Module
  • Object
show all
Defined in:
lib/associate_jsonb/with_store_attribute.rb

Instance Method Summary collapse

Constructor Details

#initialize(mixin, store, attribute, key, is_array) ⇒ InstanceMethodsOnActivation

Returns a new instance of InstanceMethodsOnActivation.



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/associate_jsonb/with_store_attribute.rb', line 103

def initialize(mixin, store, attribute, key, is_array)
  is_array = !!(is_array && attribute.to_s =~ /_ids$/)
  on_attr_change =
     is_array \
      ? "write_attribute(:#{attribute}, Array(given))" \
      : "super(given)"
  if is_array
    mixin.class_eval "      def \#{attribute}\n        _read_attribute(:\#{attribute}) || []\n      end\n    CODE\n  end\n\n  mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1\n    def \#{store}=(given)\n      given = super(given || {}).with_indifferent_access\n      write_attribute(:\#{attribute}, given[\"\#{key}\"])\n      given[\"\#{key}\"] = \#{attribute} unless \#{attribute}.nil?\n      super(given)\n    end\n\n    def \#{attribute}=(given)\n      \#{on_attr_change}\n      value = \#{store}[\"\#{key}\"] = \#{attribute}\n      \#{store}.delete(\"\#{key}\") if value.nil?\n      _write_attribute(:\#{store}, \#{store})\n      value\n    end\n  CODE\nend\n", __FILE__, __LINE__ + 1